@cline/core 0.0.62 → 0.0.63

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,7 +1,7 @@
1
- import{createRequire as gf}from"node:module";var{defineProperty:w7,getOwnPropertyNames:kf}=Object;var nY=Object.prototype.hasOwnProperty;function aY($){return this[$]}var M=($,W,Z)=>{var Q=kf(W);for(let J of Q)if(!nY.call($,J)&&J!=="default")w7($,J,{get:aY.bind(W,J),enumerable:!0});if(Z){for(let J of Q)if(!nY.call(Z,J)&&J!=="default")w7(Z,J,{get:aY.bind(W,J),enumerable:!0});return Z}};var If=($)=>$;function xf($,W){this[$]=If.bind(null,W)}var w=($,W)=>{for(var Z in W)w7($,Z,{get:W[Z],enumerable:!0,configurable:!0,set:xf.bind(W,Z)})};var W2=($,W)=>()=>($&&(W=$($=0)),W);var oY=gf(import.meta.url);import{AGENT_UNEXPECTED_REASONING_TOKENS_EVENT as OL,captureAgentUnexpectedReasoningTokens as TV,SDK_ERROR_TELEMETRY_EVENT as zL}from"@cline/shared";function a($,W,Z){$?.capture({event:W,properties:Z})}function o9($){if(!$)return;return $.substring(0,qL)}function ML($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function RL($){return typeof $==="string"?$:$.message}function LV($,W){return $.some((Z)=>W.has(Z.trim().toLowerCase()))}function OV($){a($,v.CLIENT.EXTENSION_ACTIVATED)}function s9($,W){let Z=[...W.vcs_types],Q={root_count:W.root_count,vcs_types:Z,is_multi_root:W.root_count>1,has_git:LV(Z,new Set(["git"])),has_mercurial:LV(Z,new Set(["mercurial","hg"]))};if(W.init_duration_ms!==void 0)Q.init_duration_ms=W.init_duration_ms;if(W.feature_flag_enabled!==void 0)Q.feature_flag_enabled=W.feature_flag_enabled;if(W.is_remote_workspace!==void 0)Q.is_remote_workspace=W.is_remote_workspace;a($,v.WORKSPACE.INITIALIZED,Q)}function t9($,W,Z){a($,v.WORKSPACE.INIT_ERROR,{error_type:ML(W),error_message:o9(RL(W)),fallback_to_single_root:Z.fallback_to_single_root,workspace_count:Z.workspace_count??0})}function zV($,W){a($,v.WORKSPACE.PATH_RESOLVED,{...W})}function g1($,W){a($,v.USER.AUTH_STARTED,{provider:W})}function m1($,W){a($,v.USER.AUTH_SUCCEEDED,{provider:W})}function v1($,W,Z){a($,v.USER.AUTH_FAILED,{provider:W,errorMessage:o9(Z)})}function L$($,W,Z,Q){a($,v.USER.AUTH_LOGGED_OUT,{provider:W,reason:Z,status:Q?.status,errorCode:Q?.errorCode})}function d7($,W,Z){a($,v.USER.AUTH_REFRESH_SOFT_FAILURE,{provider:W,status:Z?.status,errorCode:Z?.errorCode,errorName:Z?.errorName,tokenExpired:Z?.tokenExpired})}function qV($,W){a($,v.USER.PROVIDER_CONFIGURED,{provider:W})}function MV($,W){$?.captureRequired(v.USER.TELEMETRY_OPT_OUT,W)}function c1($,W){let Z=W.id?.trim();if(Z)$?.setDistinctId(Z);$?.updateCommonProperties({user_id:Z||W.id,account_id:W.id,account_email:W.email,provider:W.provider,organization_id:W.organizationId,organization_name:W.organizationName,member_id:W.memberId})}function e9($,W){a($,v.TASK.CREATED,W)}function $W($,W){a($,v.TASK.RESTARTED,W)}function Y4($,W){a($,v.TASK.COMPLETED,W)}function L8($,W){a($,v.TASK.CONVERSATION_TURN,{...W,timestamp:new Date().toISOString()})}function WW($,W){a($,v.TASK.TOKEN_USAGE,W)}function ZW($,W,Z){a($,v.TASK.MODE_SWITCH,{ulid:W,mode:Z})}function T8($,W){a($,v.TASK.TOOL_USED,W)}function QW($,W){a($,v.TASK.SKILL_USED,W)}function JW($,W){a($,v.TASK.DIFF_EDIT_FAILED,W)}function V4($,W){a($,v.TASK.PROVIDER_API_ERROR,{...W,errorMessage:o9(W.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function RV($,W){a($,v.SDK.TOOL_TIMEOUT,EL(W))}function EL($){let W={};for(let[Z,Q]of Object.entries($))if(Q!==void 0)W[Z]=Q;return W}function jW($,W,Z){a($,v.TASK.MENTION_USED,{mentionType:W,contentLength:Z,timestamp:new Date().toISOString()})}function XW($,W,Z,Q){a($,v.TASK.MENTION_FAILED,{mentionType:W,errorType:Z,errorMessage:o9(Q),timestamp:new Date().toISOString()})}function YW($,W,Z,Q,J){a($,v.TASK.MENTION_SEARCH_RESULTS,{queryLength:W.length,resultCount:Z,searchType:Q,isEmpty:J,timestamp:new Date().toISOString()})}function T$($,W){a($,v.TASK.AGENT_CREATED,{...W,timestamp:new Date().toISOString()})}function VW($,W){a($,v.TASK.AGENT_TEAM_CREATED,{...W,timestamp:new Date().toISOString()})}function B4($,W){a($,W.event==="ended"?v.TASK.SUBAGENT_COMPLETED:v.TASK.SUBAGENT_STARTED,{...W,timestamp:new Date().toISOString()})}function BW($,W,Z,Q){a($,v.HOOKS.DISCOVERY_COMPLETED,{hookName:W,globalCount:Z,workspaceCount:Q,totalCount:Z+Q,timestamp:new Date().toISOString()})}function HW($,W){a($,v.TASK.COMPACTION_EXECUTED,{...W,timestamp:new Date().toISOString()})}function GW($,W){a($,v.TASK.COMPACTION_SKIPPED,{...W,timestamp:new Date().toISOString()})}function EV($,W){a($,v.TASK.COMPACTION_BUDGET_EMERGENCY,{...W,timestamp:new Date().toISOString()})}var qL=500,v;var R0=W2(()=>{v={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},AGENT:{UNEXPECTED_REASONING_TOKENS:OL},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",AUTH_REFRESH_SOFT_FAILURE:"user.auth_refresh_soft_failure",PROVIDER_CONFIGURED:"user.provider_configured",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed",COMPACTION_EXECUTED:"task.compaction_executed",COMPACTION_SKIPPED:"task.compaction_skipped",COMPACTION_BUDGET_EMERGENCY:"task.compaction_budget_emergency"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:zL,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as NL,readFileSync as wL,statSync as CL,writeFileSync as PL}from"node:fs";import{dirname as SL}from"node:path";import{resolveGlobalSettingsPath as wV}from"@cline/shared/storage";import{z as j2}from"zod";function KW(){return H4.parse({})}function yL(){FW=void 0}function hL($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function kL($){let W;try{W=wL($,"utf8")}catch{return KW()}try{let Z=H4.safeParse(JSON.parse(W));return Z.success?Z.data:KW()}catch{return KW()}}function IL(){let $=wV(),W=CL($,{throwIfNoEntry:!1}),Z=W?.mtimeMs??0,Q=W?.size??0,J=FW;if(J&&J.path===$&&J.mtimeMs===Z&&J.size===Q)return J;let j=hL(W?kL($):KW());return FW={path:$,mtimeMs:Z,size:Q,value:j},FW}function E0(){return IL().value}function f1($,W={}){let Z=wV(),Q=E0();NL(SL(Z),{recursive:!0});let J=H4.parse($);if(!Q.telemetryOptOut&&J.telemetryOptOut)MV(W.telemetry);PL(Z,`${JSON.stringify(J,null,2)}
2
- `,"utf8"),yL()}function AW(){return E0().telemetryOptOut}function CV($,W={}){f1({...E0(),telemetryOptOut:$},W)}function PV(){return E0().autoUpdateEnabled}function SV($,W={}){f1({...E0(),autoUpdateEnabled:$},W)}function bV(){return E0().compactionStrategy??"basic"}function yV($){f1({...E0(),compactionStrategy:$})}function L1($){return new Set($??E0().disabledTools??[])}function G4($){return new Set($??E0().disabledPlugins??[])}function hV($){return L1().has($)}function UW($){let W=E0(),Z=new Set(W.disabledTools??[]),Q=Z.has($);if(Q)Z.delete($);else Z.add($);return f1({...W,disabledTools:[...Z]}),!Q}function l7($,W){let Z=[...new Set($.map((j)=>j.trim()).filter(Boolean))];if(Z.length===0)return;let Q=E0(),J=L1(Q.disabledTools);for(let j of Z)if(W)J.add(j);else J.delete(j);f1({...Q,disabledTools:[...J]})}function kV($,W){return l7([$],W),W}function IV($){return G4().has($)}function xV($,W){let Z=$.trim();if(!Z)return;let Q=E0(),J=G4(Q.disabledPlugins);if(W)J.add(Z);else J.delete(Z);f1({...Q,disabledPlugins:[...J]})}function DW($,W){let Z=G4(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q))}function u1($,W){let Z=L1(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q.name))}function _W($,W){if(!$||$.length===0)return $;let Z=L1(W);if(Z.size===0)return $;return $.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(J,j)=>Q.setup?.({...J,registerTool:(X)=>{if(!Z.has(X.name))J.registerTool(X)}},j)}})}var NV,bL,H4,FW;var X1=W2(()=>{R0();NV=j2.preprocess(($)=>Array.isArray($)?$.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean):void 0,j2.array(j2.string()).optional()).transform(($)=>{if(!$)return;let W=[...new Set($)].sort((Z,Q)=>Z.localeCompare(Q));return W.length>0?W:void 0}),bL=j2.enum(["basic","agentic"]).catch("basic"),H4=j2.object({telemetryOptOut:j2.boolean().default(!1).catch(!1),autoUpdateEnabled:j2.boolean().default(!0).catch(!0),compactionStrategy:bL.optional(),disabledTools:NV.optional(),disabledPlugins:NV.optional()}).strip().transform(($)=>{let W={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.compactionStrategy)W.compactionStrategy=$.compactionStrategy;if($.disabledTools?.length)W.disabledTools=$.disabledTools;if($.disabledPlugins?.length)W.disabledPlugins=$.disabledPlugins;return W})});import{existsSync as xL,mkdirSync as gL,readFileSync as mL,writeFileSync as vL}from"node:fs";import{resolve as cL}from"node:path";import{resolveSessionDataDir as uL}from"@cline/shared/storage";import{nanoid as dL}from"nanoid";import*as lL from"node-machine-id";function x0($){let W=$?.trim();if(W)return W;let Z=iL();if(Z)return Z;return nL()}function rL(){let $=lL;return $.machineIdSync??$.default?.machineIdSync}function iL(){try{let $=rL();if(!$)return;return $().trim()||void 0}catch{return}}function nL(){let $=uL(),W=cL($,pL);try{if(xL(W)){let Q=mL(W,"utf8").trim();if(Q.length>0)return Q}}catch{}let Z=`cl-${dL()}`;try{gL($,{recursive:!0}),vL(W,Z,"utf8")}catch{}return Z}var pL="machine-id";var O8=()=>{};class F4{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,W){if(!this.isEnabled())return;this.emitLog($,W,!1)}emitRequired($,W){this.emitLog($,W,!0)}recordCounter($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.counters.get($);if(!j)j=this.meter.createCounter($,Q?{description:Q}:void 0),this.counters.set($,j);j.add(W,this.flattenProperties(this.buildAttributes(Z)))}recordHistogram($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.histograms.get($);if(!j)j=this.meter.createHistogram($,Q?{description:Q}:void 0),this.histograms.set($,j);j.record(W,this.flattenProperties(this.buildAttributes(Z)))}recordGauge($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.buildAttributes(Z),X=JSON.stringify(j),Y=this.gaugeValues.get($);if(W===null){if(Y){if(Y.delete(X),Y.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let V=Y;if(!V)V=new Map,this.gaugeValues.set($,V);if(!this.gauges.has($)){let B=this.meter.createObservableGauge($,Q?{description:Q}:void 0);B.addCallback((H)=>{for(let G of this.snapshotGaugeSeries($))H.observe(G.value,this.flattenProperties(G.attributes))}),this.gauges.set($,B)}V.set(X,{value:W,attributes:j})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,W,Z){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes(W,Z));this.logger.emit({severityText:"INFO",body:$,attributes:Q})}buildAttributes($,W=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...W?{_required:!0}:{}}}snapshotGaugeSeries($){let W=this.gaugeValues.get($);if(!W)return[];return Array.from(W.values(),(Z)=>({value:Z.value,attributes:Z.attributes?{...Z.attributes}:void 0}))}flattenProperties($,W="",Z=new WeakSet,Q=0){if(!$)return{};let J={},j=100,X=10;for(let[Y,V]of Object.entries($)){if(Y==="__proto__"||Y==="constructor"||Y==="prototype")continue;let B=W?`${W}.${Y}`:Y;if(V===null||V===void 0){J[B]=String(V);continue}if(Array.isArray(V)){let H=V.length>j?V.slice(0,j):V;try{J[B]=JSON.stringify(H)}catch{J[B]="[UnserializableArray]"}if(V.length>j)J[`${B}_truncated`]=!0,J[`${B}_original_length`]=V.length;continue}if(typeof V==="object"){if(V instanceof Date){J[B]=V.toISOString();continue}if(V instanceof Error){J[B]=V.message;continue}if(Z.has(V)){J[B]="[Circular]";continue}if(Q>=X){J[B]="[MaxDepthExceeded]";continue}Z.add(V),Object.assign(J,this.flattenProperties(V,B,Z,Q+1));continue}if(aL(V)){J[B]=V;continue}try{J[B]=JSON.stringify(V)}catch{J[B]=String(V)}}return J}}function aL($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class A4{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,W){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:W})}emitRequired($,W){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:W})}recordCounter($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordHistogram($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordGauge($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:W,attributes:Z,description:Q,required:J===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class z8{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new A4({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let W=this.buildAttributes($.properties);for(let Z of this.adapters)Z.emit($.event,W)}captureRequired($,W){let Z=this.buildAttributes(W);for(let Q of this.adapters)Q.emitRequired($,Z)}recordCounter($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordCounter($,W,j,Q,J)}recordHistogram($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordHistogram($,W,j,Q,J)}recordGauge($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordGauge($,W,j,Q,J)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var p7=()=>{};import{metrics as oL,trace as sL}from"@opentelemetry/api";import{logs as tL}from"@opentelemetry/api-logs";import{OTLPLogExporter as eL}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as $T}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as WT}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as ZT}from"@opentelemetry/resources";import{BatchLogRecordProcessor as QT,ConsoleLogRecordExporter as JT,LoggerProvider as jT}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as XT,MeterProvider as YT,PeriodicExportingMetricReader as gV}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as VT,ConsoleSpanExporter as BT,SimpleSpanProcessor as HT}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as GT}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as KT,ATTR_SERVICE_VERSION as FT}from"@opentelemetry/semantic-conventions";class mV{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,W){this.resolveProperties(W)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class q8{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let W=ZT({[KT]:$.serviceName??"cline",...$.serviceVersion?{[FT]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(W),this.loggerProvider=this.createLoggerProvider(W),this.tracerProvider=this.createTracerProvider(W),this.meterProvider)oL.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)tL.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",W){return sL.getTracer($,W??this.options.serviceVersion)}createAdapter($){return new F4({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let W=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new z8({...$,adapters:[W],distinctId:x0($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let W=r7(this.options.metricsExporter);if(W.length===0)return null;let Z=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(Z*0.8)),J=W.map((j)=>DT(j,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Z,timeout:Q})).filter((j)=>j!==null);if(J.length===0)return null;return new YT({resource:$,readers:J})}createTracerProvider($){let W=r7(this.options.tracesExporter);if(W.length===0)return null;let Z=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,J=[];for(let j of W){let X=UT(j,{endpoint:Z,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(X)J.push(X)}if(J.length===0)return null;return new GT({resource:$,spanProcessors:J})}createLoggerProvider($){let W=r7(this.options.logsExporter);if(W.length===0)return null;let Z=W.map((Q)=>{let J=AT(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!J)return null;return new QT(J,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(Z.length===0)return null;return new jT({resource:$,processors:Z})}}function U4($){let W=new q8($),Z=W.createTelemetryService($);return Z.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:W,telemetry:Z}}function d1($){if(AW())return{telemetry:new mV($)};if($.enabled!==!0)return{telemetry:new z8({...$,distinctId:x0($.distinctId)})};return U4($)}function M8($){let{telemetry:W,provider:Z}=d1($);return{telemetry:W,provider:Z,flush:async()=>{let j=Z;if(j&&typeof j.forceFlush==="function")try{await j.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([W.dispose(),Z?.dispose()])}}}function r7($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Z)=>Z.trim()).filter((Z)=>Z==="console"||Z==="otlp")}function AT($,W){if($==="console")return new JT;if(!W.endpoint)return null;let Z=i7(W.endpoint,"/v1/logs");return new eL({url:Z,headers:W.headers})}function UT($,W){if($==="console")return new HT(new BT);if(!W.endpoint)return null;let Z=i7(W.endpoint,"/v1/traces");return new VT(new WT({url:Z,headers:W.headers}))}function DT($,W){if($==="console")return new gV({exporter:new XT,exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout});if(!W.endpoint)return null;let Z=i7(W.endpoint,"/v1/metrics");return new gV({exporter:new $T({url:Z,headers:W.headers}),exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout})}function i7($,W){let Z=new URL($),Q=Z.pathname.endsWith("/")?Z.pathname.slice(0,-1):Z.pathname;return Z.pathname=Q.endsWith(W)?Q:`${Q}${W}`,Z.toString()}var fW=W2(()=>{X1();O8();p7()});var CG={};w(CG,{normalizeUserMessage:()=>bR,buildInitialUserContent:()=>SR});async function SR($,W,Z,Q){let J=yR(W),j=await kR(Z,Q);if(J.length===0&&!j)return $;let X=[{type:"text",text:$},...J];if(j)X.push(...j);return X}function bR($){if($==null)return"";if(typeof $==="string")return $;let W=$.content;if(typeof W==="string")return W;if(!Array.isArray(W))return"";let Z=[];for(let Q of W)if(Q&&typeof Q==="object"&&Q.type==="text"){let J=Q.text;if(typeof J==="string")Z.push(J)}return Z.join(`
3
- `)}function yR($){if(!$||$.length===0)return[];let W=[];for(let Z of $){let Q=hR(Z);if(Q)W.push(Q)}return W}function hR($){let W=$.trim();if(!W)return;let Z=W.match(/^data:([^;,]+);base64,(.+)$/);if(Z){let Q=Z[1],J=Z[2];if(!Q||!J)return;return{type:"image",mediaType:Q,data:J}}return{type:"image",mediaType:"image/png",data:W}}async function kR($,W){if(!$||$.length===0)return;let Z=W??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all($.map(async(J)=>{let j=J.replace(/\\/g,"/");try{let X=await Z(J);return{type:"file",path:j,content:X}}catch(X){let Y=X instanceof Error?X.message:String(X);return{type:"file",path:j,content:`Error fetching content: ${Y}`}}}));if(Q.length===0)return;return Q}var WA={};w(WA,{updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>T6,updateMcpServerOAuthStateAsync:()=>i5,updateMcpServerOAuthState:()=>i2,setMcpServerDisabled:()=>p2,resolveMcpServerRegistrations:()=>t0,resolveDefaultMcpSettingsPath:()=>J0,registerMcpServersFromSettingsFile:()=>n2,normalizeMcpServerOAuthState:()=>O6,loadMcpSettingsFile:()=>l2,listMcpServerOAuthStatuses:()=>n5,hasMcpSettingsFile:()=>X$,getMcpServerOAuthState:()=>r2,McpSettingsUpdateSkippedError:()=>L6,McpSettingsMutatorPurityError:()=>u$,McpSettingsLockTimeoutError:()=>d$});import{existsSync as vF,mkdirSync as Xj,readFileSync as cF,renameSync as Bj,rmdirSync as bC,rmSync as Yj,statSync as yC,unlinkSync as uF,writeFileSync as dF}from"node:fs";import{randomUUID as hC}from"node:crypto";import{dirname as lF,join as mF}from"node:path";import{setTimeout as kC}from"node:timers/promises";import{resolveMcpSettingsPath as IC}from"@cline/shared/storage";import{z as S}from"zod";function Vj($){if(!$)return;if($==="http")return"streamableHttp";return $}function J0(){return IC()}function iC($,W){Xj(lF($),{recursive:!0});let Z=`${$}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{dF(Z,W,{encoding:"utf8",flag:"wx"}),Bj(Z,$)}catch(Q){try{uF(Z)}catch{}throw Q}}function aC($){Atomics.wait(nC,0,0,$)}function oC($){return`${$}.lock`}function nF(){return`${process.pid}.${Date.now()}.${hC()}`}function aF($,W){Xj(lF($),{recursive:!0});let Z=`${$}.tmp.${W}`;Yj(Z,{recursive:!0,force:!0}),Xj(Z,{recursive:!0}),dF(mF(Z,`owner.${W}`),W,{encoding:"utf8",flag:"wx"});try{return Bj(Z,$),{lockDir:$,ownerFile:mF($,`owner.${W}`)}}catch(Q){if(Yj(Z,{recursive:!0,force:!0}),vF($))return;throw Q}}function oF($,W){let Z;try{Z=Date.now()-yC($).mtimeMs}catch(J){if(J.code==="ENOENT")return;throw J}if(Z<Gj)return;W.logger?.log(`[mcp-settings] Stale lock directory at ${$} (age ${Z}ms); reclaiming.`,{severity:"warn"});let Q=`${$}.stale.${nF()}`;try{Bj($,Q)}catch(J){if(J.code==="ENOENT")return;throw J}Yj(Q,{recursive:!0,force:!0})}function sC($){try{uF($.ownerFile)}catch(W){if(W.code!=="ENOENT")throw W}try{bC($.lockDir)}catch(W){let Z=W.code;if(Z!=="ENOENT"&&Z!=="ENOTEMPTY"&&Z!=="EEXIST")throw W}}function sF($){let W=oC($);if(YQ.has(W))throw Error(`Reentrant MCP settings update for ${$}. Keep mutators pure: compute values up front and do not call back into the settings API.`);return{lockDir:W,token:nF()}}function tC($,W){let{lockDir:Z,token:Q}=sF($),J=W.timeoutMs??Gj,j=Date.now();while(!0){let X=aF(Z,Q);if(X)return YQ.add(Z),X;if(Date.now()-j>J)throw new d$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);oF(Z,W),aC(iF)}}async function eC($,W){let{lockDir:Z,token:Q}=sF($),J=W.timeoutMs??Gj,j=Date.now();while(!0){let X=aF(Z,Q);if(X)return YQ.add(Z),X;if(Date.now()-j>J)throw new d$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);oF(Z,W),await kC(iF)}}function tF($,W,Z){try{let Q=$P(W),J=WP(Q,Z);return iC(W,`${JSON.stringify(Q,null,2)}
4
- `),J}finally{YQ.delete($.lockDir),sC($)}}function A1($,W,Z={}){let Q=tC($,Z);return tF(Q,$,W)}async function T6($,W,Z={}){let Q=await eC($,Z);return tF(Q,$,W)}function $P($){let W=QP($);if(!W.mcpServers||typeof W.mcpServers!=="object"||Array.isArray(W.mcpServers))W.mcpServers={};return W}function WP($,W){let Z=JSON.stringify($),Q=JSON.parse(Z),J=W(Q),j=JSON.stringify(Q),X=W($);if(JSON.stringify($)!==j)throw new u$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different settings.");if(JSON.stringify(X)!==JSON.stringify(J))throw new u$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different return values.");return X}function ZP($){let W=cF($,"utf8"),Z;try{Z=JSON.parse(W)}catch(Q){let J=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${J}`)}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Z}function QP($){try{return ZP($)}catch(W){if(W.code==="ENOENT")return{};throw W}}function eF($,W){if(!Object.hasOwn($,W))return;let Z=$[W];if(!Z||typeof Z!=="object"||Array.isArray(Z))return;return Z}function JP($,W,Z){Object.defineProperty($,W,{value:Z,enumerable:!0,configurable:!0,writable:!0})}function l2($={}){let W=$.filePath??J0(),Z=cF(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(j){let X=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${W}": ${X}`)}let J=rC.safeParse(Q);if(!J.success){let j=J.error.issues.map((X)=>{let Y=X.path.join(".");return Y?`${Y}: ${X.message}`:X.message}).join("; ");throw Error(`Invalid MCP settings at "${W}": ${j}`)}return J.data}function O6($){if(!$)return;let W={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(W).length>0?W:void 0}function jP($){if($===void 0)return;let W=Hj.safeParse($);if(!W.success)return;return O6(W.data)}function X$($={}){let W=$.filePath??J0();return vF(W)}function t0($={}){let W=l2($);return Object.entries(W.mcpServers).map(([Z,Q])=>({name:Z,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function p2($){let W=$.filePath??J0(),Z=$.name.trim();if(!Z)throw Error("MCP server settings toggle requires a server name.");A1(W,(Q)=>{let J=Q.mcpServers;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${W}": mcpServers must be an object.`);let j={...J},X=eF(j,Z);if(!X)throw Error(`Unknown MCP server: ${Z}`);let Y={...X};if($.disabled)Y.disabled=!0;else delete Y.disabled;JP(j,Z,Y),Q.mcpServers=j})}function r2($,W={}){let Z=l2(W);if(!Object.hasOwn(Z.mcpServers,$))return;return O6(Z.mcpServers[$]?.oauth)}function $A($,W){return(Z)=>{let Q=Z.mcpServers,J=eF(Q,$);if(!J)throw Error(`Unknown MCP server: ${$}`);let j=jP(J.oauth)??{},X=O6(W(j));if(X)J.oauth=X;else delete J.oauth;return X??{}}}function i2($,W,Z={}){let Q=Z.filePath??J0();return A1(Q,$A($,W))}async function i5($,W,Z={}){let Q=Z.filePath??J0();return T6(Q,$A($,W))}function n5($={}){return t0($).map((Z)=>{let Q=Z.transport.type!=="stdio",J=Z.oauth?.tokens?.access_token;return{serverName:Z.name,oauthSupported:Q,oauthConfigured:Q&&typeof J==="string"&&J.trim().length>0,lastError:Z.oauth?.lastError,lastAuthenticatedAt:Z.oauth?.lastAuthenticatedAt}}).sort((Z,Q)=>Z.serverName.localeCompare(Q.serverName))}async function n2($,W={}){let Z=t0(W);for(let Q of Z)await $.registerServer(Q);return Z}var r5,pF,Hj,xC,gC,mC,vC,cC,uC,rF,dC,lC,pC,rC,L6,d$,u$,Gj=1e4,iF=25,nC,YQ;var VQ=W2(()=>{r5=S.record(S.string(),S.string()),pF=S.record(S.string(),S.unknown()),Hj=S.object({clientInformation:S.record(S.string(),S.unknown()).optional(),tokens:S.record(S.string(),S.unknown()).optional(),codeVerifier:S.string().optional(),discoveryState:S.record(S.string(),S.unknown()).optional(),redirectUrl:S.string().url().optional(),lastError:S.string().optional(),lastAuthenticatedAt:S.number().int().positive().optional()}).strip(),xC=S.object({type:S.literal("stdio"),command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:r5.optional()}),gC=S.object({type:S.literal("sse"),url:S.string().url(),headers:r5.optional()}),mC=S.object({type:S.literal("streamableHttp"),url:S.string().url(),headers:r5.optional()}),vC=S.discriminatedUnion("type",[xC,gC,mC]),cC=S.object({transport:vC,disabled:S.boolean().optional(),metadata:pF.optional(),oauth:Hj.optional()}),uC=S.enum(["stdio","sse","http","streamableHttp"]).optional(),rF=S.object({type:S.enum(["stdio","sse","streamableHttp"]).optional(),transportType:uC,disabled:S.boolean().optional(),metadata:pF.optional(),oauth:Hj.optional()});dC=rF.extend({command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:r5.optional()}).superRefine(($,W)=>{let Z=$.type??Vj($.transportType);if(Z&&Z!=="stdio")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),lC=rF.extend({url:S.string().url(),headers:r5.optional()}).superRefine(($,W)=>{let Z=$.type??Vj($.transportType)??"sse";if(Z!=="sse"&&Z!=="streamableHttp")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??Vj($.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth};return{transport:{type:"sse",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth}}),pC=S.union([cC,dC,lC]),rC=S.object({mcpServers:S.record(S.string(),pC)}).passthrough();L6=class L6 extends Error{constructor($){super($);this.name="McpSettingsUpdateSkippedError"}};d$=class d$ extends Error{constructor($){super($);this.name="McpSettingsLockTimeoutError"}};u$=class u$ extends Error{constructor($){super($);this.name="McpSettingsMutatorPurityError"}};nC=new Int32Array(new SharedArrayBuffer(4)),YQ=new Set});var nU={};w(nU,{resolveCoreDistinctId:()=>x0,createOpenTelemetryTelemetryService:()=>U4,createConfiguredTelemetryService:()=>d1,createConfiguredTelemetryHandle:()=>M8,OpenTelemetryProvider:()=>q8,OpenTelemetryAdapter:()=>F4});var bQ=W2(()=>{O8();fW()});var T_={};w(T_,{writeHubDiscovery:()=>OW,withHubStartupLock:()=>zW,verifyHubConnection:()=>z1,truncateNotificationBody:()=>k9,toHubStatusUrl:()=>s7,toHubHealthUrl:()=>qW,stopLocalHubServerGracefully:()=>B3,startHubWebSocketServer:()=>g9,startHubServer:()=>f_,spawnDetachedHubServerWithRetry:()=>N8,spawnDetachedHubServer:()=>Q3,sendHubCommand:()=>AB,restartLocalHubIfIdleAfterStartupTimeout:()=>wW,resolveWorkspaceHubOwnerContext:()=>sV,resolveSharedHubOwnerContext:()=>V1,resolveProductionHubOwnerContext:()=>O1,resolveHubUrl:()=>H3,resolveHubOwnerContext:()=>r1,resolveHubEndpointOptions:()=>T1,resolveHubBuildId:()=>TW,resolveDefaultHubPort:()=>E8,resolveDefaultHubPathname:()=>Z3,resolveDefaultHubHost:()=>W3,resolveCompatibleLocalHubUrl:()=>T4,resolveClineDir:()=>iV,resolveClineDataDir:()=>Y2,requestHubShutdown:()=>L4,rememberRecoverableLocalHubUrl:()=>O$,readHubDiscovery:()=>D0,readBearerToken:()=>f7,probeHubServer:()=>i1,probeHubConnection:()=>FB,prewarmDetachedHubServer:()=>RW,normalizeHubWebSocketUrl:()=>z$,isLocalHubOrigin:()=>AY,isLocalHubHostName:()=>L7,isHubReconnectableTransportError:()=>Y3,isHubCommandTimeoutError:()=>NW,isDiscoveryFilePresent:()=>aV,ensureHubWebSocketServer:()=>T7,ensureHubServer:()=>L_,ensureDetachedHubServer:()=>QB,ensureCompatibleLocalHubUrl:()=>H2,createLocalHubScheduleRuntimeHandlers:()=>__,createInMemoryHubOwnerContext:()=>nV,createHubServerUrl:()=>Y1,createHubAuthToken:()=>LW,createConfiguredTelemetryService:()=>d1,createConfiguredTelemetryHandle:()=>M8,connectToHub:()=>CW,clearHubDiscovery:()=>g0,NodeHubClient:()=>B1,NativeHubTransportAdapter:()=>x9,HubUIClient:()=>F3,HubTransportError:()=>y0,HubSessionClient:()=>K3,HubServerTransport:()=>o6,HubScheduleService:()=>f8,HubScheduleCommandService:()=>A8,HubCommandError:()=>w8,DEFAULT_HUB_PORT:()=>e7,DEFAULT_HUB_PATHNAME:()=>$3,DEFAULT_HUB_HOST:()=>t7,BrowserWebSocketHubAdapter:()=>I9});import{createSessionId as mf}from"@cline/shared";function p0($,W){return{version:$.version,requestId:$.requestId,ok:!0,payload:W}}function sY($,W,Z){return{version:$.version,requestId:$.requestId??mf("hubreq_"),ok:!1,error:{code:W,message:Z}}}class A8{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return p0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return p0($,{schedules:this.schedules.listSchedules({enabled:typeof $.payload?.enabled==="boolean"?$.payload.enabled:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0,tags:Array.isArray($.payload?.tags)?$.payload?.tags:void 0})});case"schedule.get":return p0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return p0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return p0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return p0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return p0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return p0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return p0($,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof $.payload?.scheduleId==="string"?$.payload.scheduleId:void 0,status:typeof $.payload?.status==="string"?$.payload.status:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0})});case"schedule.stats":return p0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return p0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return p0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return sY($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(W){return sY($,"schedule_command_failed",W instanceof Error?W.message:String(W))}}toCreateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:W}}toUpdateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:W}}}class e6{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},W=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of W)if(this.materializeOneOff(Q))$.oneOffQueued+=1;let Z=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of Z)try{if(this.materializeSchedule(Q))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as af}from"node:path";import{buildClineSystemPrompt as of}from"@cline/shared";import{nowIso as YV}from"@cline/shared/db";var O0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},D$=[O0.READ_FILES,O0.SEARCH_CODEBASE,O0.RUN_COMMANDS,O0.FETCH_WEB_CONTENT,O0.APPLY_PATCH,O0.EDITOR,O0.SKILLS,O0.ASK,O0.SUBMIT_AND_EXIT];var eY={};w(eY,{mergeRulesForSystemPrompt:()=>D8,loadRulesForSystemPromptFromWatcher:()=>C7,listEnabledRulesFromWatcher:()=>tY,isRuleEnabled:()=>l9,formatRulesForSystemPrompt:()=>U8});function l9($){return $.disabled!==!0}function U8($){if($.length===0)return"";return`
1
+ import{createRequire as mf}from"node:module";var{defineProperty:C7,getOwnPropertyNames:If}=Object;var aY=Object.prototype.hasOwnProperty;function oY($){return this[$]}var M=($,W,Z)=>{var Q=If(W);for(let J of Q)if(!aY.call($,J)&&J!=="default")C7($,J,{get:oY.bind(W,J),enumerable:!0});if(Z){for(let J of Q)if(!aY.call(Z,J)&&J!=="default")C7(Z,J,{get:oY.bind(W,J),enumerable:!0});return Z}};var xf=($)=>$;function gf($,W){this[$]=xf.bind(null,W)}var w=($,W)=>{for(var Z in W)C7($,Z,{get:W[Z],enumerable:!0,configurable:!0,set:gf.bind(W,Z)})};var W2=($,W)=>()=>($&&(W=$($=0)),W);var sY=mf(import.meta.url);import{AGENT_UNEXPECTED_REASONING_TOKENS_EVENT as zL,captureAgentUnexpectedReasoningTokens as OV,SDK_ERROR_TELEMETRY_EVENT as qL}from"@cline/shared";function n($,W,Z){$?.capture({event:W,properties:Z})}function o9($){if(!$)return;return $.substring(0,ML)}function RL($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function EL($){return typeof $==="string"?$:$.message}function TV($,W){return $.some((Z)=>W.has(Z.trim().toLowerCase()))}function zV($){n($,v.CLIENT.EXTENSION_ACTIVATED)}function s9($,W){let Z=[...W.vcs_types],Q={root_count:W.root_count,vcs_types:Z,is_multi_root:W.root_count>1,has_git:TV(Z,new Set(["git"])),has_mercurial:TV(Z,new Set(["mercurial","hg"]))};if(W.init_duration_ms!==void 0)Q.init_duration_ms=W.init_duration_ms;if(W.feature_flag_enabled!==void 0)Q.feature_flag_enabled=W.feature_flag_enabled;if(W.is_remote_workspace!==void 0)Q.is_remote_workspace=W.is_remote_workspace;n($,v.WORKSPACE.INITIALIZED,Q)}function t9($,W,Z){n($,v.WORKSPACE.INIT_ERROR,{error_type:RL(W),error_message:o9(EL(W)),fallback_to_single_root:Z.fallback_to_single_root,workspace_count:Z.workspace_count??0})}function qV($,W){n($,v.WORKSPACE.PATH_RESOLVED,{...W})}function g1($,W){n($,v.USER.AUTH_STARTED,{provider:W})}function m1($,W){n($,v.USER.AUTH_SUCCEEDED,{provider:W})}function v1($,W,Z){n($,v.USER.AUTH_FAILED,{provider:W,errorMessage:o9(Z)})}function L$($,W,Z,Q){n($,v.USER.AUTH_LOGGED_OUT,{provider:W,reason:Z,status:Q?.status,errorCode:Q?.errorCode})}function l7($,W,Z){n($,v.USER.AUTH_REFRESH_SOFT_FAILURE,{provider:W,status:Z?.status,errorCode:Z?.errorCode,errorName:Z?.errorName,tokenExpired:Z?.tokenExpired})}function MV($,W){n($,v.USER.PROVIDER_CONFIGURED,{provider:W})}function RV($,W){$?.captureRequired(v.USER.TELEMETRY_OPT_OUT,W)}function c1($,W){let Z=W.id?.trim();if(Z)$?.setDistinctId(Z);$?.updateCommonProperties({user_id:Z||W.id,account_id:W.id,account_email:W.email,provider:W.provider,organization_id:W.organizationId,organization_name:W.organizationName,member_id:W.memberId})}function e9($,W){n($,v.TASK.CREATED,W)}function $W($,W){n($,v.TASK.RESTARTED,W)}function Y4($,W){n($,v.TASK.COMPLETED,W)}function L8($,W){n($,v.TASK.CONVERSATION_TURN,{...W,timestamp:new Date().toISOString()})}function WW($,W){n($,v.TASK.TOKEN_USAGE,W)}function ZW($,W,Z){n($,v.TASK.MODE_SWITCH,{ulid:W,mode:Z})}function T8($,W){n($,v.TASK.TOOL_USED,W)}function QW($,W){n($,v.TASK.SKILL_USED,W)}function JW($,W){n($,v.TASK.DIFF_EDIT_FAILED,W)}function V4($,W){n($,v.TASK.PROVIDER_API_ERROR,{...W,errorMessage:o9(W.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function jW($,W){n($,v.TASK.MISTAKE_LIMIT_REACHED,{...W,timestamp:new Date().toISOString()})}function EV($,W){n($,v.SDK.TOOL_TIMEOUT,NL(W))}function NL($){let W={};for(let[Z,Q]of Object.entries($))if(Q!==void 0)W[Z]=Q;return W}function XW($,W,Z){n($,v.TASK.MENTION_USED,{mentionType:W,contentLength:Z,timestamp:new Date().toISOString()})}function YW($,W,Z,Q){n($,v.TASK.MENTION_FAILED,{mentionType:W,errorType:Z,errorMessage:o9(Q),timestamp:new Date().toISOString()})}function VW($,W,Z,Q,J){n($,v.TASK.MENTION_SEARCH_RESULTS,{queryLength:W.length,resultCount:Z,searchType:Q,isEmpty:J,timestamp:new Date().toISOString()})}function T$($,W){n($,v.TASK.AGENT_CREATED,{...W,timestamp:new Date().toISOString()})}function BW($,W){n($,v.TASK.AGENT_TEAM_CREATED,{...W,timestamp:new Date().toISOString()})}function B4($,W){n($,W.event==="ended"?v.TASK.SUBAGENT_COMPLETED:v.TASK.SUBAGENT_STARTED,{...W,timestamp:new Date().toISOString()})}function HW($,W,Z,Q){n($,v.HOOKS.DISCOVERY_COMPLETED,{hookName:W,globalCount:Z,workspaceCount:Q,totalCount:Z+Q,timestamp:new Date().toISOString()})}function GW($,W){n($,v.TASK.COMPACTION_EXECUTED,{...W,timestamp:new Date().toISOString()})}function KW($,W){n($,v.TASK.COMPACTION_SKIPPED,{...W,timestamp:new Date().toISOString()})}function NV($,W){n($,v.TASK.COMPACTION_BUDGET_EMERGENCY,{...W,timestamp:new Date().toISOString()})}var ML=500,v;var z0=W2(()=>{v={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},AGENT:{UNEXPECTED_REASONING_TOKENS:zL},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",AUTH_REFRESH_SOFT_FAILURE:"user.auth_refresh_soft_failure",PROVIDER_CONFIGURED:"user.provider_configured",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MISTAKE_LIMIT_REACHED:"task.mistake_limit_reached",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed",COMPACTION_EXECUTED:"task.compaction_executed",COMPACTION_SKIPPED:"task.compaction_skipped",COMPACTION_BUDGET_EMERGENCY:"task.compaction_budget_emergency"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:qL,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as wL,readFileSync as CL,statSync as PL,writeFileSync as SL}from"node:fs";import{dirname as bL}from"node:path";import{resolveGlobalSettingsPath as CV}from"@cline/shared/storage";import{z as j2}from"zod";function FW(){return H4.parse({})}function hL(){AW=void 0}function kL($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function IL($){let W;try{W=CL($,"utf8")}catch{return FW()}try{let Z=H4.safeParse(JSON.parse(W));return Z.success?Z.data:FW()}catch{return FW()}}function xL(){let $=CV(),W=PL($,{throwIfNoEntry:!1}),Z=W?.mtimeMs??0,Q=W?.size??0,J=AW;if(J&&J.path===$&&J.mtimeMs===Z&&J.size===Q)return J;let j=kL(W?IL($):FW());return AW={path:$,mtimeMs:Z,size:Q,value:j},AW}function E0(){return xL().value}function f1($,W={}){let Z=CV(),Q=E0();wL(bL(Z),{recursive:!0});let J=H4.parse($);if(!Q.telemetryOptOut&&J.telemetryOptOut)RV(W.telemetry);SL(Z,`${JSON.stringify(J,null,2)}
2
+ `,"utf8"),hL()}function UW(){return E0().telemetryOptOut}function PV($,W={}){f1({...E0(),telemetryOptOut:$},W)}function SV(){return E0().autoUpdateEnabled}function bV($,W={}){f1({...E0(),autoUpdateEnabled:$},W)}function yV(){return E0().compactionStrategy??"basic"}function hV($){f1({...E0(),compactionStrategy:$})}function L1($){return new Set($??E0().disabledTools??[])}function G4($){return new Set($??E0().disabledPlugins??[])}function kV($){return L1().has($)}function DW($){let W=E0(),Z=new Set(W.disabledTools??[]),Q=Z.has($);if(Q)Z.delete($);else Z.add($);return f1({...W,disabledTools:[...Z]}),!Q}function p7($,W){let Z=[...new Set($.map((j)=>j.trim()).filter(Boolean))];if(Z.length===0)return;let Q=E0(),J=L1(Q.disabledTools);for(let j of Z)if(W)J.add(j);else J.delete(j);f1({...Q,disabledTools:[...J]})}function IV($,W){return p7([$],W),W}function xV($){return G4().has($)}function gV($,W){let Z=$.trim();if(!Z)return;let Q=E0(),J=G4(Q.disabledPlugins);if(W)J.add(Z);else J.delete(Z);f1({...Q,disabledPlugins:[...J]})}function _W($,W){let Z=G4(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q))}function u1($,W){let Z=L1(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q.name))}function fW($,W){if(!$||$.length===0)return $;let Z=L1(W);if(Z.size===0)return $;return $.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(J,j)=>Q.setup?.({...J,registerTool:(X)=>{if(!Z.has(X.name))J.registerTool(X)}},j)}})}var wV,yL,H4,AW;var X1=W2(()=>{z0();wV=j2.preprocess(($)=>Array.isArray($)?$.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean):void 0,j2.array(j2.string()).optional()).transform(($)=>{if(!$)return;let W=[...new Set($)].sort((Z,Q)=>Z.localeCompare(Q));return W.length>0?W:void 0}),yL=j2.enum(["basic","agentic"]).catch("basic"),H4=j2.object({telemetryOptOut:j2.boolean().default(!1).catch(!1),autoUpdateEnabled:j2.boolean().default(!0).catch(!0),compactionStrategy:yL.optional(),disabledTools:wV.optional(),disabledPlugins:wV.optional()}).strip().transform(($)=>{let W={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.compactionStrategy)W.compactionStrategy=$.compactionStrategy;if($.disabledTools?.length)W.disabledTools=$.disabledTools;if($.disabledPlugins?.length)W.disabledPlugins=$.disabledPlugins;return W})});import{existsSync as gL,mkdirSync as mL,readFileSync as vL,writeFileSync as cL}from"node:fs";import{resolve as uL}from"node:path";import{resolveSessionDataDir as dL}from"@cline/shared/storage";import{nanoid as lL}from"nanoid";import*as pL from"node-machine-id";function x0($){let W=$?.trim();if(W)return W;let Z=nL();if(Z)return Z;return aL()}function iL(){let $=pL;return $.machineIdSync??$.default?.machineIdSync}function nL(){try{let $=iL();if(!$)return;return $().trim()||void 0}catch{return}}function aL(){let $=dL(),W=uL($,rL);try{if(gL(W)){let Q=vL(W,"utf8").trim();if(Q.length>0)return Q}}catch{}let Z=`cl-${lL()}`;try{mL($,{recursive:!0}),cL(W,Z,"utf8")}catch{}return Z}var rL="machine-id";var O8=()=>{};class F4{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,W){if(!this.isEnabled())return;this.emitLog($,W,!1)}emitRequired($,W){this.emitLog($,W,!0)}recordCounter($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.counters.get($);if(!j)j=this.meter.createCounter($,Q?{description:Q}:void 0),this.counters.set($,j);j.add(W,this.flattenProperties(this.buildAttributes(Z)))}recordHistogram($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.histograms.get($);if(!j)j=this.meter.createHistogram($,Q?{description:Q}:void 0),this.histograms.set($,j);j.record(W,this.flattenProperties(this.buildAttributes(Z)))}recordGauge($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.buildAttributes(Z),X=JSON.stringify(j),Y=this.gaugeValues.get($);if(W===null){if(Y){if(Y.delete(X),Y.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let V=Y;if(!V)V=new Map,this.gaugeValues.set($,V);if(!this.gauges.has($)){let B=this.meter.createObservableGauge($,Q?{description:Q}:void 0);B.addCallback((H)=>{for(let G of this.snapshotGaugeSeries($))H.observe(G.value,this.flattenProperties(G.attributes))}),this.gauges.set($,B)}V.set(X,{value:W,attributes:j})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,W,Z){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes(W,Z));this.logger.emit({severityText:"INFO",body:$,attributes:Q})}buildAttributes($,W=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...W?{_required:!0}:{}}}snapshotGaugeSeries($){let W=this.gaugeValues.get($);if(!W)return[];return Array.from(W.values(),(Z)=>({value:Z.value,attributes:Z.attributes?{...Z.attributes}:void 0}))}flattenProperties($,W="",Z=new WeakSet,Q=0){if(!$)return{};let J={},j=100,X=10;for(let[Y,V]of Object.entries($)){if(Y==="__proto__"||Y==="constructor"||Y==="prototype")continue;let B=W?`${W}.${Y}`:Y;if(V===null||V===void 0){J[B]=String(V);continue}if(Array.isArray(V)){let H=V.length>j?V.slice(0,j):V;try{J[B]=JSON.stringify(H)}catch{J[B]="[UnserializableArray]"}if(V.length>j)J[`${B}_truncated`]=!0,J[`${B}_original_length`]=V.length;continue}if(typeof V==="object"){if(V instanceof Date){J[B]=V.toISOString();continue}if(V instanceof Error){J[B]=V.message;continue}if(Z.has(V)){J[B]="[Circular]";continue}if(Q>=X){J[B]="[MaxDepthExceeded]";continue}Z.add(V),Object.assign(J,this.flattenProperties(V,B,Z,Q+1));continue}if(oL(V)){J[B]=V;continue}try{J[B]=JSON.stringify(V)}catch{J[B]=String(V)}}return J}}function oL($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class A4{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,W){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:W})}emitRequired($,W){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:W})}recordCounter($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordHistogram($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordGauge($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:W,attributes:Z,description:Q,required:J===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class z8{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new A4({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let W=this.buildAttributes($.properties);for(let Z of this.adapters)Z.emit($.event,W)}captureRequired($,W){let Z=this.buildAttributes(W);for(let Q of this.adapters)Q.emitRequired($,Z)}recordCounter($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordCounter($,W,j,Q,J)}recordHistogram($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordHistogram($,W,j,Q,J)}recordGauge($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordGauge($,W,j,Q,J)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var r7=()=>{};import{metrics as sL,trace as tL}from"@opentelemetry/api";import{logs as eL}from"@opentelemetry/api-logs";import{OTLPLogExporter as $T}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as WT}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as ZT}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as QT}from"@opentelemetry/resources";import{BatchLogRecordProcessor as JT,ConsoleLogRecordExporter as jT,LoggerProvider as XT}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as YT,MeterProvider as VT,PeriodicExportingMetricReader as mV}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as BT,ConsoleSpanExporter as HT,SimpleSpanProcessor as GT}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as KT}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as FT,ATTR_SERVICE_VERSION as AT}from"@opentelemetry/semantic-conventions";class vV{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,W){this.resolveProperties(W)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class q8{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let W=QT({[FT]:$.serviceName??"cline",...$.serviceVersion?{[AT]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(W),this.loggerProvider=this.createLoggerProvider(W),this.tracerProvider=this.createTracerProvider(W),this.meterProvider)sL.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)eL.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",W){return tL.getTracer($,W??this.options.serviceVersion)}createAdapter($){return new F4({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let W=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new z8({...$,adapters:[W],distinctId:x0($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let W=i7(this.options.metricsExporter);if(W.length===0)return null;let Z=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(Z*0.8)),J=W.map((j)=>_T(j,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Z,timeout:Q})).filter((j)=>j!==null);if(J.length===0)return null;return new VT({resource:$,readers:J})}createTracerProvider($){let W=i7(this.options.tracesExporter);if(W.length===0)return null;let Z=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,J=[];for(let j of W){let X=DT(j,{endpoint:Z,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(X)J.push(X)}if(J.length===0)return null;return new KT({resource:$,spanProcessors:J})}createLoggerProvider($){let W=i7(this.options.logsExporter);if(W.length===0)return null;let Z=W.map((Q)=>{let J=UT(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!J)return null;return new JT(J,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(Z.length===0)return null;return new XT({resource:$,processors:Z})}}function U4($){let W=new q8($),Z=W.createTelemetryService($);return Z.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:W,telemetry:Z}}function d1($){if(UW())return{telemetry:new vV($)};if($.enabled!==!0)return{telemetry:new z8({...$,distinctId:x0($.distinctId)})};return U4($)}function M8($){let{telemetry:W,provider:Z}=d1($);return{telemetry:W,provider:Z,flush:async()=>{let j=Z;if(j&&typeof j.forceFlush==="function")try{await j.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([W.dispose(),Z?.dispose()])}}}function i7($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Z)=>Z.trim()).filter((Z)=>Z==="console"||Z==="otlp")}function UT($,W){if($==="console")return new jT;if(!W.endpoint)return null;let Z=n7(W.endpoint,"/v1/logs");return new $T({url:Z,headers:W.headers})}function DT($,W){if($==="console")return new GT(new HT);if(!W.endpoint)return null;let Z=n7(W.endpoint,"/v1/traces");return new BT(new ZT({url:Z,headers:W.headers}))}function _T($,W){if($==="console")return new mV({exporter:new YT,exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout});if(!W.endpoint)return null;let Z=n7(W.endpoint,"/v1/metrics");return new mV({exporter:new WT({url:Z,headers:W.headers}),exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout})}function n7($,W){let Z=new URL($),Q=Z.pathname.endsWith("/")?Z.pathname.slice(0,-1):Z.pathname;return Z.pathname=Q.endsWith(W)?Q:`${Q}${W}`,Z.toString()}var LW=W2(()=>{X1();O8();r7()});var PG={};w(PG,{normalizeUserMessage:()=>yR,buildInitialUserContent:()=>bR});async function bR($,W,Z,Q){let J=hR(W),j=await IR(Z,Q);if(J.length===0&&!j)return $;let X=[{type:"text",text:$},...J];if(j)X.push(...j);return X}function yR($){if($==null)return"";if(typeof $==="string")return $;let W=$.content;if(typeof W==="string")return W;if(!Array.isArray(W))return"";let Z=[];for(let Q of W)if(Q&&typeof Q==="object"&&Q.type==="text"){let J=Q.text;if(typeof J==="string")Z.push(J)}return Z.join(`
3
+ `)}function hR($){if(!$||$.length===0)return[];let W=[];for(let Z of $){let Q=kR(Z);if(Q)W.push(Q)}return W}function kR($){let W=$.trim();if(!W)return;let Z=W.match(/^data:([^;,]+);base64,(.+)$/);if(Z){let Q=Z[1],J=Z[2];if(!Q||!J)return;return{type:"image",mediaType:Q,data:J}}return{type:"image",mediaType:"image/png",data:W}}async function IR($,W){if(!$||$.length===0)return;let Z=W??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all($.map(async(J)=>{let j=J.replace(/\\/g,"/");try{let X=await Z(J);return{type:"file",path:j,content:X}}catch(X){let Y=X instanceof Error?X.message:String(X);return{type:"file",path:j,content:`Error fetching content: ${Y}`}}}));if(Q.length===0)return;return Q}var ZA={};w(ZA,{updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>T6,updateMcpServerOAuthStateAsync:()=>i5,updateMcpServerOAuthState:()=>i2,setMcpServerDisabled:()=>p2,resolveMcpServerRegistrations:()=>t0,resolveDefaultMcpSettingsPath:()=>J0,registerMcpServersFromSettingsFile:()=>n2,normalizeMcpServerOAuthState:()=>O6,loadMcpSettingsFile:()=>l2,listMcpServerOAuthStatuses:()=>n5,hasMcpSettingsFile:()=>X$,getMcpServerOAuthState:()=>r2,McpSettingsUpdateSkippedError:()=>L6,McpSettingsMutatorPurityError:()=>u$,McpSettingsLockTimeoutError:()=>d$});import{existsSync as cF,mkdirSync as Yj,readFileSync as uF,renameSync as Hj,rmdirSync as yC,rmSync as Vj,statSync as hC,unlinkSync as dF,writeFileSync as lF}from"node:fs";import{randomUUID as kC}from"node:crypto";import{dirname as pF,join as vF}from"node:path";import{setTimeout as IC}from"node:timers/promises";import{resolveMcpSettingsPath as xC}from"@cline/shared/storage";import{z as S}from"zod";function Bj($){if(!$)return;if($==="http")return"streamableHttp";return $}function J0(){return xC()}function nC($,W){Yj(pF($),{recursive:!0});let Z=`${$}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{lF(Z,W,{encoding:"utf8",flag:"wx"}),Hj(Z,$)}catch(Q){try{dF(Z)}catch{}throw Q}}function oC($){Atomics.wait(aC,0,0,$)}function sC($){return`${$}.lock`}function aF(){return`${process.pid}.${Date.now()}.${kC()}`}function oF($,W){Yj(pF($),{recursive:!0});let Z=`${$}.tmp.${W}`;Vj(Z,{recursive:!0,force:!0}),Yj(Z,{recursive:!0}),lF(vF(Z,`owner.${W}`),W,{encoding:"utf8",flag:"wx"});try{return Hj(Z,$),{lockDir:$,ownerFile:vF($,`owner.${W}`)}}catch(Q){if(Vj(Z,{recursive:!0,force:!0}),cF($))return;throw Q}}function sF($,W){let Z;try{Z=Date.now()-hC($).mtimeMs}catch(J){if(J.code==="ENOENT")return;throw J}if(Z<Kj)return;W.logger?.log(`[mcp-settings] Stale lock directory at ${$} (age ${Z}ms); reclaiming.`,{severity:"warn"});let Q=`${$}.stale.${aF()}`;try{Hj($,Q)}catch(J){if(J.code==="ENOENT")return;throw J}Vj(Q,{recursive:!0,force:!0})}function tC($){try{dF($.ownerFile)}catch(W){if(W.code!=="ENOENT")throw W}try{yC($.lockDir)}catch(W){let Z=W.code;if(Z!=="ENOENT"&&Z!=="ENOTEMPTY"&&Z!=="EEXIST")throw W}}function tF($){let W=sC($);if(VQ.has(W))throw Error(`Reentrant MCP settings update for ${$}. Keep mutators pure: compute values up front and do not call back into the settings API.`);return{lockDir:W,token:aF()}}function eC($,W){let{lockDir:Z,token:Q}=tF($),J=W.timeoutMs??Kj,j=Date.now();while(!0){let X=oF(Z,Q);if(X)return VQ.add(Z),X;if(Date.now()-j>J)throw new d$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);sF(Z,W),oC(nF)}}async function $P($,W){let{lockDir:Z,token:Q}=tF($),J=W.timeoutMs??Kj,j=Date.now();while(!0){let X=oF(Z,Q);if(X)return VQ.add(Z),X;if(Date.now()-j>J)throw new d$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);sF(Z,W),await IC(nF)}}function eF($,W,Z){try{let Q=WP(W),J=ZP(Q,Z);return nC(W,`${JSON.stringify(Q,null,2)}
4
+ `),J}finally{VQ.delete($.lockDir),tC($)}}function A1($,W,Z={}){let Q=eC($,Z);return eF(Q,$,W)}async function T6($,W,Z={}){let Q=await $P($,Z);return eF(Q,$,W)}function WP($){let W=JP($);if(!W.mcpServers||typeof W.mcpServers!=="object"||Array.isArray(W.mcpServers))W.mcpServers={};return W}function ZP($,W){let Z=JSON.stringify($),Q=JSON.parse(Z),J=W(Q),j=JSON.stringify(Q),X=W($);if(JSON.stringify($)!==j)throw new u$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different settings.");if(JSON.stringify(X)!==JSON.stringify(J))throw new u$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different return values.");return X}function QP($){let W=uF($,"utf8"),Z;try{Z=JSON.parse(W)}catch(Q){let J=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${J}`)}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Z}function JP($){try{return QP($)}catch(W){if(W.code==="ENOENT")return{};throw W}}function $A($,W){if(!Object.hasOwn($,W))return;let Z=$[W];if(!Z||typeof Z!=="object"||Array.isArray(Z))return;return Z}function jP($,W,Z){Object.defineProperty($,W,{value:Z,enumerable:!0,configurable:!0,writable:!0})}function l2($={}){let W=$.filePath??J0(),Z=uF(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(j){let X=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${W}": ${X}`)}let J=iC.safeParse(Q);if(!J.success){let j=J.error.issues.map((X)=>{let Y=X.path.join(".");return Y?`${Y}: ${X.message}`:X.message}).join("; ");throw Error(`Invalid MCP settings at "${W}": ${j}`)}return J.data}function O6($){if(!$)return;let W={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(W).length>0?W:void 0}function XP($){if($===void 0)return;let W=Gj.safeParse($);if(!W.success)return;return O6(W.data)}function X$($={}){let W=$.filePath??J0();return cF(W)}function t0($={}){let W=l2($);return Object.entries(W.mcpServers).map(([Z,Q])=>({name:Z,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function p2($){let W=$.filePath??J0(),Z=$.name.trim();if(!Z)throw Error("MCP server settings toggle requires a server name.");A1(W,(Q)=>{let J=Q.mcpServers;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${W}": mcpServers must be an object.`);let j={...J},X=$A(j,Z);if(!X)throw Error(`Unknown MCP server: ${Z}`);let Y={...X};if($.disabled)Y.disabled=!0;else delete Y.disabled;jP(j,Z,Y),Q.mcpServers=j})}function r2($,W={}){let Z=l2(W);if(!Object.hasOwn(Z.mcpServers,$))return;return O6(Z.mcpServers[$]?.oauth)}function WA($,W){return(Z)=>{let Q=Z.mcpServers,J=$A(Q,$);if(!J)throw Error(`Unknown MCP server: ${$}`);let j=XP(J.oauth)??{},X=O6(W(j));if(X)J.oauth=X;else delete J.oauth;return X??{}}}function i2($,W,Z={}){let Q=Z.filePath??J0();return A1(Q,WA($,W))}async function i5($,W,Z={}){let Q=Z.filePath??J0();return T6(Q,WA($,W))}function n5($={}){return t0($).map((Z)=>{let Q=Z.transport.type!=="stdio",J=Z.oauth?.tokens?.access_token;return{serverName:Z.name,oauthSupported:Q,oauthConfigured:Q&&typeof J==="string"&&J.trim().length>0,lastError:Z.oauth?.lastError,lastAuthenticatedAt:Z.oauth?.lastAuthenticatedAt}}).sort((Z,Q)=>Z.serverName.localeCompare(Q.serverName))}async function n2($,W={}){let Z=t0(W);for(let Q of Z)await $.registerServer(Q);return Z}var r5,rF,Gj,gC,mC,vC,cC,uC,dC,iF,lC,pC,rC,iC,L6,d$,u$,Kj=1e4,nF=25,aC,VQ;var BQ=W2(()=>{r5=S.record(S.string(),S.string()),rF=S.record(S.string(),S.unknown()),Gj=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(),gC=S.object({type:S.literal("stdio"),command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:r5.optional()}),mC=S.object({type:S.literal("sse"),url:S.string().url(),headers:r5.optional()}),vC=S.object({type:S.literal("streamableHttp"),url:S.string().url(),headers:r5.optional()}),cC=S.discriminatedUnion("type",[gC,mC,vC]),uC=S.object({transport:cC,disabled:S.boolean().optional(),metadata:rF.optional(),oauth:Gj.optional()}),dC=S.enum(["stdio","sse","http","streamableHttp"]).optional(),iF=S.object({type:S.enum(["stdio","sse","streamableHttp"]).optional(),transportType:dC,disabled:S.boolean().optional(),metadata:rF.optional(),oauth:Gj.optional()});lC=iF.extend({command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:r5.optional()}).superRefine(($,W)=>{let Z=$.type??Bj($.transportType);if(Z&&Z!=="stdio")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),pC=iF.extend({url:S.string().url(),headers:r5.optional()}).superRefine(($,W)=>{let Z=$.type??Bj($.transportType)??"sse";if(Z!=="sse"&&Z!=="streamableHttp")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??Bj($.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}}),rC=S.union([uC,lC,pC]),iC=S.object({mcpServers:S.record(S.string(),rC)}).passthrough();L6=class L6 extends Error{constructor($){super($);this.name="McpSettingsUpdateSkippedError"}};d$=class d$ extends Error{constructor($){super($);this.name="McpSettingsLockTimeoutError"}};u$=class u$ extends Error{constructor($){super($);this.name="McpSettingsMutatorPurityError"}};aC=new Int32Array(new SharedArrayBuffer(4)),VQ=new Set});var aU={};w(aU,{resolveCoreDistinctId:()=>x0,createOpenTelemetryTelemetryService:()=>U4,createConfiguredTelemetryService:()=>d1,createConfiguredTelemetryHandle:()=>M8,OpenTelemetryProvider:()=>q8,OpenTelemetryAdapter:()=>F4});var yQ=W2(()=>{O8();LW()});var O_={};w(O_,{writeHubDiscovery:()=>zW,withHubStartupLock:()=>qW,verifyHubConnection:()=>z1,truncateNotificationBody:()=>k9,toHubStatusUrl:()=>t7,toHubHealthUrl:()=>MW,stopLocalHubServerGracefully:()=>H3,startHubWebSocketServer:()=>g9,startHubServer:()=>L_,spawnDetachedHubServerWithRetry:()=>N8,spawnDetachedHubServer:()=>J3,sendHubCommand:()=>UB,restartLocalHubIfIdleAfterStartupTimeout:()=>CW,resolveWorkspaceHubOwnerContext:()=>tV,resolveSharedHubOwnerContext:()=>V1,resolveProductionHubOwnerContext:()=>O1,resolveHubUrl:()=>G3,resolveHubOwnerContext:()=>r1,resolveHubEndpointOptions:()=>T1,resolveHubBuildId:()=>OW,resolveDefaultHubPort:()=>E8,resolveDefaultHubPathname:()=>Q3,resolveDefaultHubHost:()=>Z3,resolveCompatibleLocalHubUrl:()=>T4,resolveClineDir:()=>nV,resolveClineDataDir:()=>Y2,requestHubShutdown:()=>L4,rememberRecoverableLocalHubUrl:()=>O$,readHubDiscovery:()=>D0,readBearerToken:()=>L7,probeHubServer:()=>i1,probeHubConnection:()=>AB,prewarmDetachedHubServer:()=>EW,normalizeHubWebSocketUrl:()=>z$,isLocalHubOrigin:()=>UY,isLocalHubHostName:()=>T7,isHubReconnectableTransportError:()=>V3,isHubCommandTimeoutError:()=>wW,isDiscoveryFilePresent:()=>oV,ensureHubWebSocketServer:()=>O7,ensureHubServer:()=>T_,ensureDetachedHubServer:()=>JB,ensureCompatibleLocalHubUrl:()=>H2,createLocalHubScheduleRuntimeHandlers:()=>f_,createInMemoryHubOwnerContext:()=>aV,createHubServerUrl:()=>Y1,createHubAuthToken:()=>TW,createConfiguredTelemetryService:()=>d1,createConfiguredTelemetryHandle:()=>M8,connectToHub:()=>PW,clearHubDiscovery:()=>g0,NodeHubClient:()=>B1,NativeHubTransportAdapter:()=>x9,HubUIClient:()=>A3,HubTransportError:()=>y0,HubSessionClient:()=>F3,HubServerTransport:()=>o6,HubScheduleService:()=>f8,HubScheduleCommandService:()=>A8,HubCommandError:()=>w8,DEFAULT_HUB_PORT:()=>$3,DEFAULT_HUB_PATHNAME:()=>W3,DEFAULT_HUB_HOST:()=>e7,BrowserWebSocketHubAdapter:()=>I9});import{createSessionId as vf}from"@cline/shared";function p0($,W){return{version:$.version,requestId:$.requestId,ok:!0,payload:W}}function tY($,W,Z){return{version:$.version,requestId:$.requestId??vf("hubreq_"),ok:!1,error:{code:W,message:Z}}}class A8{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return p0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return p0($,{schedules:this.schedules.listSchedules({enabled:typeof $.payload?.enabled==="boolean"?$.payload.enabled:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0,tags:Array.isArray($.payload?.tags)?$.payload?.tags:void 0})});case"schedule.get":return p0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return p0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return p0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return p0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return p0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return p0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return p0($,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof $.payload?.scheduleId==="string"?$.payload.scheduleId:void 0,status:typeof $.payload?.status==="string"?$.payload.status:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0})});case"schedule.stats":return p0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return p0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return p0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return tY($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(W){return tY($,"schedule_command_failed",W instanceof Error?W.message:String(W))}}toCreateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:W}}toUpdateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:W}}}class e6{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},W=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of W)if(this.materializeOneOff(Q))$.oneOffQueued+=1;let Z=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of Z)try{if(this.materializeSchedule(Q))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as of}from"node:path";import{buildClineSystemPrompt as sf}from"@cline/shared";import{nowIso as VV}from"@cline/shared/db";var O0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},D$=[O0.READ_FILES,O0.SEARCH_CODEBASE,O0.RUN_COMMANDS,O0.FETCH_WEB_CONTENT,O0.APPLY_PATCH,O0.EDITOR,O0.SKILLS,O0.ASK,O0.SUBMIT_AND_EXIT];var $V={};w($V,{mergeRulesForSystemPrompt:()=>D8,loadRulesForSystemPromptFromWatcher:()=>P7,listEnabledRulesFromWatcher:()=>eY,isRuleEnabled:()=>l9,formatRulesForSystemPrompt:()=>U8});function l9($){return $.disabled!==!0}function U8($){if($.length===0)return"";return`
5
5
 
6
6
  # Rules
7
7
  ${$.map((Z)=>`## ${Z.name}
@@ -9,11 +9,11 @@ ${Z.instructions}`).join(`
9
9
 
10
10
  `)}`}function D8($,W){let Z=$?.trim(),Q=W?.trim();if(Z&&Q)return`${Z}
11
11
 
12
- ${Q}`;return Z||Q||void 0}function tY($){return[...$.getSnapshot("rule").values()].map((Z)=>Z.item).filter(l9).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function C7($){return U8(tY($))}var XV={};w(XV,{withSessionGitMetadata:()=>r9,readSessionGitMetadata:()=>JV,readGitWorkspaceState:()=>S7,normalizeWorkspacePath:()=>_1,hasCurrentSessionGitMetadata:()=>P7,generateWorkspaceInfoWithDiagnostics:()=>$4,generateWorkspaceInfo:()=>_8,buildWorkspaceMetadataWithInfo:()=>b7,buildWorkspaceMetadata:()=>W4});import{basename as vf,resolve as cf}from"node:path";import{performance as $V}from"node:perf_hooks";import{processWorkspaceInfo as ZV}from"@cline/shared";import QV from"simple-git";function JV($){let W=$?.git;if(!W||typeof W!=="object"||Array.isArray(W))return{};let Z=W;return{...typeof Z.url==="string"&&Z.url.trim()?{url:Z.url.trim()}:{},...typeof Z.branch==="string"&&Z.branch.trim()?{branch:Z.branch.trim()}:{}}}function r9($,W){let Z={...$??{}};if(!W.url&&!W.branch)return delete Z.git,Object.keys(Z).length>0?Z:void 0;let J={...Z.git&&typeof Z.git==="object"&&!Array.isArray(Z.git)?Z.git:{}};if(W.url)J.url=W.url;else delete J.url;if(W.branch)J.branch=W.branch;else delete J.branch;return Z.git=J,Z}function P7($,W){let Z=JV($);return Z.url===W.url&&Z.branch===W.branch}function jV($){let W=$.find(({name:Z})=>Z==="origin")??$[0];return(W?.refs.fetch||W?.refs.push)?.trim()||void 0}function _1($){return cf($)}async function _8($){return(await $4($)).info}function WV($){let W=$ instanceof Error?$.message:String($);return/unknown revision|ambiguous argument|does not have any commits yet/i.test(W)}function p9($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function $4($){let W=_1($),Z={rootPath:W,hint:vf(W)},Q={},J;try{let j=QV({baseDir:W});if(!await j.checkIsRepo())return{info:Z,vcsType:"none",gitState:Q};try{let Y=await j.getRemotes(!0);if(Y.length>0){let V=Y.map((H)=>{let G=H.refs.fetch||H.refs.push;return`${H.name}: ${G}`});Z.associatedRemoteUrls=V;let B=jV(Y);if(B)Q.url=B}}catch(Y){J??=p9(Y)}try{let Y=(await j.revparse(["HEAD"])).trim();if(Y.length>0)Z.latestGitCommitHash=Y}catch(Y){if(!WV(Y))J??=p9(Y)}try{let Y=(await j.branch()).current.trim();if(Y.length>0)Z.latestGitBranchName=Y,Q.branch=Y}catch(Y){if(!WV(Y))J??=p9(Y)}return{info:Z,vcsType:"git",gitState:Q,error:J}}catch(j){return{info:Z,vcsType:"none",gitState:Q,error:p9(j)}}}async function S7($){try{let W=QV({baseDir:_1($)});if(!await W.checkIsRepo())return{};let[Z,Q]=await Promise.all([W.getRemotes(!0),W.branch()]),J=jV(Z),j=Q.current.trim();return{...J?{url:J}:{},...j?{branch:j}:{}}}catch{return}}async function W4($){let W=await _8($);return ZV(W)}async function b7($){let W=$V.now(),Z=await $4($),Q=$V.now()-W,J=Z.info;return{workspaceInfo:J,workspaceMetadata:ZV(J),durationMs:Q,vcsType:Z.vcsType,gitState:Z.gitState,initError:Z.error}}import{mkdirSync as uf,writeFileSync as df}from"node:fs";import{join as lf}from"node:path";import{resolveCronReportsDir as pf}from"@cline/shared/storage";function _$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function Z2($,W){if(W===void 0||W===null)return;return`${$}: ${_$(W)}`}function rf($,W,Z){let Q=[`runId: ${_$($.runId)}`,`specId: ${_$(W.specId)}`,`externalId: ${_$(W.externalId)}`,`title: ${_$(W.title)}`,`triggerKind: ${_$($.triggerKind)}`,`status: ${_$($.status)}`,`sourcePath: ${_$(W.sourcePath)}`],J=[Z2("sessionId",$.sessionId),Z2("startedAt",$.startedAt),Z2("completedAt",$.completedAt),Z2("triggerEventId",$.triggerEventId),Z2("triggerEventType",Z?.eventType),Z2("triggerEventSource",Z?.source),Z2("triggerEventSubject",Z?.subject)];for(let j of J)if(j)Q.push(j);return`---
12
+ ${Q}`;return Z||Q||void 0}function eY($){return[...$.getSnapshot("rule").values()].map((Z)=>Z.item).filter(l9).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function P7($){return U8(eY($))}var YV={};w(YV,{withSessionGitMetadata:()=>r9,readSessionGitMetadata:()=>jV,readGitWorkspaceState:()=>b7,normalizeWorkspacePath:()=>_1,hasCurrentSessionGitMetadata:()=>S7,generateWorkspaceInfoWithDiagnostics:()=>$4,generateWorkspaceInfo:()=>_8,buildWorkspaceMetadataWithInfo:()=>y7,buildWorkspaceMetadata:()=>W4});import{basename as cf,resolve as uf}from"node:path";import{performance as WV}from"node:perf_hooks";import{processWorkspaceInfo as QV}from"@cline/shared";import JV from"simple-git";function jV($){let W=$?.git;if(!W||typeof W!=="object"||Array.isArray(W))return{};let Z=W;return{...typeof Z.url==="string"&&Z.url.trim()?{url:Z.url.trim()}:{},...typeof Z.branch==="string"&&Z.branch.trim()?{branch:Z.branch.trim()}:{}}}function r9($,W){let Z={...$??{}};if(!W.url&&!W.branch)return delete Z.git,Object.keys(Z).length>0?Z:void 0;let J={...Z.git&&typeof Z.git==="object"&&!Array.isArray(Z.git)?Z.git:{}};if(W.url)J.url=W.url;else delete J.url;if(W.branch)J.branch=W.branch;else delete J.branch;return Z.git=J,Z}function S7($,W){let Z=jV($);return Z.url===W.url&&Z.branch===W.branch}function XV($){let W=$.find(({name:Z})=>Z==="origin")??$[0];return(W?.refs.fetch||W?.refs.push)?.trim()||void 0}function _1($){return uf($)}async function _8($){return(await $4($)).info}function ZV($){let W=$ instanceof Error?$.message:String($);return/unknown revision|ambiguous argument|does not have any commits yet/i.test(W)}function p9($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function $4($){let W=_1($),Z={rootPath:W,hint:cf(W)},Q={},J;try{let j=JV({baseDir:W});if(!await j.checkIsRepo())return{info:Z,vcsType:"none",gitState:Q};try{let Y=await j.getRemotes(!0);if(Y.length>0){let V=Y.map((H)=>{let G=H.refs.fetch||H.refs.push;return`${H.name}: ${G}`});Z.associatedRemoteUrls=V;let B=XV(Y);if(B)Q.url=B}}catch(Y){J??=p9(Y)}try{let Y=(await j.revparse(["HEAD"])).trim();if(Y.length>0)Z.latestGitCommitHash=Y}catch(Y){if(!ZV(Y))J??=p9(Y)}try{let Y=(await j.branch()).current.trim();if(Y.length>0)Z.latestGitBranchName=Y,Q.branch=Y}catch(Y){if(!ZV(Y))J??=p9(Y)}return{info:Z,vcsType:"git",gitState:Q,error:J}}catch(j){return{info:Z,vcsType:"none",gitState:Q,error:p9(j)}}}async function b7($){try{let W=JV({baseDir:_1($)});if(!await W.checkIsRepo())return{};let[Z,Q]=await Promise.all([W.getRemotes(!0),W.branch()]),J=XV(Z),j=Q.current.trim();return{...J?{url:J}:{},...j?{branch:j}:{}}}catch{return}}async function W4($){let W=await _8($);return QV(W)}async function y7($){let W=WV.now(),Z=await $4($),Q=WV.now()-W,J=Z.info;return{workspaceInfo:J,workspaceMetadata:QV(J),durationMs:Q,vcsType:Z.vcsType,gitState:Z.gitState,initError:Z.error}}import{mkdirSync as df,writeFileSync as lf}from"node:fs";import{join as pf}from"node:path";import{resolveCronReportsDir as rf}from"@cline/shared/storage";function _$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function Z2($,W){if(W===void 0||W===null)return;return`${$}: ${_$(W)}`}function nf($,W,Z){let Q=[`runId: ${_$($.runId)}`,`specId: ${_$(W.specId)}`,`externalId: ${_$(W.externalId)}`,`title: ${_$(W.title)}`,`triggerKind: ${_$($.triggerKind)}`,`status: ${_$($.status)}`,`sourcePath: ${_$(W.sourcePath)}`],J=[Z2("sessionId",$.sessionId),Z2("startedAt",$.startedAt),Z2("completedAt",$.completedAt),Z2("triggerEventId",$.triggerEventId),Z2("triggerEventType",Z?.eventType),Z2("triggerEventSource",Z?.source),Z2("triggerEventSubject",Z?.subject)];for(let j of J)if(j)Q.push(j);return`---
13
13
  ${Q.join(`
14
14
  `)}
15
15
  ---
16
- `}function nf($){let W=[];if($.triggerEvent){let Z=$.triggerEvent,Q=[`- eventId: ${Z.eventId}`,`- eventType: ${Z.eventType}`,`- source: ${Z.source}`,Z.subject?`- subject: ${Z.subject}`:"",`- occurredAt: ${Z.occurredAt}`,Z.dedupeKey?`- dedupeKey: ${Z.dedupeKey}`:"",Z.attributes?`- attributes: ${JSON.stringify(Z.attributes)}`:""].filter((J)=>J.length>0);W.push(`## Trigger Event
16
+ `}function af($){let W=[];if($.triggerEvent){let Z=$.triggerEvent,Q=[`- eventId: ${Z.eventId}`,`- eventType: ${Z.eventType}`,`- source: ${Z.source}`,Z.subject?`- subject: ${Z.subject}`:"",`- occurredAt: ${Z.occurredAt}`,Z.dedupeKey?`- dedupeKey: ${Z.dedupeKey}`:"",Z.attributes?`- attributes: ${JSON.stringify(Z.attributes)}`:""].filter((J)=>J.length>0);W.push(`## Trigger Event
17
17
 
18
18
  ${Q.join(`
19
19
  `)}
@@ -32,12 +32,12 @@ ${Q.join(`
32
32
  ${Z.join(`
33
33
  `)}
34
34
  `)}return W.join(`
35
- `)}function y7($){let W=pf($.specs);uf(W,{recursive:!0});let Z=lf(W,`${$.run.runId}.md`),Q=`${rf($.run,$.spec,$.data.triggerEvent)}
36
- ${nf($.data)}`;return df(Z,Q,"utf8"),Z}class h7{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,W,Z){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(Z)),J=this.activeExecutions.get($)??new Set;if(J.size>=Q)return!1;return J.add(W),this.activeExecutions.set($,J),!0}release($,W){let Z=this.activeExecutions.get($);if(!Z)return;if(Z.delete(W),Z.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let W of this.activeExecutions.values())$+=W.size;return $}}var sf=15000,tf=90,VV=["rules","skills","plugins"];function ef($,W){return new Set($.extensions??VV).has(W)}function $L($,W){if($.tools===void 0)return{"*":{autoApprove:!0}};let Z={"*":{enabled:!1,autoApprove:!0}};for(let Q of $.tools)Z[Q]={enabled:!0,autoApprove:!0};if(W==="yolo")Z[O0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Z}function WL($){let W=$?.trim();if(!W)return;return["# Notes Directory",`Use ${W} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
37
- `)}class k7 extends Error{constructor($){super($);this.name="TimeoutError"}}async function ZL($,W){if(W<=0)return $;let Z,Q=new Promise((J,j)=>{Z=setTimeout(()=>{j(new k7("cron run timed out"))},W)});try{return await Promise.race([$,Q])}finally{if(Z)clearTimeout(Z)}}class Z4{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor($){this.store=$.store,this.materializer=$.materializer,this.options=$,this.limiter=new h7($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??tf)*1000)}async start(){if(this.disposed)throw Error("CronRunner disposed");if(this.started)return;this.stopping=!1,this.started=!0;let $=Math.max(2000,this.options.pollIntervalMs??sf);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let W=[...this.activeRuns.entries()];await Promise.all(W.map(async([Z,Q])=>{if(Q.sessionId)try{await this.options.runtimeHandlers.abortSession(Q.sessionId)}catch{}try{this.store.requeueRun({runId:Z,claimToken:Q.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:YV(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((W)=>this.executeClaim(W)))}catch($){let W=this.options.logger;if(W)if(W.error)W.error("cron.runner.tick.failed",{error:$});else W.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,W])=>{let Z=this.store.getRun($);return Z?[{...Z,...W}]:[]})}async executeClaim($){let W=$.run,Z=this.store.getSpec(W.specId);if(!Z){this.store.completeRun(W.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Z.enabled||Z.removed){this.store.completeRun(W.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Q=Z.maxParallel&&Z.maxParallel>0?Z.maxParallel:1;if(!this.limiter.acquire(Z.specId,W.runId,Q)){this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Z.specId,W.runId),this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(W.runId,{claimToken:$.claimToken});let j=W.triggerEventId?this.store.getEventLog(W.triggerEventId):void 0,X,Y,V=Date.now(),B;if(Z.timeoutSeconds&&Z.timeoutSeconds>0)B=V+Z.timeoutSeconds*1000;try{Y=this.startClaimLeaseHeartbeat($);let H=await this.buildStartRequest(Z);if(X=(await this.options.runtimeHandlers.startSession(H)).sessionId.trim(),!X)throw Error("runtime returned empty sessionId");this.activeRuns.set(W.runId,{claimToken:$.claimToken,sessionId:X}),this.store.attachSessionIdToRun(W.runId,X);let K={config:H,prompt:this.buildPrompt(Z,j)},F=this.options.runtimeHandlers.sendSession(X,K),A=B?Math.max(1,B-Date.now()):0,U=(await ZL(F,A)).result,f=Date.now(),_=y7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"done"},spec:Z,data:{finalText:U.text,usage:U.usage,toolCalls:U.toolCalls,durationMs:f-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"done",sessionId:X,reportPath:_,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Z,W.runId),this.store.updateSpecLastRunAt(Z.specId,YV())}catch(H){let G=H instanceof k7;if(X&&G)try{await this.options.runtimeHandlers.abortSession(X)}catch{}let K=H instanceof Error?H.message:String(H),F=Date.now(),A=y7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"failed"},spec:Z,data:{error:K,durationMs:F-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"failed",sessionId:X,reportPath:A,error:K,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Z,W.runId)}finally{if(Y?.(),X)try{await this.options.runtimeHandlers.stopSession(X)}catch{}this.activeRuns.delete(W.runId),this.limiter.release(Z.specId,W.runId)}}publishScheduleExecutionEvent($,W,Z){if(W.source!=="hub-schedule"||!this.options.eventPublisher)return;let Q=this.store.getRun(Z);if(!Q)return;let J=Q.status==="done"?"success":Q.status==="cancelled"?"aborted":Q.status==="running"?"running":Q.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:W.externalId,executionId:Q.runId,sessionId:Q.sessionId,triggeredAt:new Date(Q.scheduledFor??Q.createdAt).getTime(),startedAt:Q.startedAt?new Date(Q.startedAt).getTime():void 0,endedAt:Q.completedAt?new Date(Q.completedAt).getTime():void 0,status:J,errorMessage:Q.error})}buildPrompt($,W){let Z=$.prompt??"";if(!W)return Z;let Q={eventId:W.eventId,eventType:W.eventType,source:W.source,subject:W.subject,occurredAt:W.occurredAt,workspaceRoot:W.workspaceRoot,dedupeKey:W.dedupeKey,attributes:W.attributes,payload:W.payload};return`${Z}
35
+ `)}function h7($){let W=rf($.specs);df(W,{recursive:!0});let Z=pf(W,`${$.run.runId}.md`),Q=`${nf($.run,$.spec,$.data.triggerEvent)}
36
+ ${af($.data)}`;return lf(Z,Q,"utf8"),Z}class k7{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,W,Z){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(Z)),J=this.activeExecutions.get($)??new Set;if(J.size>=Q)return!1;return J.add(W),this.activeExecutions.set($,J),!0}release($,W){let Z=this.activeExecutions.get($);if(!Z)return;if(Z.delete(W),Z.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let W of this.activeExecutions.values())$+=W.size;return $}}var tf=15000,ef=90,BV=["rules","skills","plugins"];function $L($,W){return new Set($.extensions??BV).has(W)}function WL($,W){if($.tools===void 0)return{"*":{autoApprove:!0}};let Z={"*":{enabled:!1,autoApprove:!0}};for(let Q of $.tools)Z[Q]={enabled:!0,autoApprove:!0};if(W==="yolo")Z[O0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Z}function ZL($){let W=$?.trim();if(!W)return;return["# Notes Directory",`Use ${W} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
37
+ `)}class I7 extends Error{constructor($){super($);this.name="TimeoutError"}}async function QL($,W){if(W<=0)return $;let Z,Q=new Promise((J,j)=>{Z=setTimeout(()=>{j(new I7("cron run timed out"))},W)});try{return await Promise.race([$,Q])}finally{if(Z)clearTimeout(Z)}}class Z4{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor($){this.store=$.store,this.materializer=$.materializer,this.options=$,this.limiter=new k7($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??ef)*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??tf);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let W=[...this.activeRuns.entries()];await Promise.all(W.map(async([Z,Q])=>{if(Q.sessionId)try{await this.options.runtimeHandlers.abortSession(Q.sessionId)}catch{}try{this.store.requeueRun({runId:Z,claimToken:Q.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:VV(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((W)=>this.executeClaim(W)))}catch($){let W=this.options.logger;if(W)if(W.error)W.error("cron.runner.tick.failed",{error:$});else W.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,W])=>{let Z=this.store.getRun($);return Z?[{...Z,...W}]:[]})}async executeClaim($){let W=$.run,Z=this.store.getSpec(W.specId);if(!Z){this.store.completeRun(W.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Z.enabled||Z.removed){this.store.completeRun(W.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Q=Z.maxParallel&&Z.maxParallel>0?Z.maxParallel:1;if(!this.limiter.acquire(Z.specId,W.runId,Q)){this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Z.specId,W.runId),this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(W.runId,{claimToken:$.claimToken});let j=W.triggerEventId?this.store.getEventLog(W.triggerEventId):void 0,X,Y,V=Date.now(),B;if(Z.timeoutSeconds&&Z.timeoutSeconds>0)B=V+Z.timeoutSeconds*1000;try{Y=this.startClaimLeaseHeartbeat($);let H=await this.buildStartRequest(Z);if(X=(await this.options.runtimeHandlers.startSession(H)).sessionId.trim(),!X)throw Error("runtime returned empty sessionId");this.activeRuns.set(W.runId,{claimToken:$.claimToken,sessionId:X}),this.store.attachSessionIdToRun(W.runId,X);let K={config:H,prompt:this.buildPrompt(Z,j)},F=this.options.runtimeHandlers.sendSession(X,K),A=B?Math.max(1,B-Date.now()):0,U=(await QL(F,A)).result,f=Date.now(),_=h7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"done"},spec:Z,data:{finalText:U.text,usage:U.usage,toolCalls:U.toolCalls,durationMs:f-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"done",sessionId:X,reportPath:_,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Z,W.runId),this.store.updateSpecLastRunAt(Z.specId,VV())}catch(H){let G=H instanceof I7;if(X&&G)try{await this.options.runtimeHandlers.abortSession(X)}catch{}let K=H instanceof Error?H.message:String(H),F=Date.now(),A=h7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"failed"},spec:Z,data:{error:K,durationMs:F-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"failed",sessionId:X,reportPath:A,error:K,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Z,W.runId)}finally{if(Y?.(),X)try{await this.options.runtimeHandlers.stopSession(X)}catch{}this.activeRuns.delete(W.runId),this.limiter.release(Z.specId,W.runId)}}publishScheduleExecutionEvent($,W,Z){if(W.source!=="hub-schedule"||!this.options.eventPublisher)return;let Q=this.store.getRun(Z);if(!Q)return;let J=Q.status==="done"?"success":Q.status==="cancelled"?"aborted":Q.status==="running"?"running":Q.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:W.externalId,executionId:Q.runId,sessionId:Q.sessionId,triggeredAt:new Date(Q.scheduledFor??Q.createdAt).getTime(),startedAt:Q.startedAt?new Date(Q.startedAt).getTime():void 0,endedAt:Q.completedAt?new Date(Q.completedAt).getTime():void 0,status:J,errorMessage:Q.error})}buildPrompt($,W){let Z=$.prompt??"";if(!W)return Z;let Q={eventId:W.eventId,eventType:W.eventType,source:W.source,subject:W.subject,occurredAt:W.occurredAt,workspaceRoot:W.workspaceRoot,dedupeKey:W.dedupeKey,attributes:W.attributes,payload:W.payload};return`${Z}
38
38
 
39
39
  Trigger event:
40
- ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Z=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Q))clearInterval(Z)},W);return()=>clearInterval(Z)}async buildSystemPrompt($,W,Z,Q){let J=WL($.notesDirectory),j=D8(void 0,J),X=await W4(W),Y=of({ide:"Cline Cron",workspaceRoot:W,workspaceName:af(W),metadata:X,rules:$.systemPrompt?void 0:j,mode:Z,providerId:Q,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?D8(Y,j)??Y:Y}async buildStartRequest($){let W=($.workspaceRoot??"").trim(),Z=($.providerId??"").trim(),Q=($.modelId??"").trim(),J=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,j=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():W;if(!W)throw Error("cron spec requires workspaceRoot");let X=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:W,cwd:j,provider:Z,model:Q,mode:X,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,W,X,Z),maxIterations:$.maxIterations,enableTools:J?.enableTools??!0,enableSpawn:J?.enableSpawn??!0,enableTeams:J?.enableTeams??!0,autoApproveTools:J?.autoApproveTools??!0,toolPolicies:$L($,X),configExtensions:VV.filter((Y)=>ef($,Y))}}}function Q4($,W,Z,Q){let J=new Set;function j(X){let Y=X.toLowerCase();if(Q){let B=Q.indexOf(Y);if(B!==-1)return B+W}let V=Number(X);if(!Number.isInteger(V)||V<W||V>Z)throw Error(`Invalid cron value "${X}" for range [${W}-${Z}]`);return V}for(let X of $.split(",")){if(X==="*"){for(let B=W;B<=Z;B+=1)J.add(B);continue}let Y=X.indexOf("/");if(Y!==-1){let B=X.slice(0,Y),H=Number(X.slice(Y+1));if(!Number.isInteger(H)||H<1)throw Error(`Invalid step "${X.slice(Y+1)}"`);let G=W,K=Z;if(B!=="*"){let F=B.indexOf("-");if(F!==-1)G=j(B.slice(0,F)),K=j(B.slice(F+1));else G=j(B)}if(G>K)throw Error(`Invalid cron range "${B}"`);for(let F=G;F<=K;F+=H)J.add(F);continue}let V=X.indexOf("-");if(V!==-1){let B=j(X.slice(0,V)),H=j(X.slice(V+1));if(B>H)throw Error(`Invalid cron range "${X}"`);for(let G=B;G<=H;G+=1)J.add(G);continue}J.add(j(X))}return[...J].sort((X,Y)=>X-Y)}var QL=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],HV=["sun","mon","tue","wed","thu","fri","sat"];function J4($,W,Z){let Q=$[W];if(typeof Q!=="string")throw Error(`Invalid cron pattern "${Z}": missing field ${W+1}`);return Q}function I7($,W){let Z=$[0];if(typeof Z!=="number")throw Error(`Invalid cron pattern: no values parsed for ${W}`);return Z}function x7($){let W=$.trim().split(/\s+/);if(W.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${W.length}`);return{minutes:Q4(J4(W,0,$),0,59),hours:Q4(J4(W,1,$),0,23),daysOfMonth:Q4(J4(W,2,$),1,31),months:Q4(J4(W,3,$),1,12,QL),daysOfWeek:Q4(J4(W,4,$),0,6,HV)}}function g7($){x7($)}function GV($,W,Z=Date.now()){Q2($,Z,W)}var BV=new Map,JL=new Map(HV.map(($,W)=>[$,W]));function KV($){let W=$?.trim();return W?W:void 0}function FV($){let W=BV.get($);if(W)return W;let Z=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return BV.set($,Z),Z}function jL($){let W=KV($);if(!W)return;FV(W).format(new Date)}function XL($,W){let Z=FV(W).formatToParts(new Date($)),Q=new Map(Z.map((X)=>[X.type,X.value])),J=Q.get("weekday")?.toLowerCase().slice(0,3)??"",j=JL.get(J);if(j===void 0)throw Error(`Unable to resolve weekday for timezone "${W}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:j,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function YL($){let W=new Date($);return{month:W.getMonth()+1,dayOfMonth:W.getDate(),dayOfWeek:W.getDay(),hour:W.getHours(),minute:W.getMinutes()}}function VL($,W){return $.months.includes(W.month)&&$.daysOfMonth.includes(W.dayOfMonth)&&$.daysOfWeek.includes(W.dayOfWeek)&&$.hours.includes(W.hour)&&$.minutes.includes(W.minute)}function BL($,W,Z){let Q=x7($),J=new Date(W);J.setSeconds(0,0);let j=J.getTime()+60000,X=new Date(W);X.setFullYear(X.getFullYear()+4);let Y=X.getTime();while(j<=Y){if(VL(Q,XL(j,Z)))return j;j+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Z}"`)}function Q2($,W,Z){let Q=KV(Z);if(Q)return jL(Q),BL($,W,Q);let J=x7($),j=new Date(W);j.setSeconds(0,0),j=new Date(j.getTime()+60000);let X=new Date(W);X.setFullYear(X.getFullYear()+4);while(j<=X){let{month:Y,dayOfMonth:V,dayOfWeek:B,hour:H,minute:G}=YL(j.getTime());if(!J.months.includes(Y)){let K=J.months.find((A)=>A>Y)??I7(J.months,"months"),F=K<=Y?1:0;j=new Date(j.getFullYear()+F,K-1,1,0,0,0,0);continue}if(!J.daysOfMonth.includes(V)||!J.daysOfWeek.includes(B)){j=new Date(j.getFullYear(),j.getMonth(),V+1,0,0,0,0);continue}if(!J.hours.includes(H)){let K=J.hours.find((A)=>A>H)??I7(J.hours,"hours"),F=K<=H?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate()+F,K,0,0,0);continue}if(!J.minutes.includes(G)){let K=J.minutes.find((A)=>A>G)??I7(J.minutes,"minutes"),F=K<=G?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate(),j.getHours()+F,K,0,0);continue}return j.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{randomUUID as j4}from"node:crypto";import{asOptionalString as c,asString as Q0,loadSqliteDb as GL,nowIso as M0}from"@cline/shared/db";import{resolveCronDbPath as KL}from"@cline/shared/storage";var HL=[`CREATE TABLE IF NOT EXISTS cron_specs (
40
+ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Z=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Q))clearInterval(Z)},W);return()=>clearInterval(Z)}async buildSystemPrompt($,W,Z,Q){let J=ZL($.notesDirectory),j=D8(void 0,J),X=await W4(W),Y=sf({ide:"Cline Cron",workspaceRoot:W,workspaceName:of(W),metadata:X,rules:$.systemPrompt?void 0:j,mode:Z,providerId:Q,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?D8(Y,j)??Y:Y}async buildStartRequest($){let W=($.workspaceRoot??"").trim(),Z=($.providerId??"").trim(),Q=($.modelId??"").trim(),J=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,j=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():W;if(!W)throw Error("cron spec requires workspaceRoot");let X=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:W,cwd:j,provider:Z,model:Q,mode:X,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,W,X,Z),maxIterations:$.maxIterations,enableTools:J?.enableTools??!0,enableSpawn:J?.enableSpawn??!0,enableTeams:J?.enableTeams??!0,autoApproveTools:J?.autoApproveTools??!0,toolPolicies:WL($,X),configExtensions:BV.filter((Y)=>$L($,Y))}}}function Q4($,W,Z,Q){let J=new Set;function j(X){let Y=X.toLowerCase();if(Q){let B=Q.indexOf(Y);if(B!==-1)return B+W}let V=Number(X);if(!Number.isInteger(V)||V<W||V>Z)throw Error(`Invalid cron value "${X}" for range [${W}-${Z}]`);return V}for(let X of $.split(",")){if(X==="*"){for(let B=W;B<=Z;B+=1)J.add(B);continue}let Y=X.indexOf("/");if(Y!==-1){let B=X.slice(0,Y),H=Number(X.slice(Y+1));if(!Number.isInteger(H)||H<1)throw Error(`Invalid step "${X.slice(Y+1)}"`);let G=W,K=Z;if(B!=="*"){let F=B.indexOf("-");if(F!==-1)G=j(B.slice(0,F)),K=j(B.slice(F+1));else G=j(B)}if(G>K)throw Error(`Invalid cron range "${B}"`);for(let F=G;F<=K;F+=H)J.add(F);continue}let V=X.indexOf("-");if(V!==-1){let B=j(X.slice(0,V)),H=j(X.slice(V+1));if(B>H)throw Error(`Invalid cron range "${X}"`);for(let G=B;G<=H;G+=1)J.add(G);continue}J.add(j(X))}return[...J].sort((X,Y)=>X-Y)}var JL=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],GV=["sun","mon","tue","wed","thu","fri","sat"];function J4($,W,Z){let Q=$[W];if(typeof Q!=="string")throw Error(`Invalid cron pattern "${Z}": missing field ${W+1}`);return Q}function x7($,W){let Z=$[0];if(typeof Z!=="number")throw Error(`Invalid cron pattern: no values parsed for ${W}`);return Z}function g7($){let W=$.trim().split(/\s+/);if(W.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${W.length}`);return{minutes:Q4(J4(W,0,$),0,59),hours:Q4(J4(W,1,$),0,23),daysOfMonth:Q4(J4(W,2,$),1,31),months:Q4(J4(W,3,$),1,12,JL),daysOfWeek:Q4(J4(W,4,$),0,6,GV)}}function m7($){g7($)}function KV($,W,Z=Date.now()){Q2($,Z,W)}var HV=new Map,jL=new Map(GV.map(($,W)=>[$,W]));function FV($){let W=$?.trim();return W?W:void 0}function AV($){let W=HV.get($);if(W)return W;let Z=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return HV.set($,Z),Z}function XL($){let W=FV($);if(!W)return;AV(W).format(new Date)}function YL($,W){let Z=AV(W).formatToParts(new Date($)),Q=new Map(Z.map((X)=>[X.type,X.value])),J=Q.get("weekday")?.toLowerCase().slice(0,3)??"",j=jL.get(J);if(j===void 0)throw Error(`Unable to resolve weekday for timezone "${W}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:j,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function VL($){let W=new Date($);return{month:W.getMonth()+1,dayOfMonth:W.getDate(),dayOfWeek:W.getDay(),hour:W.getHours(),minute:W.getMinutes()}}function BL($,W){return $.months.includes(W.month)&&$.daysOfMonth.includes(W.dayOfMonth)&&$.daysOfWeek.includes(W.dayOfWeek)&&$.hours.includes(W.hour)&&$.minutes.includes(W.minute)}function HL($,W,Z){let Q=g7($),J=new Date(W);J.setSeconds(0,0);let j=J.getTime()+60000,X=new Date(W);X.setFullYear(X.getFullYear()+4);let Y=X.getTime();while(j<=Y){if(BL(Q,YL(j,Z)))return j;j+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Z}"`)}function Q2($,W,Z){let Q=FV(Z);if(Q)return XL(Q),HL($,W,Q);let J=g7($),j=new Date(W);j.setSeconds(0,0),j=new Date(j.getTime()+60000);let X=new Date(W);X.setFullYear(X.getFullYear()+4);while(j<=X){let{month:Y,dayOfMonth:V,dayOfWeek:B,hour:H,minute:G}=VL(j.getTime());if(!J.months.includes(Y)){let K=J.months.find((A)=>A>Y)??x7(J.months,"months"),F=K<=Y?1:0;j=new Date(j.getFullYear()+F,K-1,1,0,0,0,0);continue}if(!J.daysOfMonth.includes(V)||!J.daysOfWeek.includes(B)){j=new Date(j.getFullYear(),j.getMonth(),V+1,0,0,0,0);continue}if(!J.hours.includes(H)){let K=J.hours.find((A)=>A>H)??x7(J.hours,"hours"),F=K<=H?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate()+F,K,0,0,0);continue}if(!J.minutes.includes(G)){let K=J.minutes.find((A)=>A>G)??x7(J.minutes,"minutes"),F=K<=G?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate(),j.getHours()+F,K,0,0);continue}return j.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{randomUUID as j4}from"node:crypto";import{asOptionalString as c,asString as Q0,loadSqliteDb as KL,nowIso as R0}from"@cline/shared/db";import{resolveCronDbPath as FL}from"@cline/shared/storage";var GL=[`CREATE TABLE IF NOT EXISTS cron_specs (
41
41
  spec_id TEXT PRIMARY KEY,
42
42
  external_id TEXT NOT NULL,
43
43
  source_path TEXT NOT NULL UNIQUE,
@@ -128,17 +128,17 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
128
128
  ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
129
129
  ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
130
130
  ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
131
- ON cron_specs(source_path);`];function AV($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let W of HL)$.exec(W)}function i9($){if(!$)return;try{let W=JSON.parse($);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return}function m7($,W={}){if(!$)return;try{let Z=JSON.parse($);if(!Array.isArray(Z))return;let Q=Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);if(W.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function J2($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function f$($){return{specId:Q0($.spec_id),externalId:Q0($.external_id),sourcePath:Q0($.source_path),triggerKind:Q0($.trigger_kind),sourceMtimeMs:J2($.source_mtime_ms),sourceHash:c($.source_hash),parseStatus:Q0($.parse_status)==="invalid"?"invalid":"valid",parseError:c($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:Q0($.title),prompt:c($.prompt),workspaceRoot:c($.workspace_root),scheduleExpr:c($.schedule_expr),timezone:c($.timezone),eventType:c($.event_type),filters:i9(c($.filters_json)),debounceSeconds:J2($.debounce_seconds),dedupeWindowSeconds:J2($.dedupe_window_seconds),cooldownSeconds:J2($.cooldown_seconds),mode:c($.mode),systemPrompt:c($.system_prompt),providerId:c($.provider_id),modelId:c($.model_id),maxIterations:J2($.max_iterations),timeoutSeconds:J2($.timeout_seconds),maxParallel:J2($.max_parallel),tools:m7(c($.tools_json),{preserveEmpty:!0}),notesDirectory:c($.notes_directory),extensions:m7(c($.extensions_json),{preserveEmpty:!0}),source:c($.source),tags:m7(c($.tags_json)),metadata:i9(c($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:c($.last_materialized_run_id),lastRunAt:c($.last_run_at),nextRunAt:c($.next_run_at),createdAt:Q0($.created_at),updatedAt:Q0($.updated_at)}}function v7($){return{runId:Q0($.run_id),specId:Q0($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:Q0($.trigger_kind),status:Q0($.status),claimToken:c($.claim_token),claimStartedAt:c($.claim_started_at),claimUntilAt:c($.claim_until_at),scheduledFor:c($.scheduled_for),triggerEventId:c($.trigger_event_id),startedAt:c($.started_at),completedAt:c($.completed_at),sessionId:c($.session_id),reportPath:c($.report_path),error:c($.error),attemptCount:Number($.attempt_count??0),createdAt:Q0($.created_at),updatedAt:Q0($.updated_at)}}function UV($){return{eventId:Q0($.event_id),eventType:Q0($.event_type),source:Q0($.source),subject:c($.subject),occurredAt:Q0($.occurred_at),receivedAt:Q0($.received_at),workspaceRoot:c($.workspace_root),dedupeKey:c($.dedupe_key),payload:i9(c($.payload_json)),attributes:i9(c($.attributes_json)),processingStatus:Q0($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:c($.error),createdAt:Q0($.created_at),updatedAt:Q0($.updated_at)}}function DV($){return $?JSON.stringify($):null}var FL=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function _V($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function AL($,W,Z,Q){for(let J of FL){let j=$[J],X=W[J];if(_V(j)!==_V(X))return!0}if(Z===!1&&Q===!0)return!0;return!1}function UL($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function DL($){return`hub/schedules/${$}.cron.md`}function _L($){let W={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(W).length>0?W:void 0}function c7($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((W)=>W.trim().length>0),enabled:$.enabled!==!1,metadata:_L($)}}function fV($){return JSON.stringify(c7($))}function fL($,W){let Z=$.metadata?{...$.metadata}:{},Q=W.createdBy===null?void 0:W.createdBy!==void 0?W.createdBy:typeof Z.__hubScheduleCreatedBy==="string"?Z.__hubScheduleCreatedBy:void 0,J=W.cwd!==void 0?W.cwd:typeof Z.__hubScheduleCwd==="string"?Z.__hubScheduleCwd:void 0,j=W.runtimeOptions!==void 0?W.runtimeOptions:Z.__hubRuntimeOptions&&typeof Z.__hubRuntimeOptions==="object"&&!Array.isArray(Z.__hubRuntimeOptions)?Z.__hubRuntimeOptions:void 0;return delete Z.__hubScheduleCreatedBy,delete Z.__hubScheduleCwd,delete Z.__hubRuntimeOptions,{name:W.name??$.title,cronPattern:W.cronPattern??$.scheduleExpr??"",prompt:W.prompt??$.prompt??"",workspaceRoot:W.workspaceRoot??$.workspaceRoot??"",cwd:J,modelSelection:W.modelSelection!==void 0?W.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:W.enabled??$.enabled,mode:W.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:W.systemPrompt===null?void 0:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,maxIterations:W.maxIterations===null?void 0:W.maxIterations!==void 0?W.maxIterations:$.maxIterations,timeoutSeconds:W.timeoutSeconds===null?void 0:W.timeoutSeconds!==void 0?W.timeoutSeconds:$.timeoutSeconds,maxParallel:W.maxParallel??$.maxParallel??1,createdBy:Q,tags:W.tags??$.tags,runtimeOptions:j,metadata:W.metadata!==void 0?W.metadata:Object.keys(Z).length>0?Z:void 0}}class X4{db;constructor($={}){let W=$.dbPath??KL();this.db=GL(W),AV(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return W?f$(W):void 0}getSpec($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return W?f$(W):void 0}getSpecByExternalId($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return W?f$(W):void 0}listSpecs($={}){let W=[],Z=[];if($.triggerKind)W.push("trigger_kind = ?"),Z.push($.triggerKind);if(typeof $.enabled==="boolean")W.push("enabled = ?"),Z.push($.enabled?1:0);if($.parseStatus)W.push("parse_status = ?"),Z.push($.parseStatus);if(!$.includeRemoved)W.push("removed = 0");let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>f$(X))}createHubSchedule($){let W=`sched_${j4()}`,Z=this.upsertSpec({externalId:W,sourcePath:DL(W),triggerKind:"schedule",sourceHash:fV($),parseStatus:"valid",spec:c7($)});this.initializeScheduleNextRun(Z.record.specId);let Q=this.getSpec(Z.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule($){let W=this.db.prepare(`SELECT * FROM cron_specs
131
+ ON cron_specs(source_path);`];function UV($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let W of GL)$.exec(W)}function i9($){if(!$)return;try{let W=JSON.parse($);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return}function v7($,W={}){if(!$)return;try{let Z=JSON.parse($);if(!Array.isArray(Z))return;let Q=Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);if(W.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function J2($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function f$($){return{specId:Q0($.spec_id),externalId:Q0($.external_id),sourcePath:Q0($.source_path),triggerKind:Q0($.trigger_kind),sourceMtimeMs:J2($.source_mtime_ms),sourceHash:c($.source_hash),parseStatus:Q0($.parse_status)==="invalid"?"invalid":"valid",parseError:c($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:Q0($.title),prompt:c($.prompt),workspaceRoot:c($.workspace_root),scheduleExpr:c($.schedule_expr),timezone:c($.timezone),eventType:c($.event_type),filters:i9(c($.filters_json)),debounceSeconds:J2($.debounce_seconds),dedupeWindowSeconds:J2($.dedupe_window_seconds),cooldownSeconds:J2($.cooldown_seconds),mode:c($.mode),systemPrompt:c($.system_prompt),providerId:c($.provider_id),modelId:c($.model_id),maxIterations:J2($.max_iterations),timeoutSeconds:J2($.timeout_seconds),maxParallel:J2($.max_parallel),tools:v7(c($.tools_json),{preserveEmpty:!0}),notesDirectory:c($.notes_directory),extensions:v7(c($.extensions_json),{preserveEmpty:!0}),source:c($.source),tags:v7(c($.tags_json)),metadata:i9(c($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:c($.last_materialized_run_id),lastRunAt:c($.last_run_at),nextRunAt:c($.next_run_at),createdAt:Q0($.created_at),updatedAt:Q0($.updated_at)}}function c7($){return{runId:Q0($.run_id),specId:Q0($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:Q0($.trigger_kind),status:Q0($.status),claimToken:c($.claim_token),claimStartedAt:c($.claim_started_at),claimUntilAt:c($.claim_until_at),scheduledFor:c($.scheduled_for),triggerEventId:c($.trigger_event_id),startedAt:c($.started_at),completedAt:c($.completed_at),sessionId:c($.session_id),reportPath:c($.report_path),error:c($.error),attemptCount:Number($.attempt_count??0),createdAt:Q0($.created_at),updatedAt:Q0($.updated_at)}}function DV($){return{eventId:Q0($.event_id),eventType:Q0($.event_type),source:Q0($.source),subject:c($.subject),occurredAt:Q0($.occurred_at),receivedAt:Q0($.received_at),workspaceRoot:c($.workspace_root),dedupeKey:c($.dedupe_key),payload:i9(c($.payload_json)),attributes:i9(c($.attributes_json)),processingStatus:Q0($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:c($.error),createdAt:Q0($.created_at),updatedAt:Q0($.updated_at)}}function _V($){return $?JSON.stringify($):null}var AL=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function fV($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function UL($,W,Z,Q){for(let J of AL){let j=$[J],X=W[J];if(fV(j)!==fV(X))return!0}if(Z===!1&&Q===!0)return!0;return!1}function DL($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function _L($){return`hub/schedules/${$}.cron.md`}function fL($){let W={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(W).length>0?W:void 0}function u7($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((W)=>W.trim().length>0),enabled:$.enabled!==!1,metadata:fL($)}}function LV($){return JSON.stringify(u7($))}function LL($,W){let Z=$.metadata?{...$.metadata}:{},Q=W.createdBy===null?void 0:W.createdBy!==void 0?W.createdBy:typeof Z.__hubScheduleCreatedBy==="string"?Z.__hubScheduleCreatedBy:void 0,J=W.cwd!==void 0?W.cwd:typeof Z.__hubScheduleCwd==="string"?Z.__hubScheduleCwd:void 0,j=W.runtimeOptions!==void 0?W.runtimeOptions:Z.__hubRuntimeOptions&&typeof Z.__hubRuntimeOptions==="object"&&!Array.isArray(Z.__hubRuntimeOptions)?Z.__hubRuntimeOptions:void 0;return delete Z.__hubScheduleCreatedBy,delete Z.__hubScheduleCwd,delete Z.__hubRuntimeOptions,{name:W.name??$.title,cronPattern:W.cronPattern??$.scheduleExpr??"",prompt:W.prompt??$.prompt??"",workspaceRoot:W.workspaceRoot??$.workspaceRoot??"",cwd:J,modelSelection:W.modelSelection!==void 0?W.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:W.enabled??$.enabled,mode:W.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:W.systemPrompt===null?void 0:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,maxIterations:W.maxIterations===null?void 0:W.maxIterations!==void 0?W.maxIterations:$.maxIterations,timeoutSeconds:W.timeoutSeconds===null?void 0:W.timeoutSeconds!==void 0?W.timeoutSeconds:$.timeoutSeconds,maxParallel:W.maxParallel??$.maxParallel??1,createdBy:Q,tags:W.tags??$.tags,runtimeOptions:j,metadata:W.metadata!==void 0?W.metadata:Object.keys(Z).length>0?Z:void 0}}class X4{db;constructor($={}){let W=$.dbPath??FL();this.db=KL(W),UV(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return W?f$(W):void 0}getSpec($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return W?f$(W):void 0}getSpecByExternalId($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return W?f$(W):void 0}listSpecs($={}){let W=[],Z=[];if($.triggerKind)W.push("trigger_kind = ?"),Z.push($.triggerKind);if(typeof $.enabled==="boolean")W.push("enabled = ?"),Z.push($.enabled?1:0);if($.parseStatus)W.push("parse_status = ?"),Z.push($.parseStatus);if(!$.includeRemoved)W.push("removed = 0");let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>f$(X))}createHubSchedule($){let W=`sched_${j4()}`,Z=this.upsertSpec({externalId:W,sourcePath:_L(W),triggerKind:"schedule",sourceHash:LV($),parseStatus:"valid",spec:u7($)});this.initializeScheduleNextRun(Z.record.specId);let Q=this.getSpec(Z.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule($){let W=this.db.prepare(`SELECT * FROM cron_specs
132
132
  WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
133
133
  ORDER BY created_at ASC LIMIT 1`).get($);return W?f$(W):void 0}listHubSchedules($={}){let W=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],Z=[];if(typeof $.enabled==="boolean")W.push("enabled = ?"),Z.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let j of $.tags)W.push("tags_json LIKE ?"),Z.push(`%"${j.trim()}"%`);let Q=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
134
134
  WHERE ${W.join(" AND ")}
135
- ORDER BY created_at DESC LIMIT ?`).all(...Z,Q).map((j)=>f$(j))}updateHubSchedule($,W){let Z=this.getHubSchedule($);if(!Z)return;let Q=fL(Z,W),J=this.upsertSpec({externalId:$,sourcePath:Z.sourcePath,triggerKind:"schedule",sourceHash:fV(Q),parseStatus:"valid",spec:c7(Q)});if(W.cronPattern!==void 0||W.enabled!==void 0)this.initializeScheduleNextRun(J.record.specId);return this.getSpec(J.record.specId)}deleteHubSchedule($){let W=this.getHubSchedule($);if(!W)return!1;return this.markSpecRemoved(W.specId),this.cancelQueuedRunsForSpec(W.specId),!0}enqueueHubScheduleRun($,W="manual"){let Z=this.getHubSchedule($);if(!Z||!Z.enabled||Z.removed||Z.parseStatus!=="valid")return;return this.enqueueRun({specId:Z.specId,specRevision:Z.revision,triggerKind:W,scheduledFor:M0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
135
+ ORDER BY created_at DESC LIMIT ?`).all(...Z,Q).map((j)=>f$(j))}updateHubSchedule($,W){let Z=this.getHubSchedule($);if(!Z)return;let Q=LL(Z,W),J=this.upsertSpec({externalId:$,sourcePath:Z.sourcePath,triggerKind:"schedule",sourceHash:LV(Q),parseStatus:"valid",spec:u7(Q)});if(W.cronPattern!==void 0||W.enabled!==void 0)this.initializeScheduleNextRun(J.record.specId);return this.getSpec(J.record.specId)}deleteHubSchedule($){let W=this.getHubSchedule($);if(!W)return!1;return this.markSpecRemoved(W.specId),this.cancelQueuedRunsForSpec(W.specId),!0}enqueueHubScheduleRun($,W="manual"){let Z=this.getHubSchedule($);if(!Z||!Z.enabled||Z.removed||Z.parseStatus!=="valid")return;return this.enqueueRun({specId:Z.specId,specRevision:Z.revision,triggerKind:W,scheduledFor:R0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
136
136
  WHERE trigger_kind = 'event'
137
137
  AND event_type = ?
138
138
  AND enabled = 1
139
139
  AND removed = 0
140
140
  AND parse_status = 'valid'
141
- ORDER BY created_at ASC`).all($).map((Z)=>f$(Z))}upsertSpec($){let W=M0(),Z=this.getSpecBySourcePath($.sourcePath),Q=$.spec,J={title:Q?.title??Z?.title??UL($.sourcePath),prompt:Q?.prompt,workspaceRoot:Q?.workspaceRoot,scheduleExpr:Q?.triggerKind==="schedule"?Q.schedule:void 0,timezone:Q?.triggerKind==="schedule"?Q.timezone:void 0,eventType:Q?.triggerKind==="event"?Q.event:void 0,filters:Q?.triggerKind==="event"?Q.filters:void 0,debounceSeconds:Q?.triggerKind==="event"?Q.debounceSeconds:void 0,dedupeWindowSeconds:Q?.triggerKind==="event"?Q.dedupeWindowSeconds:void 0,cooldownSeconds:Q?.triggerKind==="event"?Q.cooldownSeconds:void 0,mode:Q?.mode,systemPrompt:Q?.systemPrompt,providerId:Q?.modelSelection?.providerId,modelId:Q?.modelSelection?.modelId,maxIterations:Q?.maxIterations,timeoutSeconds:Q?.timeoutSeconds,maxParallel:Q&&"maxParallel"in Q?Q.maxParallel:void 0,tools:Q?.tools,notesDirectory:Q?.notesDirectory,extensions:Q?.extensions,source:Q?.source},j=$.parseStatus==="valid"&&(Q?.enabled??!0);if(!Z){let H=`cspec_${j4()}`;this.insertSpecRow(H,$,J,j,W);let G=this.getSpec(H);if(!G)throw Error("failed to insert cron_spec row");return{record:G,created:!0,revisionChanged:!0}}let Y=Z.sourceHash!==$.sourceHash&&AL(Z,J,Z.enabled,j),V=Y?Z.revision+1:Z.revision;this.updateSpecRow(Z.specId,$,J,j,V,W);let B=this.getSpec(Z.specId);if(!B)throw Error("failed to reload cron_spec after update");return{record:B,created:!1,revisionChanged:Y}}insertSpecRow($,W,Z,Q,J){let j=W.spec;this.db.prepare(`INSERT INTO cron_specs (
141
+ ORDER BY created_at ASC`).all($).map((Z)=>f$(Z))}upsertSpec($){let W=R0(),Z=this.getSpecBySourcePath($.sourcePath),Q=$.spec,J={title:Q?.title??Z?.title??DL($.sourcePath),prompt:Q?.prompt,workspaceRoot:Q?.workspaceRoot,scheduleExpr:Q?.triggerKind==="schedule"?Q.schedule:void 0,timezone:Q?.triggerKind==="schedule"?Q.timezone:void 0,eventType:Q?.triggerKind==="event"?Q.event:void 0,filters:Q?.triggerKind==="event"?Q.filters:void 0,debounceSeconds:Q?.triggerKind==="event"?Q.debounceSeconds:void 0,dedupeWindowSeconds:Q?.triggerKind==="event"?Q.dedupeWindowSeconds:void 0,cooldownSeconds:Q?.triggerKind==="event"?Q.cooldownSeconds:void 0,mode:Q?.mode,systemPrompt:Q?.systemPrompt,providerId:Q?.modelSelection?.providerId,modelId:Q?.modelSelection?.modelId,maxIterations:Q?.maxIterations,timeoutSeconds:Q?.timeoutSeconds,maxParallel:Q&&"maxParallel"in Q?Q.maxParallel:void 0,tools:Q?.tools,notesDirectory:Q?.notesDirectory,extensions:Q?.extensions,source:Q?.source},j=$.parseStatus==="valid"&&(Q?.enabled??!0);if(!Z){let H=`cspec_${j4()}`;this.insertSpecRow(H,$,J,j,W);let G=this.getSpec(H);if(!G)throw Error("failed to insert cron_spec row");return{record:G,created:!0,revisionChanged:!0}}let Y=Z.sourceHash!==$.sourceHash&&UL(Z,J,Z.enabled,j),V=Y?Z.revision+1:Z.revision;this.updateSpecRow(Z.specId,$,J,j,V,W);let B=this.getSpec(Z.specId);if(!B)throw Error("failed to reload cron_spec after update");return{record:B,created:!1,revisionChanged:Y}}insertSpecRow($,W,Z,Q,J){let j=W.spec;this.db.prepare(`INSERT INTO cron_specs (
142
142
  spec_id, external_id, source_path, trigger_kind,
143
143
  source_mtime_ms, source_hash, parse_status, parse_error,
144
144
  enabled, removed, title, prompt, workspace_root,
@@ -161,7 +161,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
161
161
  tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
162
162
  tags_json = ?, metadata_json = ?,
163
163
  revision = ?, updated_at = ?
164
- WHERE spec_id = ?`).run(W.externalId,W.triggerKind,W.sourceMtimeMs??null,W.sourceHash,W.parseStatus,W.parseError??null,Q?1:0,Z.title??"",Z.prompt??null,Z.workspaceRoot??null,Z.scheduleExpr??null,Z.timezone??null,Z.eventType??null,Z.filters?JSON.stringify(Z.filters):null,Z.debounceSeconds??null,Z.dedupeWindowSeconds??null,Z.cooldownSeconds??null,Z.mode??null,Z.systemPrompt??null,Z.providerId??null,Z.modelId??null,Z.maxIterations??null,Z.timeoutSeconds??null,Z.maxParallel??null,Z.tools?JSON.stringify(Z.tools):null,Z.notesDirectory??null,Z.extensions?JSON.stringify(Z.extensions):null,Z.source??null,X?.tags?JSON.stringify(X.tags):null,X?.metadata?JSON.stringify(X.metadata):null,J,j,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(M0(),$)}updateSpecNextRunAt($,W){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W??null,M0(),$)}updateSpecLastRunAt($,W){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W,M0(),$)}updateLastMaterializedRunId($,W){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(W,M0(),$)}initializeScheduleNextRun($){let W=this.getSpec($);if(!W||W.triggerKind!=="schedule"||!W.enabled||!W.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let Z=new Date(Q2(W.scheduleExpr,Date.now(),W.timezone)).toISOString();this.updateSpecNextRunAt($,Z)}materializeDueScheduleRun($){let W=$.nowMs,Z=new Date(W).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let J=f$(Q);if(J.triggerKind!=="schedule"||!J.enabled||J.removed||J.parseStatus!=="valid"||!J.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let j=J.nextRunAt;if(!j){let V=new Date(Q2(J.scheduleExpr,W,J.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(V,Z,J.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:V}}if(new Date(j).getTime()>W)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:j};let X=`crun_${j4()}`,Y;try{Y=new Date(Q2(J.scheduleExpr,W,J.timezone)).toISOString()}catch{Y=void 0}return this.db.prepare(`INSERT INTO cron_runs (
164
+ WHERE spec_id = ?`).run(W.externalId,W.triggerKind,W.sourceMtimeMs??null,W.sourceHash,W.parseStatus,W.parseError??null,Q?1:0,Z.title??"",Z.prompt??null,Z.workspaceRoot??null,Z.scheduleExpr??null,Z.timezone??null,Z.eventType??null,Z.filters?JSON.stringify(Z.filters):null,Z.debounceSeconds??null,Z.dedupeWindowSeconds??null,Z.cooldownSeconds??null,Z.mode??null,Z.systemPrompt??null,Z.providerId??null,Z.modelId??null,Z.maxIterations??null,Z.timeoutSeconds??null,Z.maxParallel??null,Z.tools?JSON.stringify(Z.tools):null,Z.notesDirectory??null,Z.extensions?JSON.stringify(Z.extensions):null,Z.source??null,X?.tags?JSON.stringify(X.tags):null,X?.metadata?JSON.stringify(X.metadata):null,J,j,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(R0(),$)}updateSpecNextRunAt($,W){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W??null,R0(),$)}updateSpecLastRunAt($,W){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W,R0(),$)}updateLastMaterializedRunId($,W){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(W,R0(),$)}initializeScheduleNextRun($){let W=this.getSpec($);if(!W||W.triggerKind!=="schedule"||!W.enabled||!W.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let Z=new Date(Q2(W.scheduleExpr,Date.now(),W.timezone)).toISOString();this.updateSpecNextRunAt($,Z)}materializeDueScheduleRun($){let W=$.nowMs,Z=new Date(W).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let J=f$(Q);if(J.triggerKind!=="schedule"||!J.enabled||J.removed||J.parseStatus!=="valid"||!J.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let j=J.nextRunAt;if(!j){let V=new Date(Q2(J.scheduleExpr,W,J.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(V,Z,J.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:V}}if(new Date(j).getTime()>W)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:j};let X=`crun_${j4()}`,Y;try{Y=new Date(Q2(J.scheduleExpr,W,J.timezone)).toISOString()}catch{Y=void 0}return this.db.prepare(`INSERT INTO cron_runs (
165
165
  run_id, spec_id, spec_revision, trigger_kind, status,
166
166
  scheduled_for, trigger_event_id, attempt_count,
167
167
  created_at, updated_at
@@ -170,22 +170,22 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
170
170
  last_run_at = ?,
171
171
  next_run_at = ?,
172
172
  updated_at = ?
173
- WHERE spec_id = ?`).run(X,Z,Y??null,Z,J.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(X),nextRunAt:Y}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun($){let W=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return W?v7(W):void 0}insertEventLog($,W={}){let Z=M0(),Q=W.receivedAtIso??Z,J=$.eventId.trim();if(!J)throw Error("automation event requires eventId");let j=$.eventType.trim();if(!j)throw Error("automation event requires eventType");let X=$.source.trim();if(!X)throw Error("automation event requires source");let Y=$.occurredAt.trim()||Q,V=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
173
+ WHERE spec_id = ?`).run(X,Z,Y??null,Z,J.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(X),nextRunAt:Y}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun($){let W=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return W?c7(W):void 0}insertEventLog($,W={}){let Z=R0(),Q=W.receivedAtIso??Z,J=$.eventId.trim();if(!J)throw Error("automation event requires eventId");let j=$.eventType.trim();if(!j)throw Error("automation event requires eventType");let X=$.source.trim();if(!X)throw Error("automation event requires source");let Y=$.occurredAt.trim()||Q,V=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
174
174
  event_id, event_type, source, subject,
175
175
  occurred_at, received_at, workspace_root, dedupe_key,
176
176
  payload_json, attributes_json, processing_status,
177
177
  matched_spec_count, queued_run_count, suppressed_count,
178
178
  error, created_at, updated_at
179
- ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(J,j,X,$.subject?.trim()||null,Y,Q,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,DV($.payload),DV($.attributes),"received",0,0,0,null,Z,Z).changes??0,B=this.getEventLog(J);if(!B)throw Error("failed to insert cron_event_log row");return{record:B,created:V===1}}getEventLog($){let W=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return W?UV(W):void 0}listEventLogs($={}){let W=[],Z=[];if($.eventType)W.push("event_type = ?"),Z.push($.eventType);if($.source)W.push("source = ?"),Z.push($.source);if($.processingStatus)W.push("processing_status = ?"),Z.push($.processingStatus);let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Q}
179
+ ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(J,j,X,$.subject?.trim()||null,Y,Q,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,_V($.payload),_V($.attributes),"received",0,0,0,null,Z,Z).changes??0,B=this.getEventLog(J);if(!B)throw Error("failed to insert cron_event_log row");return{record:B,created:V===1}}getEventLog($){let W=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return W?DV(W):void 0}listEventLogs($={}){let W=[],Z=[];if($.eventType)W.push("event_type = ?"),Z.push($.eventType);if($.source)W.push("source = ?"),Z.push($.source);if($.processingStatus)W.push("processing_status = ?"),Z.push($.processingStatus);let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Q}
180
180
  ORDER BY received_at DESC, created_at DESC
181
- LIMIT ?`).all(...Z,J).map((X)=>UV(X))}updateEventLogProcessing($,W){return(this.db.prepare(`UPDATE cron_event_log SET
181
+ LIMIT ?`).all(...Z,J).map((X)=>DV(X))}updateEventLogProcessing($,W){return(this.db.prepare(`UPDATE cron_event_log SET
182
182
  processing_status = ?,
183
183
  matched_spec_count = COALESCE(?, matched_spec_count),
184
184
  queued_run_count = COALESCE(?, queued_run_count),
185
185
  suppressed_count = COALESCE(?, suppressed_count),
186
186
  error = ?,
187
187
  updated_at = ?
188
- WHERE event_id = ?`).run(W.status,W.matchedSpecCount??null,W.queuedRunCount??null,W.suppressedCount??null,W.error??null,M0(),$).changes??0)===1}listRuns($={}){let W=[],Z=[];if($.specId)W.push("spec_id = ?"),Z.push($.specId);if($.status){let X=Array.isArray($.status)?$.status:[$.status];if(X.length>0){let Y=X.map(()=>"?").join(",");W.push(`status IN (${Y})`);for(let V of X)Z.push(V)}}let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>v7(X))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
188
+ WHERE event_id = ?`).run(W.status,W.matchedSpecCount??null,W.queuedRunCount??null,W.suppressedCount??null,W.error??null,R0(),$).changes??0)===1}listRuns($={}){let W=[],Z=[];if($.specId)W.push("spec_id = ?"),Z.push($.specId);if($.status){let X=Array.isArray($.status)?$.status:[$.status];if(X.length>0){let Y=X.map(()=>"?").join(",");W.push(`status IN (${Y})`);for(let V of X)Z.push(V)}}let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>c7(X))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
189
189
  INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
190
190
  WHERE r.spec_id = ?
191
191
  AND r.trigger_kind = 'event'
@@ -203,7 +203,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
203
203
  AND r.status = 'queued'
204
204
  AND e.dedupe_key = ?
205
205
  ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
206
- LIMIT 1`).get($.specId,$.dedupeKey);return W?v7(W):void 0}updateQueuedEventRunForDebounce($){let W=M0();if((this.db.prepare(`UPDATE cron_runs SET
206
+ LIMIT 1`).get($.specId,$.dedupeKey);return W?c7(W):void 0}updateQueuedEventRunForDebounce($){let W=R0();if((this.db.prepare(`UPDATE cron_runs SET
207
207
  trigger_event_id = ?,
208
208
  scheduled_for = ?,
209
209
  updated_at = ?
@@ -212,12 +212,12 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
212
212
  AND status = 'queued'`).run($.triggerEventId,$.scheduledFor,W,$.runId).changes??0)!==1)return;return this.getRun($.runId)}hasOneOffRunForRevision($,W){return!!this.db.prepare(`SELECT run_id FROM cron_runs
213
213
  WHERE spec_id = ? AND spec_revision = ?
214
214
  AND trigger_kind = 'one_off'
215
- LIMIT 1`).get($,W)}enqueueRun($){let W=`crun_${j4()}`,Z=M0();this.db.prepare(`INSERT INTO cron_runs (
215
+ LIMIT 1`).get($,W)}enqueueRun($){let W=`crun_${j4()}`,Z=R0();this.db.prepare(`INSERT INTO cron_runs (
216
216
  run_id, spec_id, spec_revision, trigger_kind, status,
217
217
  scheduled_for, trigger_event_id, attempt_count,
218
218
  created_at, updated_at
219
219
  ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(W,$.specId,$.specRevision,$.triggerKind,"queued",$.scheduledFor??null,$.triggerEventId??null,0,Z,Z),this.updateLastMaterializedRunId($.specId,W);let Q=this.getRun(W);if(!Q)throw Error("failed to insert cron_run row");return Q}cancelQueuedRunsForSpec($){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
220
- WHERE spec_id = ? AND status = 'queued'`).run(M0(),$).changes??0}claimDueRuns($){let W=$.nowIso,Z=Math.max(1000,Math.floor($.leaseMs)),Q=new Date(new Date(W).getTime()+Z).toISOString(),J=Math.max(1,Math.floor($.limit??25)),j=[];this.db.exec("BEGIN IMMEDIATE;");try{let X=this.db.prepare(`SELECT * FROM cron_runs
220
+ WHERE spec_id = ? AND status = 'queued'`).run(R0(),$).changes??0}claimDueRuns($){let W=$.nowIso,Z=Math.max(1000,Math.floor($.leaseMs)),Q=new Date(new Date(W).getTime()+Z).toISOString(),J=Math.max(1,Math.floor($.limit??25)),j=[];this.db.exec("BEGIN IMMEDIATE;");try{let X=this.db.prepare(`SELECT * FROM cron_runs
221
221
  WHERE (
222
222
  status = 'queued'
223
223
  OR (
@@ -251,7 +251,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
251
251
  AND completed_at IS NULL
252
252
  )
253
253
  )`).run(B,W,Q,W,W,V,W).changes??0)!==1)continue;let G=this.getRun(V);if(!G)continue;j.push({run:G,claimToken:B,claimUntilAt:Q})}this.db.exec("COMMIT;")}catch(X){throw this.db.exec("ROLLBACK;"),X}return j}renewClaim($,W,Z){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
254
- WHERE run_id = ? AND claim_token = ?`).run(Z,M0(),$,W).changes??0)===1}completeRun($,W){let Z=W.completedAtIso??M0(),Q=W.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
254
+ WHERE run_id = ? AND claim_token = ?`).run(Z,R0(),$,W).changes??0)===1}completeRun($,W){let Z=W.completedAtIso??R0(),Q=W.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
255
255
  status = ?,
256
256
  session_id = COALESCE(?, session_id),
257
257
  report_path = COALESCE(?, report_path),
@@ -261,7 +261,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
261
261
  claim_token = NULL,
262
262
  claim_until_at = NULL,
263
263
  updated_at = ?
264
- ${Q}`).run(W.status,W.sessionId??null,W.reportPath??null,W.error??null,Z,Z,$,...W.claimToken?[W.claimToken]:[]).changes??0)>0}requeueRun($){let W=M0();return(this.db.prepare(`UPDATE cron_runs SET
264
+ ${Q}`).run(W.status,W.sessionId??null,W.reportPath??null,W.error??null,Z,Z,$,...W.claimToken?[W.claimToken]:[]).changes??0)>0}requeueRun($){let W=R0();return(this.db.prepare(`UPDATE cron_runs SET
265
265
  status = 'queued',
266
266
  claim_started_at = NULL,
267
267
  claim_token = NULL,
@@ -273,9 +273,9 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
273
273
  error = ?,
274
274
  scheduled_for = COALESCE(?, scheduled_for),
275
275
  updated_at = ?
276
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,W,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,W){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(W,M0(),$)}attachReportPathToRun($,W){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(W,M0(),$)}}function a9($){return $?new Date($).getTime():void 0}function LL($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W.__hubScheduleCreatedBy,delete W.__hubScheduleCwd,delete W.__hubRuntimeOptions;return W}function n9($){let W=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof W?.__hubScheduleCwd==="string"?W.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:a9($.nextRunAt),lastRunAt:a9($.lastRunAt),createdBy:typeof W?.__hubScheduleCreatedBy==="string"?W.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:W?.__hubRuntimeOptions&&typeof W.__hubRuntimeOptions==="object"&&!Array.isArray(W.__hubRuntimeOptions)?W.__hubRuntimeOptions:void 0,metadata:LL($)}}function TL($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function u7($,W){return{executionId:$.runId,scheduleId:W,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:a9($.startedAt),endedAt:a9($.completedAt),status:TL($.status),errorMessage:$.error}}class f8{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new X4({dbPath:$.dbPath}),this.materializer=new e6({store:this.store}),this.runner=new Z4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,eventPublisher:$.eventPublisher,workspaceRoot:"",logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule($){if(g7($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return n9(this.store.createHubSchedule($))}getSchedule($){let W=this.store.getHubSchedule($);return W?n9(W):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((W)=>n9(W))}updateSchedule($,W){if(W.cronPattern!==void 0)g7(W.cronPattern);let Z=this.store.getHubSchedule($);if(!Z)return;let Q=W.workspaceRoot!==void 0?W.workspaceRoot.trim():Z.workspaceRoot;if((W.enabled??Z.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...W,scheduleId:$});return j?n9(j):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;await this.runner.tick();let Z=this.store.getRun(W.runId)??W;return u7(Z,$)}triggerScheduleNowDetached($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;return this.runner.tick().catch(()=>{return}),u7(W,$)}listScheduleExecutions($){let W=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Z={specId:W?.specId,limit:$.limit};return this.store.listRuns(Z).map((J)=>{let j=W??this.store.getSpec(J.specId);if(!j||j.source!=="hub-schedule")return;return u7(J,j.externalId)}).filter((J)=>{if(!J)return!1;return!$.status||J.status===$.status})}getScheduleStats($){let W=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(W.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Z=0,Q=0,J=0,j;for(let X of W){if(X.status==="success"||X.status==="completed")Z+=1;if(!j&&X.status!=="success"&&X.status!=="completed")j=X;if(X.startedAt&&X.endedAt)J+=X.endedAt-X.startedAt,Q+=1}return{totalRuns:W.length,successRate:Z/W.length,avgDurationSeconds:Q>0?J/Q/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let W=this.store.getSpec($.specId);if(!W||W.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:W.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:W.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+W.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let W={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(W).flatMap((Z)=>Z.source==="hub-schedule"&&Z.nextRunAt?[{spec:Z,nextRunAt:Z.nextRunAt}]:[]).sort((Z,Q)=>String(Z.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:Z,nextRunAt:Q})=>({scheduleId:Z.externalId,name:Z.title,nextRunAt:Q}))}}fW();import{createSessionId as HO,isHubProtocolCompatible as GO,resolveClineBuildEnv as KO,resolveHubCommandTimeoutMs as FO}from"@cline/shared";var vV={};w(vV,{splitCoreSessionConfig:()=>D4,isSessionNotFoundError:()=>p1,SessionNotFoundError:()=>l1,SESSION_NOT_FOUND_ERROR_CODE:()=>X2});var X2="session_not_found";class l1 extends Error{sessionId;code="session_not_found";constructor($,W){super(W??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function p1($){return $ instanceof l1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function D4($){let{hooks:W,logger:Z,telemetry:Q,extensionContext:J,extraTools:j,extensions:X,onTeamEvent:Y,onConsecutiveMistakeLimitReached:V,checkpoint:B,compaction:H,...G}=$,K={};if(W)K.hooks=W;if(Z)K.logger=Z;if(Q)K.telemetry=Q;if(J)K.extensionContext=J;if(j)K.extraTools=j;if(X)K.extensions=X;if(Y)K.onTeamEvent=Y;if(V)K.onConsecutiveMistakeLimitReached=V;if(B?.createCheckpoint)K.checkpoint=B;if(H?.compact)K.compaction=H;let F=Object.keys(K).length>0?K:void 0;return{config:{...G,...B?{checkpoint:{enabled:B.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,preserveRecentTokens:H.preserveRecentTokens,summarizer:H.summarizer}}:{}},...F?{localRuntime:F}:{}}}import{spawn as cT}from"node:child_process";import{closeSync as uT,mkdirSync as dT,openSync as lT}from"node:fs";import{basename as pT,dirname as rT,join as iT}from"node:path";import{fileURLToPath as nT}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as aT,isHubDaemonProcess as eV,isHubProtocolCompatible as oT,resolveClineBuildEnv as $B,withResolvedClineBuildEnv as sT}from"@cline/shared";import{createHash as _T,randomBytes as fT}from"node:crypto";import{existsSync as LT}from"node:fs";import{chmod as TT,mkdir as n7,readFile as lV,rm as a7,writeFile as pV}from"node:fs/promises";import{dirname as rV,join as o7}from"node:path";import{resolveClineDataDir as Y2,resolveClineDir as iV}from"@cline/shared/storage";var R8="0.0.62";var _4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:R8,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var OT="CLINE_HUB_DISCOVERY_PATH",zT="CLINE_HUB_BUILD_ID",uV=30000,qT=15000,MT=100;function RT($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ET($){return _T("sha256").update($).digest("hex").slice(0,12)}function NT($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(W){return W instanceof Error&&"code"in W?String(W.code)==="EPERM":!1}}function LW(){return fT(32).toString("hex")}function wT($){return new Promise((W)=>setTimeout(W,$))}function CT($){return`${$}.lock`}async function PT($){try{let W=JSON.parse(await lV(o7($,"owner.json"),"utf8"));if(typeof W.pid!=="number"||typeof W.acquiredAt!=="string")return;return{pid:W.pid,acquiredAt:W.acquiredAt}}catch{return}}async function dV($){await a7($,{recursive:!0,force:!0}).catch(()=>{return})}function TW(){return process.env[zT]?.trim()||String(_4.version)}function r1($=process.argv[1]?.trim()||process.cwd()){let W=`hub-${ET($)}`,Z=process.env[OT]?.trim()||o7(Y2(),"locks","hub","owners",`${RT(W)}.json`);return{ownerId:W,discoveryPath:Z}}function nV($=`hub-${Date.now().toString(36)}`){return r1($)}async function D0($){try{let W=JSON.parse(await lV($,"utf8"));if(typeof W.hubId!=="string"||typeof W.protocolVersion!=="string"||typeof W.authToken!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string"||typeof W.startedAt!=="string"||typeof W.updatedAt!=="string")return;return{hubId:W.hubId,protocolVersion:W.protocolVersion,minClientProtocolVersion:typeof W.minClientProtocolVersion==="string"?W.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof W.maxClientProtocolVersion==="string"?W.maxClientProtocolVersion:void 0,capabilities:Array.isArray(W.capabilities)?W.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,authToken:W.authToken,host:W.host,port:W.port,url:W.url,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:W.startedAt,updatedAt:W.updatedAt}}catch{return}}async function OW($,W){await n7(rV($),{recursive:!0}),await a7($,{force:!0}).catch(()=>{return}),await pV($,`${JSON.stringify(W,null,2)}
277
- `,{encoding:"utf8",mode:384}),await TT($,384)}async function g0($){await a7($,{force:!0}).catch(()=>{return})}async function zW($,W){let Z=CT($);await n7(rV(Z),{recursive:!0});let Q=Date.now()+qT;while(!0)try{await n7(Z,{recursive:!1}),await pV(o7(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
278
- `,"utf8");try{return await W()}finally{await dV(Z)}}catch(J){if((J instanceof Error&&"code"in J?String(J.code):"")!=="EEXIST")throw J;let X=await PT(Z),Y=X?Date.now()-Date.parse(X.acquiredAt):uV+1;if(!X||!NT(X.pid)||Y>uV){await dV(Z);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${Z}`);await wT(MT)}}async function i1($,W){try{let Z=await fetch(W?.authToken?s7($):qW($),{headers:W?.authToken?{authorization:`Bearer ${W.authToken}`}:void 0});if(!Z.ok)return;let Q=await Z.json();if(typeof Q.protocolVersion!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string")return;return{protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((J)=>typeof J==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,host:Q.host,port:Q.port,url:Q.url,hubId:typeof Q.hubId==="string"?Q.hubId:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:typeof Q.startedAt==="string"?Q.startedAt:void 0,updatedAt:typeof Q.updatedAt==="string"?Q.updatedAt:void 0}}catch{return}}function Y1($,W,Z="/hub"){return new URL(`ws://${$}:${W}${Z}`).toString()}function qW($){let W=new URL($);return W.protocol=W.protocol==="wss:"?"https:":"http:",W.pathname="/health",W.search="",W.toString()}function s7($){let W=new URL(qW($));return W.pathname="/status",W.toString()}function aV($){return LT($)}import{CLINE_HUB_DEV_PORT as ST,CLINE_HUB_PORT as bT,resolveClineBuildEnv as yT}from"@cline/shared";var hT="CLINE_HUB_HOST",kT="CLINE_HUB_PORT",IT="CLINE_HUB_PATHNAME",t7="127.0.0.1",e7=bT,$3="/hub";function oV($){return yT($)==="development"?ST:e7}function W3($={}){return($.env??process.env)[hT]?.trim()||t7}function E8($={}){let Z=($.env??process.env)[kT]?.trim();if(!Z)return oV($);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return oV($);return Q}function Z3($={}){return($.env??process.env)[IT]?.trim()||$3}function T1($={},W={}){return{host:$.host??W3(W),port:$.port??E8(W),pathname:$.pathname??Z3(W)}}import{join as xT}from"node:path";var gT="shared:cline",mT="CLINE_HUB_DISCOVERY_PATH",vT="hub-production";function sV($){let W=_1($.trim());return r1(`workspace:${W||$.trim()}`)}function V1($=gT){return r1($)}function O1(){return{ownerId:vT,discoveryPath:process.env[mT]?.trim()||xT(Y2(),"locks","hub","production.json")}}var tT=8000,eT=200,$O=3000,WO=100,ZO=[100,250,500,1000,2000],QO="--cline-hub-daemon";function JO($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function jO(){try{let $=iT(Y2(),"logs","hub-daemon.log");return dT(rT($),{recursive:!0}),{fd:lT($,"a"),logPath:$}}catch{return}}function WB(){return $B()==="production"?O1():V1()}function V2($){return oT($).compatible}function tV($,W,Z){if(!W||W.url!==Z)return $;return{...$,authToken:$.authToken??W.authToken,pid:$.pid??W.pid}}async function B2($,W){try{return await i1($,{authToken:W})}catch{return}}async function XO($,W){let Z=Date.now()+W;while(Date.now()<Z){if(!(await B2($))?.url)return!0;await new Promise((J)=>setTimeout(J,WO))}return!1}async function MW($,W){if(await L4($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Z=await XO($.url,$O);return await g0(W).catch(()=>{return}),Z}async function f4($,W){if(V2($))return!0;return MW($,W)}async function ZB($){if($B()!=="production")return;let W=V1();if(W.discoveryPath===$.discoveryPath)return;let Z=await D0(W.discoveryPath);if(Z?.url)await MW(Z,W.discoveryPath);else await g0(W.discoveryPath).catch(()=>{return})}function YO(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return nT(new URL(`./entry.${$}`,import.meta.url))}function VO($,W){let Z=YO(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let J=pT(Q).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),X=J&&Z.toLowerCase().endsWith(".ts"),Y=j?[QO]:[...X?["--conditions=development"]:[],Z];return{launcher:Q,args:[...Y,"--cwd",$,...JO(W)],cwd:$,env:{...sT(process.env),CLINE_NO_INTERACTIVE:"1",[aT]:"1"}}}function BO($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function Q3($,W={}){if(eV())return;let Z=VO($,W),Q=jO();try{cT(Z.launcher,Z.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(Q)uT(Q.fd)}}async function N8($,W={}){for(let Z=0;;Z++)try{Q3($,W);return}catch(Q){let J=ZO[Z];if(!BO(Q)||J===void 0)throw Q;await new Promise((j)=>setTimeout(j,J))}}function RW($,W={}){if(eV())return;let Z=WB(),Q=T1(W),J=Y1(Q.host,Q.port,Q.pathname),j=W.allowPortFallback===!0&&Q.port!==0;ZB(Z).catch(()=>{return}).then(()=>D0(Z.discoveryPath)).then(async(X)=>{let Y=!1;if(X?.url)if(!X.authToken){if(Y=!0,!await MW(X,Z.discoveryPath)&&!j)return}else{let H=await B2(X.url,X.authToken);if(H?.url&&V2(H)&&await z1(H.url,{authToken:X.authToken}))return;if(H?.url)await f4({...H,authToken:X.authToken},Z.discoveryPath);else await g0(Z.discoveryPath).catch(()=>{return})}let V=await B2(J);if(V?.url){if(V2(V)){if(!j||!Y)return}else if(!await f4({...V,authToken:void 0},Z.discoveryPath)&&!j)return}let B=j?{...Q,port:0}:Q;await N8($,B)}).catch(()=>{})}async function QB($,W={}){let Z=WB(),Q=W.host!==void 0||W.port!==void 0||W.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=T1(W),j=Y1(J.host,J.port,J.pathname),X=(F)=>{if(!Q)O$(F.url,F.authToken);return F};await ZB(Z).catch(()=>{return});let Y=await D0(Z.discoveryPath),V=!1;if(Y?.url){let F=Y.authToken;if(!F)V=!0,await MW(Y,Z.discoveryPath);else{let A=await B2(Y.url,F);if(A?.url&&V2(A)&&await z1(A.url,{authToken:F}))return X({url:A.url,authToken:F});if(A?.url)await f4({...A,authToken:F},Z.discoveryPath);else await g0(Z.discoveryPath).catch(()=>{return})}}let B=await B2(j);if(B?.url){let F=tV(B,Y,j);if(V2(B))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${V?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await f4(F,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let G=W.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await N8($,G);let K=Date.now()+tT;while(Date.now()<K){let F=await D0(Z.discoveryPath);if(F?.url&&F.authToken){let D=await B2(F.url,F.authToken);if(D?.url&&V2(D)&&await z1(D.url,{authToken:F.authToken}))return X({url:D.url,authToken:F.authToken})}let A=await B2(j);if(A?.url&&!V2(A)){let D=tV(A,F,j);if(!await f4(D,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((D)=>setTimeout(D,eT))}throw Error("Timed out waiting for detached hub startup.")}function EW(){return KO()==="production"?O1():V1()}function AO(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function VB($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((W)=>Buffer.from(W))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return VB($.data);return String($)}function UO($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function JB($){let W=$,Z=UO(W.reason);return new y0("hub_connection_closed",W.code||Z?`Hub connection closed (code=${W.code??0}${Z?`, reason=${Z}`:""})`:J3,{closeCode:W.code,closeReason:Z||void 0})}function DO($,W){if($ instanceof y0)return $;if($ instanceof Error)return new y0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new y0("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new y0("hub_connect_failed",Z);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new y0("hub_connect_failed",Q?`Failed to connect to hub at ${W.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${W.toString()}.`)}var _O=8000,fO=200,jB="*",XB=8000,LO="cline-hub-auth.",BB=new Map,HB=new Set,TO=3000,OO=3000,zO=100,J3="Hub connection closed",qO=250,MO=5000,YB=0.5;class y0 extends Error{code;details;constructor($,W,Z){super(W);this.code=$;this.details=Z;this.name="HubTransportError"}}function Y3($){return $ instanceof y0}class w8 extends Error{command;code;constructor($,W,Z){super(Z);this.command=$;this.code=W;this.name="HubCommandError"}}function NW($,W){return $ instanceof w8&&$.code==="hub_command_timeout"&&(W===void 0||$.command===W)}function GB($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=V3($.toString());return Z?BB.get(Z):void 0}function RO($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function V3($){if(!RO($))return;let W=new URL(z$($));return W.search="",W.hash="",W.toString()}function j3($){let W=V3($);return!!W&&HB.has(W)}function O$($,W){let Z=V3($);if(Z){if(HB.add(Z),W?.trim())BB.set(Z,W)}return $}class B1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new y0("hub_connection_closed",J3);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),W=this.options.authToken?.trim()||GB($);$.hash="";let Q=new(AO())($.toString(),W?[`${LO}${W}`]:void 0);this.socket=Q;let J=!1;this.connectPromise=new Promise((j,X)=>{let Y=!1,V=setTimeout(()=>{if(Y)return;Y=!0,J=!0,this.lastCloseError=new y0("hub_connect_timeout",`Timed out connecting to hub after ${XB}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}X(this.lastCloseError)},XB);Q.addEventListener("open",()=>{if(Y)return;Y=!0,clearTimeout(V),j()}),Q.addEventListener("error",(B)=>{if(Y)return;Y=!0,clearTimeout(V),this.lastCloseError=DO(B,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),Q.addEventListener("close",(B)=>{if(Y)return;if(Y=!0,clearTimeout(V),!J)this.lastCloseError=JB(B),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),Q.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(VB(j)))}),Q.addEventListener("close",(j)=>{if(this.socket!==Q)return;if(!J)this.lastCloseError=JB(j),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,W){let Z=W?.sessionId?.trim()||void 0,Q={listener:$,sessionId:Z};return this.listeners.add(Q),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(Z,-1)}}async command($,W,Z,Q){let J=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,W,Z,Q)}catch(X){if(!j||J>=1||!await this.recoverLocalHubTransport(X))throw X;J+=1}}async commandOnce($,W,Z,Q){await this.connect();let J=HO("hubreq_"),j=FO($,Q?.timeoutMs),X=new Promise((V,B)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;B(new w8($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${J}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(J,{resolve:(G)=>{if(H)clearTimeout(H);V(G)},reject:(G)=>{if(H)clearTimeout(H);B(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:J,clientId:this.clientId,sessionId:Z,timeoutMs:j,payload:W}})}catch(V){throw this.pendingReplies.delete(J),V}let Y=await X;if(!Y.ok){if(Y.error?.code===X2){let V=Z??(typeof W?.sessionId==="string"?W.sessionId:void 0);throw new l1(V,Y.error.message)}throw new w8($,Y.error?.code,Y.error?.message??`Hub command ${$} failed`)}return Y}async recoverLocalHubTransport($){if(!j3(this.currentUrl)||!Y3($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let W=await H2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!W)return!1;return this.currentUrl=W,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(qO*2**this.reconnectAttempt,MO),W=Math.round($*(1-YB)+Math.random()*$*YB);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},W)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!j3(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await H2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!$)return;this.lastCloseError=new y0("hub_connection_closed",J3),this.sawSocketClose=!1;for(let W of this.pendingReplies.values())W.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new y0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,W){this.sendFrame({kind:$,clientId:this.clientId,...W?{sessionId:W}:{}})}adjustSubscriptionCount($,W){let Z=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(Z)??0)+W;if(Q<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(W<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,Q),W>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??jB}subscriptionSessionIdFromKey($){return $===jB?void 0:$}handleFrame($){switch($.kind){case"reply":{let W=$.envelope.requestId;if(!W)return;let Z=this.pendingReplies.get(W);if(!Z)return;this.pendingReplies.delete(W),Z.resolve($.envelope);return}case"event":for(let W of this.listeners){if(W.sessionId&&W.sessionId!==$.envelope.sessionId?.trim())continue;W.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function z$($){let W=new URL($);if(W.protocol==="http:")W.protocol="ws:";else if(W.protocol==="https:")W.protocol="wss:";return W.toString()}async function z1($,W){let Z=new B1({url:$,authToken:W?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function X3($,W){let Z=z$($),Q=await i1(Z,{authToken:W?.authToken});if(!Q)return{status:"unreachable",url:Z};if(!GO(Q).compatible)return{status:"protocol_mismatch",url:Z};if(W?.verifyConnection===!0&&!await z1(Z,{workspaceRoot:W.workspaceRoot,cwd:W.cwd,authToken:W.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function EO($){let W=Date.now()+_O;while(Date.now()<W){let Z=await D0($.discoveryPath);if(Z?.url){let Q=await X3(Z.url,{verifyConnection:!0,authToken:Z.authToken});if(Q.status==="compatible")return O$(Q.url,Z.authToken)}await new Promise((Q)=>setTimeout(Q,fO))}return}async function NO($){let W=Date.now()+OO;while(Date.now()<W){if(!(await i1($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,zO))}return!1}function wO($,W){try{return z$($)===z$(W)}catch{return!1}}function CO($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function PO($,W,Z){let Q=new B1({url:$,authToken:W,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let J=await Q.command("session.list",{limit:500},void 0,{timeoutMs:TO});return!CO(J.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function T4($={}){if($.endpoint?.trim()){let J=await X3($.endpoint);return J.status==="compatible"?J.url:void 0}let W=EW(),Z=await D0(W.discoveryPath);if(!Z?.url)return;let Q=await X3(Z.url,{authToken:Z.authToken});if(Q.status==="compatible")return O$(Q.url,Z.authToken);if(Q.status==="protocol_mismatch")await g0(W.discoveryPath).catch(()=>{return});return}async function H2($={}){let W=await T4($);if(W&&await z1(W,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return W;if($.endpoint?.trim())return;let Z=EW();return await N8($.workspaceRoot??process.cwd()),await EO(Z)}async function L4($,W){let Z=new URL($),Q=W?.trim()||GB(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function B3($=EW()){let W=await D0($.discoveryPath);if(!W?.url)return!1;try{if(await L4(W.url,W.authToken))return!0}catch{}return!1}async function wW($){if(!j3($.url))return;let W=EW(),Z=await D0(W.discoveryPath);if(!Z?.url||!wO(Z.url,$.url))return;if(!await PO(Z.url,Z.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await B3())return;if(!await NO(Z.url))return;return await g0(W.discoveryPath).catch(()=>{return}),await H2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{resolveClineBuildEnv as SO}from"@cline/shared";function bO($,W){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Z?`Failed to connect to hub at ${W} (${Z} event before socket open).`:`Failed to connect to hub at ${W}.`)}var yO="cline-hub-auth.";function hO($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function kO($,W){let Z=new URL($),Q=new URL(W);return Z.search="",Z.hash="",Q.search="",Q.hash="",Z.toString()===Q.toString()}function KB(){return SO()==="production"?O1():V1()}async function IO($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=KB(),Q=await D0(Z.discoveryPath);if(Q?.url&&kO($.toString(),Q.url))return Q.authToken;return}async function H3($={}){let W=T1($);if(!hO($)){let Z=KB(),Q=await D0(Z.discoveryPath);if(Q?.url)return Q.url}return Y1(W.host,W.port,W.pathname)}async function CW($){return await new Promise((W,Z)=>{(async()=>{let Q=new URL($),J=await IO(Q);Q.hash="";let j=new WebSocket(Q.toString(),J?[`${yO}${J}`]:void 0),X=new Map,Y=0;j.addEventListener("open",()=>{W({send(V){let B=V.requestId??`hub-client-${++Y}`;return new Promise((H,G)=>{X.set(B,{resolve:H,reject:G});let K={kind:"command",envelope:{...V,requestId:B}};j.send(JSON.stringify(K))})},close(){j.close()}})}),j.addEventListener("message",(V)=>{let B=JSON.parse(String(V.data));if(B.kind==="reply"&&B.envelope.requestId){let H=X.get(B.envelope.requestId);if(H)X.delete(B.envelope.requestId),H.resolve(B.envelope)}}),j.addEventListener("close",()=>{for(let V of X.values())V.reject(Error("Hub connection closed"));X.clear()}),j.addEventListener("error",(V)=>{Z(bO(V,$))})})().catch(Z)})}async function FB($){try{return(await CW($)).close(),!0}catch{return!1}}async function AB($,W){let Z=await H3($),Q=await CW(Z);try{return await Q.send({version:W.version??"v1",clientId:W.clientId??"hub-client",...W})}finally{Q.close()}}function G3($){return $?JSON.parse(JSON.stringify($)):{}}function PW($){let W=$?.session&&typeof $.session==="object"?$.session:void 0;if(!W)return;let Z=W.metadata&&typeof W.metadata==="object"?G3(W.metadata):void 0;return{sessionId:typeof W.sessionId==="string"?W.sessionId:"",parentSessionId:typeof Z?.parentSessionId==="string"?Z.parentSessionId:void 0,messagesPath:typeof Z?.messagesPath==="string"?Z.messagesPath:void 0,metadata:Z}}function UB($,W){return $.error?.message??`hub command failed: ${W}`}function xO($){let W=G3($);if(typeof W.error==="string"&&W.error.trim())return{...W,error:W.error.trim()};let Z=W.result&&typeof W.result==="object"?W.result:void 0;if(typeof Z?.text==="string"&&Z.text.trim())return{...W,error:Z.text.trim()};let Q=Z?.error&&typeof Z.error==="object"?Z.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...W,error:Q.message.trim()};return W}function DB($){let W=$?.sessionId;return typeof W==="string"&&W.trim()?W.trim():void 0}function gO($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))throw Error("hub checkpoint restore returned no checkpoint");let Z=W;if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Z}function mO($){let W=G3($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||DB(W)||"",eventType:"schedule.execution.completed",payload:W};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||DB(W)||"",eventType:"schedule.execution.failed",payload:W};let Z=$.sessionId?.trim();if(!Z)return;switch($.event){case"iteration.started":return{sessionId:Z,eventType:"runtime.chat.iteration_start",payload:W};case"iteration.finished":return{sessionId:Z,eventType:"runtime.chat.iteration_end",payload:W};case"assistant.delta":return{sessionId:Z,eventType:"runtime.chat.text_delta",payload:W};case"usage.updated":return{sessionId:Z,eventType:"runtime.chat.usage",payload:W};case"session.notice":return{sessionId:Z,eventType:"runtime.chat.notice",payload:W};case"tool.started":return{sessionId:Z,eventType:"runtime.chat.tool_call_start",payload:W};case"tool.finished":return{sessionId:Z,eventType:"runtime.chat.tool_call_end",payload:W};case"approval.requested":return{sessionId:Z,eventType:"approval.requested",payload:W};case"run.aborted":return{sessionId:Z,eventType:"runtime.chat.aborted",payload:W};case"run.failed":return{sessionId:Z,eventType:"runtime.chat.failed",payload:xO($.payload)};case"run.completed":return{sessionId:Z,eventType:"runtime.chat.completed",payload:W};default:return}}class K3{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new B1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let W=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Z=PW(W.payload);if(!Z?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:"",messagesPath:Z.messagesPath??""}}}async sendRuntimeSession($,W,Z){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:W.prompt,mode:W.config.mode,attachments:W.attachments,delivery:W.delivery,timeoutSeconds:W.config.timeoutSeconds},$,Z)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(p1(Z))return;throw Z}return PW(W.payload)}async readMessages($){let W=$.trim();if(!W)return[];await this.ensureMetadataApplied();let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Error(UB(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,J=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},W);if(!J.ok)throw Error(UB(J,"session.restore"));let j=PW(J.payload);if(Z&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let X=Array.isArray(J.payload?.messages)?J.payload.messages:void 0,Y=gO(J.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...X?{messages:X}:{},checkpoint:Y}}async listSessions($){await this.ensureMetadataApplied();let W=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(W.payload?.sessions)?W.payload?.sessions:[]).map((Q)=>PW({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,W=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:W})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,W){let Z=new Set(($.sessionIds??[]).map((J)=>J.trim()).filter(Boolean)),Q=this.client.subscribe((J)=>{let j=mO(J);if(!j)return;if(Z.size>0&&!Z.has(j.sessionId))return;W.onEvent?.(j)});return this.ensureMetadataApplied().catch((J)=>{W.onError?.(J instanceof Error?J:Error(String(J)))}),Q}streamTeamProgress($,W){let Z=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;W.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{W.onError?.(Q instanceof Error?Q:Error(String(Q)))}),Z}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let W=await this.client.command("schedule.list");return Array.isArray(W.payload?.schedules)?W.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,W){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...W})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,W){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.list_executions",{scheduleId:$,limit:W});return Array.isArray(Z.payload?.executions)?Z.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let W=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(W.payload?.upcoming)?W.payload?.upcoming:[]}}class F3{client;constructor($){this.client=new B1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let W=await this.client.command("session.list",{limit:$});return Array.isArray(W.payload?.sessions)?W.payload.sessions:[]}subscribeUI($){return this.client.subscribe((W)=>{switch(W.event){case"ui.notify":$.onNotify?.(W.payload);break;case"ui.show_window":$.onShowWindow?.(W.payload);break;case"hub.client.registered":$.onClientRegistered?.(W.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(W.payload??{});break;case"session.created":$.onSessionCreated?.(W.payload??{});break;case"session.updated":$.onSessionUpdated?.(W.payload??{});break;case"session.detached":$.onSessionDetached?.(W.payload??{});break}})}}import{normalizeProviderId as Xm}from"@cline/llms";var D_={};w(D_,{LocalRuntimeHost:()=>b1});import{readdirSync as sg}from"node:fs";import{homedir as tg}from"node:os";import{isAbsolute as eg,join as RY,resolve as EY}from"node:path";import{captureSdkError as s$,createSessionId as $m,isLikelyAuthError as Wm,normalizeUserInput as Zm}from"@cline/shared";import{setHomeDirIfUnset as Qm}from"@cline/shared/storage";var rB={};w(rB,{saveProviderOAuthCredentials:()=>F2,resolveProviderApiKeyFromSettings:()=>w3,loginAndSaveProviderOAuthCredentials:()=>C4,isOAuthProvider:()=>K2,getProviderOAuthCredentialsFromSettings:()=>P4,getProviderAuthStorageId:()=>N3,getProviderAuthHandler:()=>H0,getPersistedProviderApiKey:()=>h8,formatProviderOAuthApiKey:()=>C3});import{decodeJwtPayload as fz,getClineEnvironmentConfig as lB}from"@cline/shared";var NB={};w(NB,{startClineDeviceAuth:()=>O3,refreshClineToken:()=>hW,loginClineOAuth:()=>O4,getValidClineCredentials:()=>z4,completeClineDeviceAuth:()=>z3});import{getClineEnvironmentConfig as D3}from"@cline/shared";var _B={};w(_B,{setSdkLogger:()=>U3,sdkDebug:()=>s,hashSecret:()=>N0,getSdkLogger:()=>cO});import{createHash as vO}from"node:crypto";var A3;function U3($){A3=$}function cO(){return A3}function N0($){if(typeof $!=="string"||$.length===0)return"unset";return vO("sha256").update($).digest("hex").slice(0,8)}function s($){try{A3?.debug($)}catch{}}R0();var fB={};w(fB,{startLocalOAuthServer:()=>H1});function uO(){let $;return{promise:new Promise((Z)=>{$=Z}),resolve:$}}async function H1($){let W=await import("node:http"),Z=$.host??"127.0.0.1",Q=$.timeoutMs??300000,J=$.successHtml??dO,j=uO(),X=!1,Y=null,V=null,B=null,H=(F)=>{if(X)return;X=!0,j.resolve(F)},G=()=>{if(Y)clearTimeout(Y),Y=null;let F=B;if(B=null,V)V.close(),V.closeAllConnections?.(),V=null;if(F!==null&&$.onClose)Promise.resolve($.onClose({host:Z,port:F})).catch(()=>{})},K=async()=>{return Y=setTimeout(()=>{G(),H(null)},Q),j.promise};for(let F of $.ports){let A=W.createServer((U,f)=>{try{let _=new URL(U.url||"",`http://${Z}:${F}`);if(_.pathname!==$.callbackPath){f.statusCode=404,f.end("Not found");return}let R={url:_,code:_.searchParams.get("code")??void 0,state:_.searchParams.get("state")??void 0,provider:_.searchParams.get("provider")??void 0,error:_.searchParams.get("error")??void 0};if(R.error){f.statusCode=400,f.end(`Authentication failed: ${R.error}`),G(),H(R);return}if(!R.code){f.statusCode=400,f.end("Missing authorization code");return}if($.expectedState&&R.state!==$.expectedState){f.statusCode=400,f.end("State mismatch");return}f.statusCode=200,f.setHeader("Content-Type","text/html; charset=utf-8"),f.end(J),G(),H(R)}catch{f.statusCode=500,f.end("Internal error")}}),D=await new Promise((U)=>{let f=(_)=>{A.off("error",f),U({bound:!1,error:_})};A.once("error",f),A.listen(F,Z,()=>{A.off("error",f),V=A,U({bound:!0})})});if(D.error){if(D.error.code==="EADDRINUSE")continue;throw G(),D.error}if(D.bound){B=F;let U=`http://${Z}:${F}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Z,port:F,callbackUrl:U})).catch(()=>{});return{callbackUrl:U,waitForCallback:K,cancelWait:()=>{G(),H(null)},close:()=>{G(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var dO=`<!DOCTYPE html>
276
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,W,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,W){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(W,R0(),$)}attachReportPathToRun($,W){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(W,R0(),$)}}function a9($){return $?new Date($).getTime():void 0}function TL($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W.__hubScheduleCreatedBy,delete W.__hubScheduleCwd,delete W.__hubRuntimeOptions;return W}function n9($){let W=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof W?.__hubScheduleCwd==="string"?W.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:a9($.nextRunAt),lastRunAt:a9($.lastRunAt),createdBy:typeof W?.__hubScheduleCreatedBy==="string"?W.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:W?.__hubRuntimeOptions&&typeof W.__hubRuntimeOptions==="object"&&!Array.isArray(W.__hubRuntimeOptions)?W.__hubRuntimeOptions:void 0,metadata:TL($)}}function OL($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function d7($,W){return{executionId:$.runId,scheduleId:W,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:a9($.startedAt),endedAt:a9($.completedAt),status:OL($.status),errorMessage:$.error}}class f8{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new X4({dbPath:$.dbPath}),this.materializer=new e6({store:this.store}),this.runner=new Z4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,eventPublisher:$.eventPublisher,workspaceRoot:"",logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule($){if(m7($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return n9(this.store.createHubSchedule($))}getSchedule($){let W=this.store.getHubSchedule($);return W?n9(W):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((W)=>n9(W))}updateSchedule($,W){if(W.cronPattern!==void 0)m7(W.cronPattern);let Z=this.store.getHubSchedule($);if(!Z)return;let Q=W.workspaceRoot!==void 0?W.workspaceRoot.trim():Z.workspaceRoot;if((W.enabled??Z.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...W,scheduleId:$});return j?n9(j):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;await this.runner.tick();let Z=this.store.getRun(W.runId)??W;return d7(Z,$)}triggerScheduleNowDetached($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;return this.runner.tick().catch(()=>{return}),d7(W,$)}listScheduleExecutions($){let W=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Z={specId:W?.specId,limit:$.limit};return this.store.listRuns(Z).map((J)=>{let j=W??this.store.getSpec(J.specId);if(!j||j.source!=="hub-schedule")return;return d7(J,j.externalId)}).filter((J)=>{if(!J)return!1;return!$.status||J.status===$.status})}getScheduleStats($){let W=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(W.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Z=0,Q=0,J=0,j;for(let X of W){if(X.status==="success"||X.status==="completed")Z+=1;if(!j&&X.status!=="success"&&X.status!=="completed")j=X;if(X.startedAt&&X.endedAt)J+=X.endedAt-X.startedAt,Q+=1}return{totalRuns:W.length,successRate:Z/W.length,avgDurationSeconds:Q>0?J/Q/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let W=this.store.getSpec($.specId);if(!W||W.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:W.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:W.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+W.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let W={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(W).flatMap((Z)=>Z.source==="hub-schedule"&&Z.nextRunAt?[{spec:Z,nextRunAt:Z.nextRunAt}]:[]).sort((Z,Q)=>String(Z.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:Z,nextRunAt:Q})=>({scheduleId:Z.externalId,name:Z.title,nextRunAt:Q}))}}LW();import{createSessionId as GO,isHubProtocolCompatible as KO,resolveClineBuildEnv as FO,resolveHubCommandTimeoutMs as AO}from"@cline/shared";var cV={};w(cV,{splitCoreSessionConfig:()=>D4,isSessionNotFoundError:()=>p1,SessionNotFoundError:()=>l1,SESSION_NOT_FOUND_ERROR_CODE:()=>X2});var X2="session_not_found";class l1 extends Error{sessionId;code="session_not_found";constructor($,W){super(W??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function p1($){return $ instanceof l1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function D4($){let{hooks:W,logger:Z,telemetry:Q,extensionContext:J,extraTools:j,extensions:X,onTeamEvent:Y,onConsecutiveMistakeLimitReached:V,checkpoint:B,compaction:H,...G}=$,K={};if(W)K.hooks=W;if(Z)K.logger=Z;if(Q)K.telemetry=Q;if(J)K.extensionContext=J;if(j)K.extraTools=j;if(X)K.extensions=X;if(Y)K.onTeamEvent=Y;if(V)K.onConsecutiveMistakeLimitReached=V;if(B?.createCheckpoint)K.checkpoint=B;if(H?.compact)K.compaction=H;let F=Object.keys(K).length>0?K:void 0;return{config:{...G,...B?{checkpoint:{enabled:B.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,preserveRecentTokens:H.preserveRecentTokens,summarizer:H.summarizer}}:{}},...F?{localRuntime:F}:{}}}import{spawn as uT}from"node:child_process";import{closeSync as dT,mkdirSync as lT,openSync as pT}from"node:fs";import{basename as rT,dirname as iT,join as nT}from"node:path";import{fileURLToPath as aT}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as oT,isHubDaemonProcess as $B,isHubProtocolCompatible as sT,resolveClineBuildEnv as WB,withResolvedClineBuildEnv as tT}from"@cline/shared";import{createHash as fT,randomBytes as LT}from"node:crypto";import{existsSync as TT}from"node:fs";import{chmod as OT,mkdir as a7,readFile as pV,rm as o7,writeFile as rV}from"node:fs/promises";import{dirname as iV,join as s7}from"node:path";import{resolveClineDataDir as Y2,resolveClineDir as nV}from"@cline/shared/storage";var R8="0.0.63";var _4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:R8,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var zT="CLINE_HUB_DISCOVERY_PATH",qT="CLINE_HUB_BUILD_ID",dV=30000,MT=15000,RT=100;function ET($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function NT($){return fT("sha256").update($).digest("hex").slice(0,12)}function wT($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(W){return W instanceof Error&&"code"in W?String(W.code)==="EPERM":!1}}function TW(){return LT(32).toString("hex")}function CT($){return new Promise((W)=>setTimeout(W,$))}function PT($){return`${$}.lock`}async function ST($){try{let W=JSON.parse(await pV(s7($,"owner.json"),"utf8"));if(typeof W.pid!=="number"||typeof W.acquiredAt!=="string")return;return{pid:W.pid,acquiredAt:W.acquiredAt}}catch{return}}async function lV($){await o7($,{recursive:!0,force:!0}).catch(()=>{return})}function OW(){return process.env[qT]?.trim()||String(_4.version)}function r1($=process.argv[1]?.trim()||process.cwd()){let W=`hub-${NT($)}`,Z=process.env[zT]?.trim()||s7(Y2(),"locks","hub","owners",`${ET(W)}.json`);return{ownerId:W,discoveryPath:Z}}function aV($=`hub-${Date.now().toString(36)}`){return r1($)}async function D0($){try{let W=JSON.parse(await pV($,"utf8"));if(typeof W.hubId!=="string"||typeof W.protocolVersion!=="string"||typeof W.authToken!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string"||typeof W.startedAt!=="string"||typeof W.updatedAt!=="string")return;return{hubId:W.hubId,protocolVersion:W.protocolVersion,minClientProtocolVersion:typeof W.minClientProtocolVersion==="string"?W.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof W.maxClientProtocolVersion==="string"?W.maxClientProtocolVersion:void 0,capabilities:Array.isArray(W.capabilities)?W.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,authToken:W.authToken,host:W.host,port:W.port,url:W.url,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:W.startedAt,updatedAt:W.updatedAt}}catch{return}}async function zW($,W){await a7(iV($),{recursive:!0}),await o7($,{force:!0}).catch(()=>{return}),await rV($,`${JSON.stringify(W,null,2)}
277
+ `,{encoding:"utf8",mode:384}),await OT($,384)}async function g0($){await o7($,{force:!0}).catch(()=>{return})}async function qW($,W){let Z=PT($);await a7(iV(Z),{recursive:!0});let Q=Date.now()+MT;while(!0)try{await a7(Z,{recursive:!1}),await rV(s7(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
278
+ `,"utf8");try{return await W()}finally{await lV(Z)}}catch(J){if((J instanceof Error&&"code"in J?String(J.code):"")!=="EEXIST")throw J;let X=await ST(Z),Y=X?Date.now()-Date.parse(X.acquiredAt):dV+1;if(!X||!wT(X.pid)||Y>dV){await lV(Z);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${Z}`);await CT(RT)}}async function i1($,W){try{let Z=await fetch(W?.authToken?t7($):MW($),{headers:W?.authToken?{authorization:`Bearer ${W.authToken}`}:void 0});if(!Z.ok)return;let Q=await Z.json();if(typeof Q.protocolVersion!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string")return;return{protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((J)=>typeof J==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,host:Q.host,port:Q.port,url:Q.url,hubId:typeof Q.hubId==="string"?Q.hubId:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:typeof Q.startedAt==="string"?Q.startedAt:void 0,updatedAt:typeof Q.updatedAt==="string"?Q.updatedAt:void 0}}catch{return}}function Y1($,W,Z="/hub"){return new URL(`ws://${$}:${W}${Z}`).toString()}function MW($){let W=new URL($);return W.protocol=W.protocol==="wss:"?"https:":"http:",W.pathname="/health",W.search="",W.toString()}function t7($){let W=new URL(MW($));return W.pathname="/status",W.toString()}function oV($){return TT($)}import{CLINE_HUB_DEV_PORT as bT,CLINE_HUB_PORT as yT,resolveClineBuildEnv as hT}from"@cline/shared";var kT="CLINE_HUB_HOST",IT="CLINE_HUB_PORT",xT="CLINE_HUB_PATHNAME",e7="127.0.0.1",$3=yT,W3="/hub";function sV($){return hT($)==="development"?bT:$3}function Z3($={}){return($.env??process.env)[kT]?.trim()||e7}function E8($={}){let Z=($.env??process.env)[IT]?.trim();if(!Z)return sV($);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return sV($);return Q}function Q3($={}){return($.env??process.env)[xT]?.trim()||W3}function T1($={},W={}){return{host:$.host??Z3(W),port:$.port??E8(W),pathname:$.pathname??Q3(W)}}import{join as gT}from"node:path";var mT="shared:cline",vT="CLINE_HUB_DISCOVERY_PATH",cT="hub-production";function tV($){let W=_1($.trim());return r1(`workspace:${W||$.trim()}`)}function V1($=mT){return r1($)}function O1(){return{ownerId:cT,discoveryPath:process.env[vT]?.trim()||gT(Y2(),"locks","hub","production.json")}}var eT=8000,$O=200,WO=3000,ZO=100,QO=[100,250,500,1000,2000],JO="--cline-hub-daemon";function jO($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function XO(){try{let $=nT(Y2(),"logs","hub-daemon.log");return lT(iT($),{recursive:!0}),{fd:pT($,"a"),logPath:$}}catch{return}}function ZB(){return WB()==="production"?O1():V1()}function V2($){return sT($).compatible}function eV($,W,Z){if(!W||W.url!==Z)return $;return{...$,authToken:$.authToken??W.authToken,pid:$.pid??W.pid}}async function B2($,W){try{return await i1($,{authToken:W})}catch{return}}async function YO($,W){let Z=Date.now()+W;while(Date.now()<Z){if(!(await B2($))?.url)return!0;await new Promise((J)=>setTimeout(J,ZO))}return!1}async function RW($,W){if(await L4($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Z=await YO($.url,WO);return await g0(W).catch(()=>{return}),Z}async function f4($,W){if(V2($))return!0;return RW($,W)}async function QB($){if(WB()!=="production")return;let W=V1();if(W.discoveryPath===$.discoveryPath)return;let Z=await D0(W.discoveryPath);if(Z?.url)await RW(Z,W.discoveryPath);else await g0(W.discoveryPath).catch(()=>{return})}function VO(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return aT(new URL(`./entry.${$}`,import.meta.url))}function BO($,W){let Z=VO(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let J=rT(Q).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),X=J&&Z.toLowerCase().endsWith(".ts"),Y=j?[JO]:[...X?["--conditions=development"]:[],Z];return{launcher:Q,args:[...Y,"--cwd",$,...jO(W)],cwd:$,env:{...tT(process.env),CLINE_NO_INTERACTIVE:"1",[oT]:"1"}}}function HO($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function J3($,W={}){if($B())return;let Z=BO($,W),Q=XO();try{uT(Z.launcher,Z.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(Q)dT(Q.fd)}}async function N8($,W={}){for(let Z=0;;Z++)try{J3($,W);return}catch(Q){let J=QO[Z];if(!HO(Q)||J===void 0)throw Q;await new Promise((j)=>setTimeout(j,J))}}function EW($,W={}){if($B())return;let Z=ZB(),Q=T1(W),J=Y1(Q.host,Q.port,Q.pathname),j=W.allowPortFallback===!0&&Q.port!==0;QB(Z).catch(()=>{return}).then(()=>D0(Z.discoveryPath)).then(async(X)=>{let Y=!1;if(X?.url)if(!X.authToken){if(Y=!0,!await RW(X,Z.discoveryPath)&&!j)return}else{let H=await B2(X.url,X.authToken);if(H?.url&&V2(H)&&await z1(H.url,{authToken:X.authToken}))return;if(H?.url)await f4({...H,authToken:X.authToken},Z.discoveryPath);else await g0(Z.discoveryPath).catch(()=>{return})}let V=await B2(J);if(V?.url){if(V2(V)){if(!j||!Y)return}else if(!await f4({...V,authToken:void 0},Z.discoveryPath)&&!j)return}let B=j?{...Q,port:0}:Q;await N8($,B)}).catch(()=>{})}async function JB($,W={}){let Z=ZB(),Q=W.host!==void 0||W.port!==void 0||W.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=T1(W),j=Y1(J.host,J.port,J.pathname),X=(F)=>{if(!Q)O$(F.url,F.authToken);return F};await QB(Z).catch(()=>{return});let Y=await D0(Z.discoveryPath),V=!1;if(Y?.url){let F=Y.authToken;if(!F)V=!0,await RW(Y,Z.discoveryPath);else{let A=await B2(Y.url,F);if(A?.url&&V2(A)&&await z1(A.url,{authToken:F}))return X({url:A.url,authToken:F});if(A?.url)await f4({...A,authToken:F},Z.discoveryPath);else await g0(Z.discoveryPath).catch(()=>{return})}}let B=await B2(j);if(B?.url){let F=eV(B,Y,j);if(V2(B))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${V?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await f4(F,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let G=W.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await N8($,G);let K=Date.now()+eT;while(Date.now()<K){let F=await D0(Z.discoveryPath);if(F?.url&&F.authToken){let D=await B2(F.url,F.authToken);if(D?.url&&V2(D)&&await z1(D.url,{authToken:F.authToken}))return X({url:D.url,authToken:F.authToken})}let A=await B2(j);if(A?.url&&!V2(A)){let D=eV(A,F,j);if(!await f4(D,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((D)=>setTimeout(D,$O))}throw Error("Timed out waiting for detached hub startup.")}function NW(){return FO()==="production"?O1():V1()}function UO(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function BB($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((W)=>Buffer.from(W))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return BB($.data);return String($)}function DO($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function jB($){let W=$,Z=DO(W.reason);return new y0("hub_connection_closed",W.code||Z?`Hub connection closed (code=${W.code??0}${Z?`, reason=${Z}`:""})`:j3,{closeCode:W.code,closeReason:Z||void 0})}function _O($,W){if($ instanceof y0)return $;if($ instanceof Error)return new y0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new y0("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new y0("hub_connect_failed",Z);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new y0("hub_connect_failed",Q?`Failed to connect to hub at ${W.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${W.toString()}.`)}var fO=8000,LO=200,XB="*",YB=8000,TO="cline-hub-auth.",HB=new Map,GB=new Set,OO=3000,zO=3000,qO=100,j3="Hub connection closed",MO=250,RO=5000,VB=0.5;class y0 extends Error{code;details;constructor($,W,Z){super(W);this.code=$;this.details=Z;this.name="HubTransportError"}}function V3($){return $ instanceof y0}class w8 extends Error{command;code;constructor($,W,Z){super(Z);this.command=$;this.code=W;this.name="HubCommandError"}}function wW($,W){return $ instanceof w8&&$.code==="hub_command_timeout"&&(W===void 0||$.command===W)}function KB($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=B3($.toString());return Z?HB.get(Z):void 0}function EO($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function B3($){if(!EO($))return;let W=new URL(z$($));return W.search="",W.hash="",W.toString()}function X3($){let W=B3($);return!!W&&GB.has(W)}function O$($,W){let Z=B3($);if(Z){if(GB.add(Z),W?.trim())HB.set(Z,W)}return $}class B1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new y0("hub_connection_closed",j3);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),W=this.options.authToken?.trim()||KB($);$.hash="";let Q=new(UO())($.toString(),W?[`${TO}${W}`]:void 0);this.socket=Q;let J=!1;this.connectPromise=new Promise((j,X)=>{let Y=!1,V=setTimeout(()=>{if(Y)return;Y=!0,J=!0,this.lastCloseError=new y0("hub_connect_timeout",`Timed out connecting to hub after ${YB}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}X(this.lastCloseError)},YB);Q.addEventListener("open",()=>{if(Y)return;Y=!0,clearTimeout(V),j()}),Q.addEventListener("error",(B)=>{if(Y)return;Y=!0,clearTimeout(V),this.lastCloseError=_O(B,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),Q.addEventListener("close",(B)=>{if(Y)return;if(Y=!0,clearTimeout(V),!J)this.lastCloseError=jB(B),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),Q.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(BB(j)))}),Q.addEventListener("close",(j)=>{if(this.socket!==Q)return;if(!J)this.lastCloseError=jB(j),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,W){let Z=W?.sessionId?.trim()||void 0,Q={listener:$,sessionId:Z};return this.listeners.add(Q),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(Z,-1)}}async command($,W,Z,Q){let J=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,W,Z,Q)}catch(X){if(!j||J>=1||!await this.recoverLocalHubTransport(X))throw X;J+=1}}async commandOnce($,W,Z,Q){await this.connect();let J=GO("hubreq_"),j=AO($,Q?.timeoutMs),X=new Promise((V,B)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;B(new w8($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${J}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(J,{resolve:(G)=>{if(H)clearTimeout(H);V(G)},reject:(G)=>{if(H)clearTimeout(H);B(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:J,clientId:this.clientId,sessionId:Z,timeoutMs:j,payload:W}})}catch(V){throw this.pendingReplies.delete(J),V}let Y=await X;if(!Y.ok){if(Y.error?.code===X2){let V=Z??(typeof W?.sessionId==="string"?W.sessionId:void 0);throw new l1(V,Y.error.message)}throw new w8($,Y.error?.code,Y.error?.message??`Hub command ${$} failed`)}return Y}async recoverLocalHubTransport($){if(!X3(this.currentUrl)||!V3($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let W=await H2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!W)return!1;return this.currentUrl=W,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(MO*2**this.reconnectAttempt,RO),W=Math.round($*(1-VB)+Math.random()*$*VB);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},W)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!X3(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await H2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!$)return;this.lastCloseError=new y0("hub_connection_closed",j3),this.sawSocketClose=!1;for(let W of this.pendingReplies.values())W.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new y0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,W){this.sendFrame({kind:$,clientId:this.clientId,...W?{sessionId:W}:{}})}adjustSubscriptionCount($,W){let Z=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(Z)??0)+W;if(Q<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(W<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,Q),W>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??XB}subscriptionSessionIdFromKey($){return $===XB?void 0:$}handleFrame($){switch($.kind){case"reply":{let W=$.envelope.requestId;if(!W)return;let Z=this.pendingReplies.get(W);if(!Z)return;this.pendingReplies.delete(W),Z.resolve($.envelope);return}case"event":for(let W of this.listeners){if(W.sessionId&&W.sessionId!==$.envelope.sessionId?.trim())continue;W.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function z$($){let W=new URL($);if(W.protocol==="http:")W.protocol="ws:";else if(W.protocol==="https:")W.protocol="wss:";return W.toString()}async function z1($,W){let Z=new B1({url:$,authToken:W?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function Y3($,W){let Z=z$($),Q=await i1(Z,{authToken:W?.authToken});if(!Q)return{status:"unreachable",url:Z};if(!KO(Q).compatible)return{status:"protocol_mismatch",url:Z};if(W?.verifyConnection===!0&&!await z1(Z,{workspaceRoot:W.workspaceRoot,cwd:W.cwd,authToken:W.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function NO($){let W=Date.now()+fO;while(Date.now()<W){let Z=await D0($.discoveryPath);if(Z?.url){let Q=await Y3(Z.url,{verifyConnection:!0,authToken:Z.authToken});if(Q.status==="compatible")return O$(Q.url,Z.authToken)}await new Promise((Q)=>setTimeout(Q,LO))}return}async function wO($){let W=Date.now()+zO;while(Date.now()<W){if(!(await i1($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,qO))}return!1}function CO($,W){try{return z$($)===z$(W)}catch{return!1}}function PO($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function SO($,W,Z){let Q=new B1({url:$,authToken:W,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let J=await Q.command("session.list",{limit:500},void 0,{timeoutMs:OO});return!PO(J.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function T4($={}){if($.endpoint?.trim()){let J=await Y3($.endpoint);return J.status==="compatible"?J.url:void 0}let W=NW(),Z=await D0(W.discoveryPath);if(!Z?.url)return;let Q=await Y3(Z.url,{authToken:Z.authToken});if(Q.status==="compatible")return O$(Q.url,Z.authToken);if(Q.status==="protocol_mismatch")await g0(W.discoveryPath).catch(()=>{return});return}async function H2($={}){let W=await T4($);if(W&&await z1(W,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return W;if($.endpoint?.trim())return;let Z=NW();return await N8($.workspaceRoot??process.cwd()),await NO(Z)}async function L4($,W){let Z=new URL($),Q=W?.trim()||KB(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function H3($=NW()){let W=await D0($.discoveryPath);if(!W?.url)return!1;try{if(await L4(W.url,W.authToken))return!0}catch{}return!1}async function CW($){if(!X3($.url))return;let W=NW(),Z=await D0(W.discoveryPath);if(!Z?.url||!CO(Z.url,$.url))return;if(!await SO(Z.url,Z.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await H3())return;if(!await wO(Z.url))return;return await g0(W.discoveryPath).catch(()=>{return}),await H2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{resolveClineBuildEnv as bO}from"@cline/shared";function yO($,W){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Z?`Failed to connect to hub at ${W} (${Z} event before socket open).`:`Failed to connect to hub at ${W}.`)}var hO="cline-hub-auth.";function kO($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function IO($,W){let Z=new URL($),Q=new URL(W);return Z.search="",Z.hash="",Q.search="",Q.hash="",Z.toString()===Q.toString()}function FB(){return bO()==="production"?O1():V1()}async function xO($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=FB(),Q=await D0(Z.discoveryPath);if(Q?.url&&IO($.toString(),Q.url))return Q.authToken;return}async function G3($={}){let W=T1($);if(!kO($)){let Z=FB(),Q=await D0(Z.discoveryPath);if(Q?.url)return Q.url}return Y1(W.host,W.port,W.pathname)}async function PW($){return await new Promise((W,Z)=>{(async()=>{let Q=new URL($),J=await xO(Q);Q.hash="";let j=new WebSocket(Q.toString(),J?[`${hO}${J}`]:void 0),X=new Map,Y=0;j.addEventListener("open",()=>{W({send(V){let B=V.requestId??`hub-client-${++Y}`;return new Promise((H,G)=>{X.set(B,{resolve:H,reject:G});let K={kind:"command",envelope:{...V,requestId:B}};j.send(JSON.stringify(K))})},close(){j.close()}})}),j.addEventListener("message",(V)=>{let B=JSON.parse(String(V.data));if(B.kind==="reply"&&B.envelope.requestId){let H=X.get(B.envelope.requestId);if(H)X.delete(B.envelope.requestId),H.resolve(B.envelope)}}),j.addEventListener("close",()=>{for(let V of X.values())V.reject(Error("Hub connection closed"));X.clear()}),j.addEventListener("error",(V)=>{Z(yO(V,$))})})().catch(Z)})}async function AB($){try{return(await PW($)).close(),!0}catch{return!1}}async function UB($,W){let Z=await G3($),Q=await PW(Z);try{return await Q.send({version:W.version??"v1",clientId:W.clientId??"hub-client",...W})}finally{Q.close()}}function K3($){return $?JSON.parse(JSON.stringify($)):{}}function SW($){let W=$?.session&&typeof $.session==="object"?$.session:void 0;if(!W)return;let Z=W.metadata&&typeof W.metadata==="object"?K3(W.metadata):void 0;return{sessionId:typeof W.sessionId==="string"?W.sessionId:"",parentSessionId:typeof Z?.parentSessionId==="string"?Z.parentSessionId:void 0,messagesPath:typeof Z?.messagesPath==="string"?Z.messagesPath:void 0,metadata:Z}}function DB($,W){return $.error?.message??`hub command failed: ${W}`}function gO($){let W=K3($);if(typeof W.error==="string"&&W.error.trim())return{...W,error:W.error.trim()};let Z=W.result&&typeof W.result==="object"?W.result:void 0;if(typeof Z?.text==="string"&&Z.text.trim())return{...W,error:Z.text.trim()};let Q=Z?.error&&typeof Z.error==="object"?Z.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...W,error:Q.message.trim()};return W}function _B($){let W=$?.sessionId;return typeof W==="string"&&W.trim()?W.trim():void 0}function mO($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))throw Error("hub checkpoint restore returned no checkpoint");let Z=W;if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Z}function vO($){let W=K3($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||_B(W)||"",eventType:"schedule.execution.completed",payload:W};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||_B(W)||"",eventType:"schedule.execution.failed",payload:W};let Z=$.sessionId?.trim();if(!Z)return;switch($.event){case"iteration.started":return{sessionId:Z,eventType:"runtime.chat.iteration_start",payload:W};case"iteration.finished":return{sessionId:Z,eventType:"runtime.chat.iteration_end",payload:W};case"assistant.delta":return{sessionId:Z,eventType:"runtime.chat.text_delta",payload:W};case"usage.updated":return{sessionId:Z,eventType:"runtime.chat.usage",payload:W};case"session.notice":return{sessionId:Z,eventType:"runtime.chat.notice",payload:W};case"tool.started":return{sessionId:Z,eventType:"runtime.chat.tool_call_start",payload:W};case"tool.finished":return{sessionId:Z,eventType:"runtime.chat.tool_call_end",payload:W};case"approval.requested":return{sessionId:Z,eventType:"approval.requested",payload:W};case"run.aborted":return{sessionId:Z,eventType:"runtime.chat.aborted",payload:W};case"run.failed":return{sessionId:Z,eventType:"runtime.chat.failed",payload:gO($.payload)};case"run.completed":return{sessionId:Z,eventType:"runtime.chat.completed",payload:W};default:return}}class F3{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new B1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let W=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Z=SW(W.payload);if(!Z?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:"",messagesPath:Z.messagesPath??""}}}async sendRuntimeSession($,W,Z){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:W.prompt,mode:W.config.mode,attachments:W.attachments,delivery:W.delivery,timeoutSeconds:W.config.timeoutSeconds},$,Z)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(p1(Z))return;throw Z}return SW(W.payload)}async readMessages($){let W=$.trim();if(!W)return[];await this.ensureMetadataApplied();let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Error(DB(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,J=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},W);if(!J.ok)throw Error(DB(J,"session.restore"));let j=SW(J.payload);if(Z&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let X=Array.isArray(J.payload?.messages)?J.payload.messages:void 0,Y=mO(J.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...X?{messages:X}:{},checkpoint:Y}}async listSessions($){await this.ensureMetadataApplied();let W=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(W.payload?.sessions)?W.payload?.sessions:[]).map((Q)=>SW({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,W=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:W})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,W){let Z=new Set(($.sessionIds??[]).map((J)=>J.trim()).filter(Boolean)),Q=this.client.subscribe((J)=>{let j=vO(J);if(!j)return;if(Z.size>0&&!Z.has(j.sessionId))return;W.onEvent?.(j)});return this.ensureMetadataApplied().catch((J)=>{W.onError?.(J instanceof Error?J:Error(String(J)))}),Q}streamTeamProgress($,W){let Z=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;W.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{W.onError?.(Q instanceof Error?Q:Error(String(Q)))}),Z}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let W=await this.client.command("schedule.list");return Array.isArray(W.payload?.schedules)?W.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,W){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...W})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,W){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.list_executions",{scheduleId:$,limit:W});return Array.isArray(Z.payload?.executions)?Z.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let W=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(W.payload?.upcoming)?W.payload?.upcoming:[]}}class A3{client;constructor($){this.client=new B1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let W=await this.client.command("session.list",{limit:$});return Array.isArray(W.payload?.sessions)?W.payload.sessions:[]}subscribeUI($){return this.client.subscribe((W)=>{switch(W.event){case"ui.notify":$.onNotify?.(W.payload);break;case"ui.show_window":$.onShowWindow?.(W.payload);break;case"hub.client.registered":$.onClientRegistered?.(W.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(W.payload??{});break;case"session.created":$.onSessionCreated?.(W.payload??{});break;case"session.updated":$.onSessionUpdated?.(W.payload??{});break;case"session.detached":$.onSessionDetached?.(W.payload??{});break}})}}import{normalizeProviderId as Ym}from"@cline/llms";var __={};w(__,{LocalRuntimeHost:()=>b1});import{readdirSync as tg}from"node:fs";import{homedir as eg}from"node:os";import{isAbsolute as $m,join as EY,resolve as NY}from"node:path";import{captureSdkError as s$,createSessionId as Wm,isLikelyAuthError as Zm,normalizeUserInput as Qm}from"@cline/shared";import{setHomeDirIfUnset as Jm}from"@cline/shared/storage";var iB={};w(iB,{saveProviderOAuthCredentials:()=>F2,resolveProviderApiKeyFromSettings:()=>C3,loginAndSaveProviderOAuthCredentials:()=>C4,isOAuthProvider:()=>K2,getProviderOAuthCredentialsFromSettings:()=>P4,getProviderAuthStorageId:()=>w3,getProviderAuthHandler:()=>H0,getPersistedProviderApiKey:()=>h8,formatProviderOAuthApiKey:()=>P3});import{decodeJwtPayload as Lz,getClineEnvironmentConfig as pB}from"@cline/shared";var wB={};w(wB,{startClineDeviceAuth:()=>z3,refreshClineToken:()=>kW,loginClineOAuth:()=>O4,getValidClineCredentials:()=>z4,completeClineDeviceAuth:()=>q3});import{getClineEnvironmentConfig as _3}from"@cline/shared";var fB={};w(fB,{setSdkLogger:()=>D3,sdkDebug:()=>s,hashSecret:()=>N0,getSdkLogger:()=>uO});import{createHash as cO}from"node:crypto";var U3;function D3($){U3=$}function uO(){return U3}function N0($){if(typeof $!=="string"||$.length===0)return"unset";return cO("sha256").update($).digest("hex").slice(0,8)}function s($){try{U3?.debug($)}catch{}}z0();var LB={};w(LB,{startLocalOAuthServer:()=>H1});function dO(){let $;return{promise:new Promise((Z)=>{$=Z}),resolve:$}}async function H1($){let W=await import("node:http"),Z=$.host??"127.0.0.1",Q=$.timeoutMs??300000,J=$.successHtml??lO,j=dO(),X=!1,Y=null,V=null,B=null,H=(F)=>{if(X)return;X=!0,j.resolve(F)},G=()=>{if(Y)clearTimeout(Y),Y=null;let F=B;if(B=null,V)V.close(),V.closeAllConnections?.(),V=null;if(F!==null&&$.onClose)Promise.resolve($.onClose({host:Z,port:F})).catch(()=>{})},K=async()=>{return Y=setTimeout(()=>{G(),H(null)},Q),j.promise};for(let F of $.ports){let A=W.createServer((U,f)=>{try{let _=new URL(U.url||"",`http://${Z}:${F}`);if(_.pathname!==$.callbackPath){f.statusCode=404,f.end("Not found");return}let R={url:_,code:_.searchParams.get("code")??void 0,state:_.searchParams.get("state")??void 0,provider:_.searchParams.get("provider")??void 0,error:_.searchParams.get("error")??void 0};if(R.error){f.statusCode=400,f.end(`Authentication failed: ${R.error}`),G(),H(R);return}if(!R.code){f.statusCode=400,f.end("Missing authorization code");return}if($.expectedState&&R.state!==$.expectedState){f.statusCode=400,f.end("State mismatch");return}f.statusCode=200,f.setHeader("Content-Type","text/html; charset=utf-8"),f.end(J),G(),H(R)}catch{f.statusCode=500,f.end("Internal error")}}),D=await new Promise((U)=>{let f=(_)=>{A.off("error",f),U({bound:!1,error:_})};A.once("error",f),A.listen(F,Z,()=>{A.off("error",f),V=A,U({bound:!0})})});if(D.error){if(D.error.code==="EADDRINUSE")continue;throw G(),D.error}if(D.bound){B=F;let U=`http://${Z}:${F}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Z,port:F,callbackUrl:U})).catch(()=>{});return{callbackUrl:U,waitForCallback:K,cancelWait:()=>{G(),H(null)},close:()=>{G(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var lO=`<!DOCTYPE html>
279
279
  <html lang="en">
280
280
  <head>
281
281
  <meta charset="utf-8">
@@ -316,27 +316,27 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
316
316
  </div>
317
317
  <script>setTimeout(() => window.close(), 3000);</script>
318
318
  </body>
319
- </html>`;function LB($){let W="";for(let Z=0;Z<$.length;Z+=1)W+=String.fromCharCode($[Z]??0);return btoa(W).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function lO($){let Z=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",Z);return new Uint8Array(Q)}function pO($=32){let W=new Uint8Array($);return crypto.getRandomValues(W),LB(W)}async function SW(){let $=pO(),W=LB(await lO($));return{verifier:$,challenge:W}}function bW($){return $.endsWith("/")?$.slice(0,-1):$}function G2($,W){return new URL(W,`${bW($)}/`).toString()}function C8($,W={}){let Z=$.trim();if(!Z)return{};try{let Q=new URL(Z);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:W.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(W.allowHashCodeState&&Z.includes("#")){let[Q,J]=Z.split("#",2);return{code:Q||void 0,state:J||void 0}}if(Z.includes("code=")){let Q=new URLSearchParams(Z);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:W.includeProvider?Q.get("provider")??void 0:void 0}}return{code:Z}}function P8($){try{let W=JSON.parse($),Z=W.error,Q=typeof Z==="string"?Z:Z&&typeof Z==="object"&&typeof Z.type==="string"?Z.type:void 0,J=typeof W.error_description==="string"?W.error_description:typeof W.message==="string"?W.message:Z&&typeof Z==="object"&&typeof Z.message==="string"?Z.message:void 0;return{code:Q,message:J}}catch{return{}}}function S8($,W){return Date.now()>=$.expires-W}async function b8($){if(!$.onManualCodeInput){let j=await $.waitForCallback();return{code:j?.code,state:j?.state,provider:j?.provider,error:j?.error}}let W,Z,Q=$.onManualCodeInput().then((j)=>{W=j,$.cancelWait()}).catch((j)=>{Z=j instanceof Error?j:Error(String(j)),$.cancelWait()}),J=await $.waitForCallback();if(Z)throw Z;if(J?.code||J?.error)return{code:J.code,state:J.state,provider:J.provider,error:J.error};if(W)return C8(W,$.parseOptions);if(await Q,Z)throw Z;if(W)return C8(W,$.parseOptions);return{}}var yW={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},qB={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},_3="https://api.workos.com",rO="/auth",TB=Array.from({length:11},($,W)=>48801+W),iO=300000,nO=30000,y8=30000,aO=300,oO=5;class q1 extends Error{status;errorCode;constructor($,W){super($);this.name="ClineOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function sO($){let W=Date.parse($);if(Number.isNaN(W))throw Error(`Invalid expiresAt value: ${$}`);return W}function f3($,W,Z={}){let Q=$.userInfo.clineUserId??Z.accountId,J=$.refreshToken??Z.refresh;if(!J)throw Error("Token response did not include a refresh token");let j={...Z.metadata??{},provider:W,tokenType:$.tokenType,userInfo:$.userInfo};return delete j.startedAt,{access:$.accessToken,refresh:J,expires:sO($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||Z.email,metadata:j}}async function L3($){if(!$)return{};return typeof $==="function"?await $():$}function OB($,W){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return W;return Math.floor($)}async function zB($){await new Promise((W)=>setTimeout(W,$))}function T3($,W){if(!$.success||!$.data?.accessToken)throw Error(W);return $.data}async function MB($,W){let Z=await fetch(G2(_3,qB.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(W?.requestTimeoutMs??y8)}),Q=await Z.json().catch(()=>({}));if(!Z.ok)throw new q1(`Device authorization failed: ${Z.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:Z.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:OB(Q.expires_in,aO),pollIntervalSeconds:OB(Q.interval,oO)}}async function RB($){let W=Date.now()+$.expiresInSeconds*1000,Z=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=W){let Q=await fetch(G2($.workosApiBaseUrl,qB.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),J=await Q.json().catch(()=>({}));if(Q.ok){if(!J.access_token||!J.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:J.access_token,refreshToken:J.refresh_token,tokenType:J.token_type??"Bearer"}}switch(J.error){case"authorization_pending":{await zB(Z*1000);break}case"slow_down":{Z+=1,await zB(Z*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new q1(J.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:J.error});default:throw new q1(`WorkOS token polling failed: ${Q.status}${J.error_description?` - ${J.error_description}`:""}`,{status:Q.status,errorCode:J.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function EB($,W,Z){let Q={accessToken:$.accessToken,refreshToken:$.refreshToken},J=await fetch(G2(W.apiBaseUrl,yW.register),{method:"POST",headers:{"Content-Type":"application/json",...await L3(W.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout(W.requestTimeoutMs??y8)});if(!J.ok){let X=await J.text().catch(()=>""),Y=P8(X);throw new q1(`Token registration failed: ${J.status}${Y.message?` - ${Y.message}`:""}`,{status:J.status,errorCode:Y.code})}let j=await J.json();return f3(T3(j,"Invalid token exchange response"),Z??W.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function tO($,W,Z,Q){let J={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:W,provider:Q??Z.provider},j=await fetch(G2(Z.apiBaseUrl,yW.token),{method:"POST",headers:{"Content-Type":"application/json",...await L3(Z.headers)},body:JSON.stringify(J),signal:AbortSignal.timeout(Z.requestTimeoutMs??y8)});if(!j.ok){let Y=await j.text().catch(()=>""),V=P8(Y);throw new q1(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let X=await j.json();return f3(T3(X,"Invalid token exchange response"),Q??Z.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function O4($){g1($.telemetry,$.provider??"cline");let W=$.useWorkOSDeviceAuth??!0,Z=$.callbackPorts?.length?$.callbackPorts:TB,Q=$.callbackPath??rO,J=W?null:await H1({ports:Z,callbackPath:Q,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=J?.callbackUrl||`http://127.0.0.1:${Z[0]??TB[0]}${Q}`;try{let X;if(W){let Y=D3().workOsClientId,V=await MB(Y,$);$.callbacks.onAuth({url:V.verificationUriComplete??V.verificationUri,instructions:`Enter this code in your browser: ${V.userCode}`});let B=await RB({clientId:Y,deviceCode:V.deviceCode,expiresInSeconds:V.expiresInSeconds,initialPollIntervalSeconds:V.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??y8,workosApiBaseUrl:_3,onProgress:$.callbacks.onProgress});X=await EB(B,$,$.provider)}else{let Y=new URL(G2($.apiBaseUrl,yW.authorize));Y.searchParams.set("client_type","extension"),Y.searchParams.set("callback_url",j),Y.searchParams.set("redirect_uri",j),$.callbacks.onAuth({url:Y.toString(),instructions:"Continue the authentication process in your browser."});let V,B=$.provider,H=await b8({waitForCallback:J?.waitForCallback??(async()=>null),cancelWait:J?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(H.error)throw Error(`OAuth error: ${H.error}`);if(V=H.code,B=H.provider??B,!V){let G=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),K=C8(G,{includeProvider:!0});V=K.code,B=K.provider??B}if(!V)throw Error("Missing authorization code");X=await tO(V,j,$,B)}return m1($.telemetry,$.provider??"cline"),c1($.telemetry,{id:X.accountId,email:X.email,provider:$.provider??"cline"}),X}catch(X){throw v1($.telemetry,$.provider??"cline",X instanceof Error?X.message:String(X)),X}finally{J?.close()}}async function O3($){return await MB(D3().workOsClientId,$)}async function z3($){let W=$.provider??"cline";g1($.telemetry,W);try{let Z=await RB({clientId:D3().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??y8,workosApiBaseUrl:_3}),Q=await EB(Z,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return m1($.telemetry,W),c1($.telemetry,{id:Q.accountId,email:Q.email,provider:W}),Q}catch(Z){throw v1($.telemetry,W,Z instanceof Error?Z.message:String(Z)),Z}}async function hW($,W){let Z=G2(W.apiBaseUrl,yW.refresh);s(`cline.refresh.request url=${Z} refreshTokenHash=${N0($.refresh)}`);let Q=await fetch(Z,{method:"POST",headers:{"Content-Type":"application/json",...await L3(W.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(W.requestTimeoutMs??y8)});if(!Q.ok){let Y=await Q.text().catch(()=>""),V=P8(Y);throw s(`cline.refresh.error status=${Q.status} errorCode=${V.code??"none"} message=${V.message??"none"}`),new q1(`Token refresh failed: ${Q.status}${V.message?` - ${V.message}`:""}`,{status:Q.status,errorCode:V.code})}let J=await Q.json(),j=$.metadata?.provider??W.provider,X=f3(T3(J,"Invalid token refresh response"),j,$);return s(`cline.refresh.success newAccessTokenHash=${N0(X.access)} newRefreshTokenHash=${N0(X.refresh)} expires=${X.expires}`),X}async function z4($,W,Z){if(!$)return s("cline.getCredentials outcome=no_current_credentials"),null;let Q=Z?.refreshBufferMs??iO,J=Z?.retryableTokenGraceMs??nO,j=Z?.forceRefresh===!0;if(!j&&!S8($,Q))return s(`cline.getCredentials outcome=still_valid forceRefresh=${j}`),$;s(`cline.getCredentials outcome=needs_refresh forceRefresh=${j} accessTokenHash=${N0($.access)}`);try{return await hW($,W)}catch(X){let Y={status:X instanceof q1?X.status:void 0,errorCode:X instanceof q1?X.errorCode:void 0,errorName:X instanceof Error?X.name:void 0};if(X instanceof q1&&X.isLikelyInvalidGrant())return s(`cline.getCredentials outcome=invalid_grant status=${X.status} errorCode=${X.errorCode??"none"}`),L$(W.telemetry,W.provider??"cline","invalid_grant",{status:X.status,errorCode:X.errorCode}),null;if($.expires-Date.now()>J)return s(`cline.getCredentials outcome=transient_failure_kept_current error=${X instanceof Error?X.message:String(X)}`),d7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!1}),$;throw s(`cline.getCredentials outcome=transient_failure_rethrown error=${X instanceof Error?X.message:String(X)}`),d7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!0}),X}}R0();var CB={};w(CB,{refreshOpenAICodexToken:()=>IW,loginOpenAICodex:()=>q4,getValidOpenAICodexCredentials:()=>M4,OPENAI_CODEX_OAUTH_CONFIG:()=>Y0});import{decodeJwtPayload as q3}from"@cline/shared";import{nanoid as eO}from"nanoid";var Y0={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class kW extends Error{status;errorCode;constructor($,W){super($);this.name="OpenAICodexOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function $z($,W,Z=Y0.redirectUri){let Q=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:Y0.clientId,code:$,code_verifier:W,redirect_uri:Z}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let J=await Q.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}async function Wz($){try{let W=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:Y0.clientId}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!W.ok){let Q=await W.text().catch(()=>""),J=P8(Q);throw new kW(`Token refresh failed: ${W.status}${J.message?` - ${J.message}`:""}`,{status:W.status,errorCode:J.code})}let Z=await W.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}catch(W){if(W instanceof kW)throw W;return{type:"failed"}}}async function Zz($="pi"){let{verifier:W,challenge:Z}=await SW(),Q=eO(32),J=new URL(Y0.authorizationEndpoint);return J.searchParams.set("response_type","code"),J.searchParams.set("client_id",Y0.clientId),J.searchParams.set("redirect_uri",Y0.redirectUri),J.searchParams.set("scope",Y0.scopes),J.searchParams.set("code_challenge",Z),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("state",Q),J.searchParams.set("id_token_add_organizations","true"),J.searchParams.set("codex_cli_simplified_flow","true"),J.searchParams.set("originator",$),{verifier:W,state:Q,url:J.toString()}}function Qz(){try{let $=new URL(Y0.redirectUri),W=$.port.length>0?Number.parseInt($.port,10):Y0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(W)?W:Y0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:Y0.callbackPort,callbackPath:"/auth/callback",redirectUri:Y0.redirectUri}}}function Jz($,W){let Z=W?q3(W):q3($),Q=Z?Z:q3($),j=Q?.[Y0.jwtClaimPath]?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;let X=Q?.organizations;if(Array.isArray(X)&&X.length>0){let V=X[0];if(typeof V?.id==="string"&&V.id.length>0)return V.id}let Y=Q?.chatgpt_account_id;if(typeof Y==="string"&&Y.length>0)return Y;return null}function wB($,W){let Z=Jz($.access,$.idToken)??W?.accountId;if(!Z)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||W?.refresh||"",expires:$.expires,accountId:Z,email:$.email??W?.email,metadata:{...W?.metadata??{},provider:"openai-codex"}}}async function q4($){g1($.telemetry,"openai-codex");let W=Qz(),{verifier:Z,state:Q,url:J}=await Zz($.originator),j=await H1({host:W.host,ports:[W.port],callbackPath:W.callbackPath,expectedState:Q});$.onAuth({url:J,instructions:"Continue the authentication process in your browser."});let X;try{let Y=await b8({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(Y.state&&Y.state!==Q)throw Error("State mismatch");if(X=Y.code,!X){let H=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),G=C8(H,{allowHashCodeState:!0});if(G.state&&G.state!==Q)throw Error("State mismatch");X=G.code}if(!X)throw Error("Missing authorization code");let V=await $z(X,Z,W.redirectUri);if(V.type!=="success")throw Error("Token exchange failed");let B=wB(V);return m1($.telemetry,"openai-codex"),c1($.telemetry,{id:B.accountId,email:B.email,provider:"openai-codex"}),B}catch(Y){throw v1($.telemetry,"openai-codex",Y instanceof Error?Y.message:String(Y)),Y}finally{j.close()}}async function IW($,W){let Z=await Wz($);if(Z.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=wB(Z,W);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function M4($,W){if(!$)return null;let Z=W?.refreshBufferMs??Y0.refreshBufferMs,Q=W?.retryableTokenGraceMs??Y0.retryableTokenGraceMs;if(W?.forceRefresh!==!0&&!S8($,Z))return $;try{return await IW($.refresh,$)}catch(j){if(j instanceof kW&&j.isLikelyInvalidGrant())return L$(W?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Q)return $;return null}}R0();var dB={};w(dB,{refreshOcaToken:()=>vW,loginOcaOAuth:()=>N4,getValidOcaCredentials:()=>w4,OCI_HEADER_OPC_REQUEST_ID:()=>jz,DEFAULT_INTERNAL_OCA_BASE_URL:()=>xW,DEFAULT_INTERNAL_IDCS_URL:()=>bB,DEFAULT_INTERNAL_IDCS_SCOPES:()=>yB,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>SB,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>gW,DEFAULT_EXTERNAL_IDCS_URL:()=>kB,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>IB,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>hB});import{decodeJwtPayload as R4}from"@cline/shared";import{nanoid as PB}from"nanoid";class M3{ttlMs;maxEntries;entries=new Map;constructor($,W){this.ttlMs=$;this.maxEntries=W}get($,W=Date.now()){this.pruneExpired(W);let Z=this.entries.get($);if(!Z)return;return this.entries.delete($),this.entries.set($,Z),Z.value}set($,W,Z=Date.now(),Q=this.ttlMs){this.pruneExpired(Z),this.entries.delete($);while(this.entries.size>=this.maxEntries){let J=this.entries.keys().next().value;if(J===void 0)break;this.entries.delete(J)}this.entries.set($,{value:W,expiresAt:Z+Q})}pruneExpired($){for(let[W,Z]of this.entries)if(Z.expiresAt<=$)this.entries.delete(W)}}var SB="a8331954c0cf48ba99b5dd223a14c6ea",bB="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",yB="openid offline_access",xW="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",hB="c1aba3deed5740659981a752714eba33",kB="https://login-ext.identity.oraclecloud.com",IB="openid offline_access",gW="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",jz="opc-request-id",Xz="/auth/oca",Yz=Array.from({length:11},($,W)=>48801+W),Vz=300000,Bz=30000,xB=30000,Hz=600000;class mW extends Error{status;errorCode;constructor($,W){super($);this.name="OcaOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var q$={internal:{clientId:SB,idcsUrl:bB,scopes:yB,baseUrl:xW},external:{clientId:hB,idcsUrl:kB,scopes:IB,baseUrl:gW}},E4=new Map,Gz=86400000,Kz=300000,Fz=32,R3=new M3(Gz,Fz);function gB($){if(typeof $==="function")return $();return $??"internal"}function mB($){return{internal:{clientId:$?.internal?.clientId??q$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??q$.internal.idcsUrl,scopes:$?.internal?.scopes??q$.internal.scopes,baseUrl:$?.internal?.baseUrl??q$.internal.baseUrl},external:{clientId:$?.external?.clientId??q$.external.clientId,idcsUrl:$?.external?.idcsUrl??q$.external.idcsUrl,scopes:$?.external?.scopes??q$.external.scopes,baseUrl:$?.external?.baseUrl??q$.external.baseUrl}}}function Az($=Date.now()){let W=$-Hz;for(let[Z,Q]of E4.entries())if(Q.createdAt<W)E4.delete(Z)}function Uz($,W,Z){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let J=R4(W)?.exp;if(typeof J==="number"&&J>0)return J*1000;let X=R4(Z)?.exp;if(typeof X==="number"&&X>0)return X*1000;return Date.now()+3600000}function vB($,W,Z){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let J=$.refresh_token??Z?.refresh;if(!J)throw Error("Token response did not include a refresh token");let j=R4($.id_token),X=R4(Q),Y=j?.sub??X?.sub,V=j?.email??X?.email;return{access:Q,refresh:J,expires:Uz($,Q,$.id_token),accountId:Y??Z?.accountId,email:V??Z?.email,metadata:{...Z?.metadata??{},provider:"oca",mode:W,subject:Y,idToken:$.id_token}}}async function cB($,W){let Z=bW($),Q=R3.get(Z);if(Q)return Q;let J=`${Z}/.well-known/openid-configuration`,j=await fetch(J,{method:"GET",signal:AbortSignal.timeout(W)});if(!j.ok){let V=`${Z}/oauth2/v1/token`;return R3.set(Z,V,Date.now(),Kz),V}let Y=(await j.json()).token_endpoint||`${Z}/oauth2/v1/token`;return R3.set(Z,Y),Y}function uB($){return{code:$.error,message:$.error_description}}async function Dz($){let W=E4.get($.state);if(!W)throw Error("No PKCE verifier found for this state");E4.delete($.state);let Z=$.mode==="external"?$.config.external:$.config.internal,Q=await cB(Z.idcsUrl,$.requestTimeoutMs),J=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:W.redirectUri,client_id:Z.clientId,code_verifier:W.verifier}),j=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J,signal:AbortSignal.timeout($.requestTimeoutMs)}),X=await j.json();if(!j.ok){let V=uB(X);throw new mW(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let Y=R4(X.id_token);if(!X.id_token||!Y)throw Error("No ID token received from OCA");if(Y.nonce!==W.nonce)throw Error("OIDC nonce verification failed");return vB(X,$.mode)}function _z($){let W=$.mode==="external"?$.config.external:$.config.internal,Z=new URL(`${bW(W.idcsUrl)}/oauth2/v1/authorize`);return Z.searchParams.set("client_id",W.clientId),Z.searchParams.set("response_type","code"),Z.searchParams.set("scope",W.scopes),Z.searchParams.set("code_challenge",$.challenge),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("redirect_uri",$.callbackUrl),Z.searchParams.set("state",$.state),Z.searchParams.set("nonce",$.nonce),Z.toString()}async function N4($){g1($.telemetry,"oca");let W=mB($.config),Z=gB($.mode),Q=$.callbackPorts?.length?$.callbackPorts:Yz,J=$.callbackPath??Xz,j=$.requestTimeoutMs??xB,X=await H1({ports:Q,callbackPath:J,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),Y=X.callbackUrl;if(!Y)throw Error("Unable to bind local OAuth callback server");let V=PB(16),B=PB(16),{verifier:H,challenge:G}=await SW();Az(),E4.set(V,{verifier:H,nonce:B,mode:Z,redirectUri:Y,createdAt:Date.now()});let K=_z({callbackUrl:Y,mode:Z,state:V,nonce:B,challenge:G,config:W});$.callbacks.onAuth({url:K,instructions:"Continue the authentication process in your browser."});try{let F=await b8({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),A=F.code,D=F.state;if(F.error)throw Error(`OAuth error: ${F.error}`);if(!A){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!D||D!==V)throw Error("State mismatch");let U=await Dz({code:A,state:D,mode:Z,config:W,requestTimeoutMs:j});return m1($.telemetry,"oca"),c1($.telemetry,{id:U.accountId,email:U.email,provider:"oca"}),U}catch(F){throw v1($.telemetry,"oca",F instanceof Error?F.message:String(F)),F}finally{X.close()}}async function vW($,W={}){let Z=mB(W.config),Q=W.requestTimeoutMs??xB,J=$.metadata?.mode,j=J==="internal"||J==="external"?J:gB(W.mode),X=j==="external"?Z.external:Z.internal,Y=await cB(X.idcsUrl,Q),V=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:X.clientId}),B=await fetch(Y,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:V,signal:AbortSignal.timeout(Q)}),H=await B.json();if(!B.ok){let G=uB(H);throw new mW(`Token refresh failed: ${B.status}${G.message?` - ${G.message}`:""}`,{status:B.status,errorCode:G.code})}return vB(H,j,$)}async function w4($,W,Z){if(!$)return null;let Q=W?.refreshBufferMs??Z?.refreshBufferMs??Vz,J=W?.retryableTokenGraceMs??Z?.retryableTokenGraceMs??Bz;if(W?.forceRefresh!==!0&&!S8($,Q))return $;try{return await vW($,Z)}catch(X){if(X instanceof mW&&X.isLikelyInvalidGrant())return L$(Z?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>J)return $;return null}}var cW="workos:";function Lz($){let W=$.trim();return W.toLowerCase().startsWith(cW)?W:`${cW}${W}`}function Tz($){let W=$.trim();return W.toLowerCase().startsWith(cW)?W.slice(cW.length):W}function Oz($){let Z=fz($)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return null}function zz($,W){let Z=$.auth?.expiresAt;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>0)return Z;let Q=Oz(W);if(Q)return Q;return Date.now()-1}function qz($,W){let Z=$.auth?.accessToken?.trim(),Q=$.auth?.refreshToken?.trim();if(!Z||!Q)return null;let J=W?.normalizeAccessToken?.(Z)??Z;if(!J)return null;return{access:J,refresh:Q,expires:zz($,J),accountId:$.auth?.accountId,metadata:$.auth?.metadata}}function Mz($){let W=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Z={...$.settings?.auth??{},accessToken:W,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Q=Object.fromEntries(Object.entries($.credentials.metadata??{}).filter(([,X])=>X!==void 0)),J={...$.settings?.auth?.metadata??{},...Q};if(Object.keys(J).length>0)Z.metadata=J;let j={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Z};if($.save!==!1)$.manager.saveProviderSettings(j,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return j}function E3($){let W=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:W,getApiKey(Z){let Q=Z?.auth?.accessToken?.trim();if(Q)return $.formatAccessToken?.(Q)??Q;return Z?.apiKey?.trim()||Z?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Z){return Mz({...Z,storageProviderId:W,formatAccessToken:$.formatAccessToken})},isConfigured(Z){return!!Z?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function pB($){return E3({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:Lz,normalizeStoredAccessToken:Tz,login:({settings:W,callbacks:Z,telemetry:Q})=>O4({apiBaseUrl:W?.baseUrl?.trim()||lB().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:Q}),refresh:({settings:W,credentials:Z,forceRefresh:Q,telemetry:J})=>z4(Z,{apiBaseUrl:W.baseUrl?.trim()||lB().apiBaseUrl,telemetry:J},{forceRefresh:Q})})}var Rz=[pB({providerId:"cline"}),pB({providerId:"cline-pass",storageProviderId:"cline"}),E3({providerId:"oca",login:({settings:$,callbacks:W,telemetry:Z})=>N4({mode:$?.oca?.mode,callbacks:W,telemetry:Z}),refresh:({settings:$,credentials:W,forceRefresh:Z,telemetry:Q})=>w4(W,{forceRefresh:Z,telemetry:Q},{mode:$.oca?.mode,telemetry:Q})}),E3({providerId:"openai-codex",login:({callbacks:$,telemetry:W})=>q4({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:W}),refresh:({credentials:$,forceRefresh:W,telemetry:Z})=>M4($,{forceRefresh:W,telemetry:Z})})],Ez=new Map(Rz.map(($)=>[$.providerId,$]));function H0($){return Ez.get($.trim().toLowerCase())}function K2($){return H0($)!==void 0}function N3($){return H0($)?.storageProviderId}function w3($,W){let Z=H0(W),Q=Z?.storageProviderId??W,J=$.getProviderSettings(Q);return Z?.getApiKey(J)??h8(W,J)}async function C4($,W,Z){let Q=H0(W);if(!Q)throw Error(`Provider "${W}" does not support OAuth login`);let J=$.getProviderSettings(Q.storageProviderId),j=await Q.login({settings:J,callbacks:Z.callbacks,telemetry:Z.telemetry});return Q.saveCredentials({manager:$,settings:J,credentials:j})}function P4($,W){let Z=H0($);if(!Z)return null;return qz(W,{normalizeAccessToken:Z.normalizeStoredAccessToken})}function F2($){let W=H0($.providerId);if(!W)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return W.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function h8($,W){let Z=H0($);if(Z)return Z.getApiKey(W);return W?.auth?.accessToken?.trim()||W?.apiKey?.trim()||W?.auth?.apiKey?.trim()||void 0}function C3($,W){let Z=H0($);if(!Z)return W.access;return Z.getApiKey({provider:Z.storageProviderId,auth:{accessToken:W.access}})??W.access}R0();var SH={};w(SH,{createContextCompactionPrepareTurn:()=>m4,createCompactionStateAwarePrepareTurn:()=>v4});import{estimateRequestInputTokens as Hq}from"@cline/shared";var tB={};w(tB,{projectSessionCompactionState:()=>A2,parseSessionCompactionState:()=>G1,createSessionCompactionState:()=>k8,SessionCompactionStateSchema:()=>S4});import{createHash as Nz}from"node:crypto";import{formatDisplayUserInput as iB}from"@cline/shared";import{z as M1}from"zod";function wz($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let W=$;if(W.role!=="user"&&W.role!=="assistant")return!1;return typeof W.content==="string"||Array.isArray(W.content)}var Cz=M1.custom(wz),S4=M1.object({version:M1.literal(1),updated_at:M1.string().datetime(),conversation_id:M1.string().min(1).optional(),source_message_count:M1.number().int().nonnegative(),source_prefix_hash:M1.string().min(1).optional(),source_last_message_key:M1.string().min(1).optional(),messages:M1.array(Cz),system_prompt:M1.string().optional()});function P3($){return JSON.parse(JSON.stringify($))}function nB($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:iB($.content)};return{...$,content:$.content.map((W)=>W.type==="text"?{...W,text:iB(W.text)}:W)}}function aB($){if($.includes(":"))throw TypeError("Message role cannot contain ':' in compaction boundary keys")}function Pz($){let W=nB($);return aB(W.role),[["role",W.role],["content",W.content],["id",W.id??null],["agent",W.agent??null],["sessionId",W.sessionId??null],["metadata",W.metadata??null],["modelInfo",W.modelInfo??null],["metrics",W.metrics??null],["ts",W.ts??null]]}function oB($){if(!$)return"";let W=nB($);if(typeof W.id==="string"&&W.id.trim())return`id:${W.id.trim()}`;if(aB(W.role),typeof W.ts==="number"&&Number.isFinite(W.ts))return`ts:${W.role}:${W.ts}`;return`content:${W.role}:${JSON.stringify(W.content)}`}function sB($,W=$.length){let Z=Nz("sha256");Z.update(`cline-session-compaction-source-v1
319
+ </html>`;function TB($){let W="";for(let Z=0;Z<$.length;Z+=1)W+=String.fromCharCode($[Z]??0);return btoa(W).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function pO($){let Z=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",Z);return new Uint8Array(Q)}function rO($=32){let W=new Uint8Array($);return crypto.getRandomValues(W),TB(W)}async function bW(){let $=rO(),W=TB(await pO($));return{verifier:$,challenge:W}}function yW($){return $.endsWith("/")?$.slice(0,-1):$}function G2($,W){return new URL(W,`${yW($)}/`).toString()}function C8($,W={}){let Z=$.trim();if(!Z)return{};try{let Q=new URL(Z);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:W.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(W.allowHashCodeState&&Z.includes("#")){let[Q,J]=Z.split("#",2);return{code:Q||void 0,state:J||void 0}}if(Z.includes("code=")){let Q=new URLSearchParams(Z);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:W.includeProvider?Q.get("provider")??void 0:void 0}}return{code:Z}}function P8($){try{let W=JSON.parse($),Z=W.error,Q=typeof Z==="string"?Z:Z&&typeof Z==="object"&&typeof Z.type==="string"?Z.type:void 0,J=typeof W.error_description==="string"?W.error_description:typeof W.message==="string"?W.message:Z&&typeof Z==="object"&&typeof Z.message==="string"?Z.message:void 0;return{code:Q,message:J}}catch{return{}}}function S8($,W){return Date.now()>=$.expires-W}async function b8($){if(!$.onManualCodeInput){let j=await $.waitForCallback();return{code:j?.code,state:j?.state,provider:j?.provider,error:j?.error}}let W,Z,Q=$.onManualCodeInput().then((j)=>{W=j,$.cancelWait()}).catch((j)=>{Z=j instanceof Error?j:Error(String(j)),$.cancelWait()}),J=await $.waitForCallback();if(Z)throw Z;if(J?.code||J?.error)return{code:J.code,state:J.state,provider:J.provider,error:J.error};if(W)return C8(W,$.parseOptions);if(await Q,Z)throw Z;if(W)return C8(W,$.parseOptions);return{}}var hW={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},MB={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},f3="https://api.workos.com",iO="/auth",OB=Array.from({length:11},($,W)=>48801+W),nO=300000,aO=30000,y8=30000,oO=300,sO=5;class q1 extends Error{status;errorCode;constructor($,W){super($);this.name="ClineOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function tO($){let W=Date.parse($);if(Number.isNaN(W))throw Error(`Invalid expiresAt value: ${$}`);return W}function L3($,W,Z={}){let Q=$.userInfo.clineUserId??Z.accountId,J=$.refreshToken??Z.refresh;if(!J)throw Error("Token response did not include a refresh token");let j={...Z.metadata??{},provider:W,tokenType:$.tokenType,userInfo:$.userInfo};return delete j.startedAt,{access:$.accessToken,refresh:J,expires:tO($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||Z.email,metadata:j}}async function T3($){if(!$)return{};return typeof $==="function"?await $():$}function zB($,W){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return W;return Math.floor($)}async function qB($){await new Promise((W)=>setTimeout(W,$))}function O3($,W){if(!$.success||!$.data?.accessToken)throw Error(W);return $.data}async function RB($,W){let Z=await fetch(G2(f3,MB.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(W?.requestTimeoutMs??y8)}),Q=await Z.json().catch(()=>({}));if(!Z.ok)throw new q1(`Device authorization failed: ${Z.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:Z.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:zB(Q.expires_in,oO),pollIntervalSeconds:zB(Q.interval,sO)}}async function EB($){let W=Date.now()+$.expiresInSeconds*1000,Z=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=W){let Q=await fetch(G2($.workosApiBaseUrl,MB.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),J=await Q.json().catch(()=>({}));if(Q.ok){if(!J.access_token||!J.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:J.access_token,refreshToken:J.refresh_token,tokenType:J.token_type??"Bearer"}}switch(J.error){case"authorization_pending":{await qB(Z*1000);break}case"slow_down":{Z+=1,await qB(Z*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new q1(J.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:J.error});default:throw new q1(`WorkOS token polling failed: ${Q.status}${J.error_description?` - ${J.error_description}`:""}`,{status:Q.status,errorCode:J.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function NB($,W,Z){let Q={accessToken:$.accessToken,refreshToken:$.refreshToken},J=await fetch(G2(W.apiBaseUrl,hW.register),{method:"POST",headers:{"Content-Type":"application/json",...await T3(W.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout(W.requestTimeoutMs??y8)});if(!J.ok){let X=await J.text().catch(()=>""),Y=P8(X);throw new q1(`Token registration failed: ${J.status}${Y.message?` - ${Y.message}`:""}`,{status:J.status,errorCode:Y.code})}let j=await J.json();return L3(O3(j,"Invalid token exchange response"),Z??W.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function eO($,W,Z,Q){let J={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:W,provider:Q??Z.provider},j=await fetch(G2(Z.apiBaseUrl,hW.token),{method:"POST",headers:{"Content-Type":"application/json",...await T3(Z.headers)},body:JSON.stringify(J),signal:AbortSignal.timeout(Z.requestTimeoutMs??y8)});if(!j.ok){let Y=await j.text().catch(()=>""),V=P8(Y);throw new q1(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let X=await j.json();return L3(O3(X,"Invalid token exchange response"),Q??Z.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function O4($){g1($.telemetry,$.provider??"cline");let W=$.useWorkOSDeviceAuth??!0,Z=$.callbackPorts?.length?$.callbackPorts:OB,Q=$.callbackPath??iO,J=W?null:await H1({ports:Z,callbackPath:Q,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=J?.callbackUrl||`http://127.0.0.1:${Z[0]??OB[0]}${Q}`;try{let X;if(W){let Y=_3().workOsClientId,V=await RB(Y,$);$.callbacks.onAuth({url:V.verificationUriComplete??V.verificationUri,instructions:`Enter this code in your browser: ${V.userCode}`});let B=await EB({clientId:Y,deviceCode:V.deviceCode,expiresInSeconds:V.expiresInSeconds,initialPollIntervalSeconds:V.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??y8,workosApiBaseUrl:f3,onProgress:$.callbacks.onProgress});X=await NB(B,$,$.provider)}else{let Y=new URL(G2($.apiBaseUrl,hW.authorize));Y.searchParams.set("client_type","extension"),Y.searchParams.set("callback_url",j),Y.searchParams.set("redirect_uri",j),$.callbacks.onAuth({url:Y.toString(),instructions:"Continue the authentication process in your browser."});let V,B=$.provider,H=await b8({waitForCallback:J?.waitForCallback??(async()=>null),cancelWait:J?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(H.error)throw Error(`OAuth error: ${H.error}`);if(V=H.code,B=H.provider??B,!V){let G=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),K=C8(G,{includeProvider:!0});V=K.code,B=K.provider??B}if(!V)throw Error("Missing authorization code");X=await eO(V,j,$,B)}return m1($.telemetry,$.provider??"cline"),c1($.telemetry,{id:X.accountId,email:X.email,provider:$.provider??"cline"}),X}catch(X){throw v1($.telemetry,$.provider??"cline",X instanceof Error?X.message:String(X)),X}finally{J?.close()}}async function z3($){return await RB(_3().workOsClientId,$)}async function q3($){let W=$.provider??"cline";g1($.telemetry,W);try{let Z=await EB({clientId:_3().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??y8,workosApiBaseUrl:f3}),Q=await NB(Z,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return m1($.telemetry,W),c1($.telemetry,{id:Q.accountId,email:Q.email,provider:W}),Q}catch(Z){throw v1($.telemetry,W,Z instanceof Error?Z.message:String(Z)),Z}}async function kW($,W){let Z=G2(W.apiBaseUrl,hW.refresh);s(`cline.refresh.request url=${Z} refreshTokenHash=${N0($.refresh)}`);let Q=await fetch(Z,{method:"POST",headers:{"Content-Type":"application/json",...await T3(W.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(W.requestTimeoutMs??y8)});if(!Q.ok){let Y=await Q.text().catch(()=>""),V=P8(Y);throw s(`cline.refresh.error status=${Q.status} errorCode=${V.code??"none"} message=${V.message??"none"}`),new q1(`Token refresh failed: ${Q.status}${V.message?` - ${V.message}`:""}`,{status:Q.status,errorCode:V.code})}let J=await Q.json(),j=$.metadata?.provider??W.provider,X=L3(O3(J,"Invalid token refresh response"),j,$);return s(`cline.refresh.success newAccessTokenHash=${N0(X.access)} newRefreshTokenHash=${N0(X.refresh)} expires=${X.expires}`),X}async function z4($,W,Z){if(!$)return s("cline.getCredentials outcome=no_current_credentials"),null;let Q=Z?.refreshBufferMs??nO,J=Z?.retryableTokenGraceMs??aO,j=Z?.forceRefresh===!0;if(!j&&!S8($,Q))return s(`cline.getCredentials outcome=still_valid forceRefresh=${j}`),$;s(`cline.getCredentials outcome=needs_refresh forceRefresh=${j} accessTokenHash=${N0($.access)}`);try{return await kW($,W)}catch(X){let Y={status:X instanceof q1?X.status:void 0,errorCode:X instanceof q1?X.errorCode:void 0,errorName:X instanceof Error?X.name:void 0};if(X instanceof q1&&X.isLikelyInvalidGrant())return s(`cline.getCredentials outcome=invalid_grant status=${X.status} errorCode=${X.errorCode??"none"}`),L$(W.telemetry,W.provider??"cline","invalid_grant",{status:X.status,errorCode:X.errorCode}),null;if($.expires-Date.now()>J)return s(`cline.getCredentials outcome=transient_failure_kept_current error=${X instanceof Error?X.message:String(X)}`),l7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!1}),$;throw s(`cline.getCredentials outcome=transient_failure_rethrown error=${X instanceof Error?X.message:String(X)}`),l7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!0}),X}}z0();var PB={};w(PB,{refreshOpenAICodexToken:()=>xW,loginOpenAICodex:()=>q4,getValidOpenAICodexCredentials:()=>M4,OPENAI_CODEX_OAUTH_CONFIG:()=>Y0});import{decodeJwtPayload as M3}from"@cline/shared";import{nanoid as $z}from"nanoid";var Y0={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class IW extends Error{status;errorCode;constructor($,W){super($);this.name="OpenAICodexOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function Wz($,W,Z=Y0.redirectUri){let Q=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:Y0.clientId,code:$,code_verifier:W,redirect_uri:Z}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let J=await Q.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}async function Zz($){try{let W=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:Y0.clientId}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!W.ok){let Q=await W.text().catch(()=>""),J=P8(Q);throw new IW(`Token refresh failed: ${W.status}${J.message?` - ${J.message}`:""}`,{status:W.status,errorCode:J.code})}let Z=await W.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}catch(W){if(W instanceof IW)throw W;return{type:"failed"}}}async function Qz($="pi"){let{verifier:W,challenge:Z}=await bW(),Q=$z(32),J=new URL(Y0.authorizationEndpoint);return J.searchParams.set("response_type","code"),J.searchParams.set("client_id",Y0.clientId),J.searchParams.set("redirect_uri",Y0.redirectUri),J.searchParams.set("scope",Y0.scopes),J.searchParams.set("code_challenge",Z),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("state",Q),J.searchParams.set("id_token_add_organizations","true"),J.searchParams.set("codex_cli_simplified_flow","true"),J.searchParams.set("originator",$),{verifier:W,state:Q,url:J.toString()}}function Jz(){try{let $=new URL(Y0.redirectUri),W=$.port.length>0?Number.parseInt($.port,10):Y0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(W)?W:Y0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:Y0.callbackPort,callbackPath:"/auth/callback",redirectUri:Y0.redirectUri}}}function jz($,W){let Z=W?M3(W):M3($),Q=Z?Z:M3($),j=Q?.[Y0.jwtClaimPath]?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;let X=Q?.organizations;if(Array.isArray(X)&&X.length>0){let V=X[0];if(typeof V?.id==="string"&&V.id.length>0)return V.id}let Y=Q?.chatgpt_account_id;if(typeof Y==="string"&&Y.length>0)return Y;return null}function CB($,W){let Z=jz($.access,$.idToken)??W?.accountId;if(!Z)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||W?.refresh||"",expires:$.expires,accountId:Z,email:$.email??W?.email,metadata:{...W?.metadata??{},provider:"openai-codex"}}}async function q4($){g1($.telemetry,"openai-codex");let W=Jz(),{verifier:Z,state:Q,url:J}=await Qz($.originator),j=await H1({host:W.host,ports:[W.port],callbackPath:W.callbackPath,expectedState:Q});$.onAuth({url:J,instructions:"Continue the authentication process in your browser."});let X;try{let Y=await b8({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(Y.state&&Y.state!==Q)throw Error("State mismatch");if(X=Y.code,!X){let H=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),G=C8(H,{allowHashCodeState:!0});if(G.state&&G.state!==Q)throw Error("State mismatch");X=G.code}if(!X)throw Error("Missing authorization code");let V=await Wz(X,Z,W.redirectUri);if(V.type!=="success")throw Error("Token exchange failed");let B=CB(V);return m1($.telemetry,"openai-codex"),c1($.telemetry,{id:B.accountId,email:B.email,provider:"openai-codex"}),B}catch(Y){throw v1($.telemetry,"openai-codex",Y instanceof Error?Y.message:String(Y)),Y}finally{j.close()}}async function xW($,W){let Z=await Zz($);if(Z.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=CB(Z,W);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function M4($,W){if(!$)return null;let Z=W?.refreshBufferMs??Y0.refreshBufferMs,Q=W?.retryableTokenGraceMs??Y0.retryableTokenGraceMs;if(W?.forceRefresh!==!0&&!S8($,Z))return $;try{return await xW($.refresh,$)}catch(j){if(j instanceof IW&&j.isLikelyInvalidGrant())return L$(W?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Q)return $;return null}}z0();var lB={};w(lB,{refreshOcaToken:()=>cW,loginOcaOAuth:()=>N4,getValidOcaCredentials:()=>w4,OCI_HEADER_OPC_REQUEST_ID:()=>Xz,DEFAULT_INTERNAL_OCA_BASE_URL:()=>gW,DEFAULT_INTERNAL_IDCS_URL:()=>yB,DEFAULT_INTERNAL_IDCS_SCOPES:()=>hB,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>bB,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>mW,DEFAULT_EXTERNAL_IDCS_URL:()=>IB,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>xB,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>kB});import{decodeJwtPayload as R4}from"@cline/shared";import{nanoid as SB}from"nanoid";class R3{ttlMs;maxEntries;entries=new Map;constructor($,W){this.ttlMs=$;this.maxEntries=W}get($,W=Date.now()){this.pruneExpired(W);let Z=this.entries.get($);if(!Z)return;return this.entries.delete($),this.entries.set($,Z),Z.value}set($,W,Z=Date.now(),Q=this.ttlMs){this.pruneExpired(Z),this.entries.delete($);while(this.entries.size>=this.maxEntries){let J=this.entries.keys().next().value;if(J===void 0)break;this.entries.delete(J)}this.entries.set($,{value:W,expiresAt:Z+Q})}pruneExpired($){for(let[W,Z]of this.entries)if(Z.expiresAt<=$)this.entries.delete(W)}}var bB="a8331954c0cf48ba99b5dd223a14c6ea",yB="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",hB="openid offline_access",gW="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",kB="c1aba3deed5740659981a752714eba33",IB="https://login-ext.identity.oraclecloud.com",xB="openid offline_access",mW="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",Xz="opc-request-id",Yz="/auth/oca",Vz=Array.from({length:11},($,W)=>48801+W),Bz=300000,Hz=30000,gB=30000,Gz=600000;class vW extends Error{status;errorCode;constructor($,W){super($);this.name="OcaOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var q$={internal:{clientId:bB,idcsUrl:yB,scopes:hB,baseUrl:gW},external:{clientId:kB,idcsUrl:IB,scopes:xB,baseUrl:mW}},E4=new Map,Kz=86400000,Fz=300000,Az=32,E3=new R3(Kz,Az);function mB($){if(typeof $==="function")return $();return $??"internal"}function vB($){return{internal:{clientId:$?.internal?.clientId??q$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??q$.internal.idcsUrl,scopes:$?.internal?.scopes??q$.internal.scopes,baseUrl:$?.internal?.baseUrl??q$.internal.baseUrl},external:{clientId:$?.external?.clientId??q$.external.clientId,idcsUrl:$?.external?.idcsUrl??q$.external.idcsUrl,scopes:$?.external?.scopes??q$.external.scopes,baseUrl:$?.external?.baseUrl??q$.external.baseUrl}}}function Uz($=Date.now()){let W=$-Gz;for(let[Z,Q]of E4.entries())if(Q.createdAt<W)E4.delete(Z)}function Dz($,W,Z){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let J=R4(W)?.exp;if(typeof J==="number"&&J>0)return J*1000;let X=R4(Z)?.exp;if(typeof X==="number"&&X>0)return X*1000;return Date.now()+3600000}function cB($,W,Z){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let J=$.refresh_token??Z?.refresh;if(!J)throw Error("Token response did not include a refresh token");let j=R4($.id_token),X=R4(Q),Y=j?.sub??X?.sub,V=j?.email??X?.email;return{access:Q,refresh:J,expires:Dz($,Q,$.id_token),accountId:Y??Z?.accountId,email:V??Z?.email,metadata:{...Z?.metadata??{},provider:"oca",mode:W,subject:Y,idToken:$.id_token}}}async function uB($,W){let Z=yW($),Q=E3.get(Z);if(Q)return Q;let J=`${Z}/.well-known/openid-configuration`,j=await fetch(J,{method:"GET",signal:AbortSignal.timeout(W)});if(!j.ok){let V=`${Z}/oauth2/v1/token`;return E3.set(Z,V,Date.now(),Fz),V}let Y=(await j.json()).token_endpoint||`${Z}/oauth2/v1/token`;return E3.set(Z,Y),Y}function dB($){return{code:$.error,message:$.error_description}}async function _z($){let W=E4.get($.state);if(!W)throw Error("No PKCE verifier found for this state");E4.delete($.state);let Z=$.mode==="external"?$.config.external:$.config.internal,Q=await uB(Z.idcsUrl,$.requestTimeoutMs),J=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:W.redirectUri,client_id:Z.clientId,code_verifier:W.verifier}),j=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J,signal:AbortSignal.timeout($.requestTimeoutMs)}),X=await j.json();if(!j.ok){let V=dB(X);throw new vW(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let Y=R4(X.id_token);if(!X.id_token||!Y)throw Error("No ID token received from OCA");if(Y.nonce!==W.nonce)throw Error("OIDC nonce verification failed");return cB(X,$.mode)}function fz($){let W=$.mode==="external"?$.config.external:$.config.internal,Z=new URL(`${yW(W.idcsUrl)}/oauth2/v1/authorize`);return Z.searchParams.set("client_id",W.clientId),Z.searchParams.set("response_type","code"),Z.searchParams.set("scope",W.scopes),Z.searchParams.set("code_challenge",$.challenge),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("redirect_uri",$.callbackUrl),Z.searchParams.set("state",$.state),Z.searchParams.set("nonce",$.nonce),Z.toString()}async function N4($){g1($.telemetry,"oca");let W=vB($.config),Z=mB($.mode),Q=$.callbackPorts?.length?$.callbackPorts:Vz,J=$.callbackPath??Yz,j=$.requestTimeoutMs??gB,X=await H1({ports:Q,callbackPath:J,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),Y=X.callbackUrl;if(!Y)throw Error("Unable to bind local OAuth callback server");let V=SB(16),B=SB(16),{verifier:H,challenge:G}=await bW();Uz(),E4.set(V,{verifier:H,nonce:B,mode:Z,redirectUri:Y,createdAt:Date.now()});let K=fz({callbackUrl:Y,mode:Z,state:V,nonce:B,challenge:G,config:W});$.callbacks.onAuth({url:K,instructions:"Continue the authentication process in your browser."});try{let F=await b8({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),A=F.code,D=F.state;if(F.error)throw Error(`OAuth error: ${F.error}`);if(!A){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!D||D!==V)throw Error("State mismatch");let U=await _z({code:A,state:D,mode:Z,config:W,requestTimeoutMs:j});return m1($.telemetry,"oca"),c1($.telemetry,{id:U.accountId,email:U.email,provider:"oca"}),U}catch(F){throw v1($.telemetry,"oca",F instanceof Error?F.message:String(F)),F}finally{X.close()}}async function cW($,W={}){let Z=vB(W.config),Q=W.requestTimeoutMs??gB,J=$.metadata?.mode,j=J==="internal"||J==="external"?J:mB(W.mode),X=j==="external"?Z.external:Z.internal,Y=await uB(X.idcsUrl,Q),V=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:X.clientId}),B=await fetch(Y,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:V,signal:AbortSignal.timeout(Q)}),H=await B.json();if(!B.ok){let G=dB(H);throw new vW(`Token refresh failed: ${B.status}${G.message?` - ${G.message}`:""}`,{status:B.status,errorCode:G.code})}return cB(H,j,$)}async function w4($,W,Z){if(!$)return null;let Q=W?.refreshBufferMs??Z?.refreshBufferMs??Bz,J=W?.retryableTokenGraceMs??Z?.retryableTokenGraceMs??Hz;if(W?.forceRefresh!==!0&&!S8($,Q))return $;try{return await cW($,Z)}catch(X){if(X instanceof vW&&X.isLikelyInvalidGrant())return L$(Z?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>J)return $;return null}}var uW="workos:";function Tz($){let W=$.trim();return W.toLowerCase().startsWith(uW)?W:`${uW}${W}`}function Oz($){let W=$.trim();return W.toLowerCase().startsWith(uW)?W.slice(uW.length):W}function zz($){let Z=Lz($)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return null}function qz($,W){let Z=$.auth?.expiresAt;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>0)return Z;let Q=zz(W);if(Q)return Q;return Date.now()-1}function Mz($,W){let Z=$.auth?.accessToken?.trim(),Q=$.auth?.refreshToken?.trim();if(!Z||!Q)return null;let J=W?.normalizeAccessToken?.(Z)??Z;if(!J)return null;return{access:J,refresh:Q,expires:qz($,J),accountId:$.auth?.accountId,metadata:$.auth?.metadata}}function Rz($){let W=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Z={...$.settings?.auth??{},accessToken:W,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Q=Object.fromEntries(Object.entries($.credentials.metadata??{}).filter(([,X])=>X!==void 0)),J={...$.settings?.auth?.metadata??{},...Q};if(Object.keys(J).length>0)Z.metadata=J;let j={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Z};if($.save!==!1)$.manager.saveProviderSettings(j,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return j}function N3($){let W=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:W,getApiKey(Z){let Q=Z?.auth?.accessToken?.trim();if(Q)return $.formatAccessToken?.(Q)??Q;return Z?.apiKey?.trim()||Z?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Z){return Rz({...Z,storageProviderId:W,formatAccessToken:$.formatAccessToken})},isConfigured(Z){return!!Z?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function rB($){return N3({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:Tz,normalizeStoredAccessToken:Oz,login:({settings:W,callbacks:Z,telemetry:Q})=>O4({apiBaseUrl:W?.baseUrl?.trim()||pB().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:Q}),refresh:({settings:W,credentials:Z,forceRefresh:Q,telemetry:J})=>z4(Z,{apiBaseUrl:W.baseUrl?.trim()||pB().apiBaseUrl,telemetry:J},{forceRefresh:Q})})}var Ez=[rB({providerId:"cline"}),rB({providerId:"cline-pass",storageProviderId:"cline"}),N3({providerId:"oca",login:({settings:$,callbacks:W,telemetry:Z})=>N4({mode:$?.oca?.mode,callbacks:W,telemetry:Z}),refresh:({settings:$,credentials:W,forceRefresh:Z,telemetry:Q})=>w4(W,{forceRefresh:Z,telemetry:Q},{mode:$.oca?.mode,telemetry:Q})}),N3({providerId:"openai-codex",login:({callbacks:$,telemetry:W})=>q4({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:W}),refresh:({credentials:$,forceRefresh:W,telemetry:Z})=>M4($,{forceRefresh:W,telemetry:Z})})],Nz=new Map(Ez.map(($)=>[$.providerId,$]));function H0($){return Nz.get($.trim().toLowerCase())}function K2($){return H0($)!==void 0}function w3($){return H0($)?.storageProviderId}function C3($,W){let Z=H0(W),Q=Z?.storageProviderId??W,J=$.getProviderSettings(Q);return Z?.getApiKey(J)??h8(W,J)}async function C4($,W,Z){let Q=H0(W);if(!Q)throw Error(`Provider "${W}" does not support OAuth login`);let J=$.getProviderSettings(Q.storageProviderId),j=await Q.login({settings:J,callbacks:Z.callbacks,telemetry:Z.telemetry});return Q.saveCredentials({manager:$,settings:J,credentials:j})}function P4($,W){let Z=H0($);if(!Z)return null;return Mz(W,{normalizeAccessToken:Z.normalizeStoredAccessToken})}function F2($){let W=H0($.providerId);if(!W)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return W.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function h8($,W){let Z=H0($);if(Z)return Z.getApiKey(W);return W?.auth?.accessToken?.trim()||W?.apiKey?.trim()||W?.auth?.apiKey?.trim()||void 0}function P3($,W){let Z=H0($);if(!Z)return W.access;return Z.getApiKey({provider:Z.storageProviderId,auth:{accessToken:W.access}})??W.access}z0();var bH={};w(bH,{createContextCompactionPrepareTurn:()=>m4,createCompactionStateAwarePrepareTurn:()=>v4});import{estimateRequestInputTokens as Gq}from"@cline/shared";var eB={};w(eB,{projectSessionCompactionState:()=>A2,parseSessionCompactionState:()=>G1,createSessionCompactionState:()=>k8,SessionCompactionStateSchema:()=>S4});import{createHash as wz}from"node:crypto";import{formatDisplayUserInput as nB}from"@cline/shared";import{z as M1}from"zod";function Cz($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let W=$;if(W.role!=="user"&&W.role!=="assistant")return!1;return typeof W.content==="string"||Array.isArray(W.content)}var Pz=M1.custom(Cz),S4=M1.object({version:M1.literal(1),updated_at:M1.string().datetime(),conversation_id:M1.string().min(1).optional(),source_message_count:M1.number().int().nonnegative(),source_prefix_hash:M1.string().min(1).optional(),source_last_message_key:M1.string().min(1).optional(),messages:M1.array(Pz),system_prompt:M1.string().optional()});function S3($){return JSON.parse(JSON.stringify($))}function aB($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:nB($.content)};return{...$,content:$.content.map((W)=>W.type==="text"?{...W,text:nB(W.text)}:W)}}function oB($){if($.includes(":"))throw TypeError("Message role cannot contain ':' in compaction boundary keys")}function Sz($){let W=aB($);return oB(W.role),[["role",W.role],["content",W.content],["id",W.id??null],["agent",W.agent??null],["sessionId",W.sessionId??null],["metadata",W.metadata??null],["modelInfo",W.modelInfo??null],["metrics",W.metrics??null],["ts",W.ts??null]]}function sB($){if(!$)return"";let W=aB($);if(typeof W.id==="string"&&W.id.trim())return`id:${W.id.trim()}`;if(oB(W.role),typeof W.ts==="number"&&Number.isFinite(W.ts))return`ts:${W.role}:${W.ts}`;return`content:${W.role}:${JSON.stringify(W.content)}`}function tB($,W=$.length){let Z=wz("sha256");Z.update(`cline-session-compaction-source-v1
320
320
  `),Z.update(`${W}
321
- `);for(let Q of $.slice(0,W))Z.update(JSON.stringify(Pz(Q))),Z.update(`
322
- `);return`sha256:${Z.digest("hex")}`}function k8($){let W=$.sourceMessages.at(-1),Z=oB(W);return S4.parse({version:1,updated_at:$.updatedAt??new Date().toISOString(),...$.conversationId?.trim()?{conversation_id:$.conversationId.trim()}:{},source_message_count:$.sourceMessages.length,source_prefix_hash:sB($.sourceMessages),...Z?{source_last_message_key:Z}:{},messages:P3($.compactedMessages),...$.systemPrompt!==void 0?{system_prompt:$.systemPrompt}:{}})}function A2($,W){if(!($.source_message_count<=W.length))return;let Q=!!$.source_prefix_hash&&sB(W,$.source_message_count)===$.source_prefix_hash,J=W[$.source_message_count-1],j=!$.source_prefix_hash&&$.source_message_count>0&&!!$.source_last_message_key&&oB(J)===$.source_last_message_key;if(!(Q||j))return;return[...P3($.messages),...P3(W.slice($.source_message_count))]}function G1($){let W=S4.safeParse($);return W.success?W.data:void 0}import{createHandlerAsync as oz}from"@cline/llms";function Sz($){switch($){case"agentic_summary":case"basic_compaction_projection":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!0,dropThinkingBlocks:!0};case"normal_provider_request":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!1,dropThinkingBlocks:!1}}}function eB($){return $.map((W)=>({...W,content:Array.isArray(W.content)?W.content.map((Z)=>({...Z})):W.content,...W.metadata?{metadata:{...W.metadata}}:{}}))}function R1($){try{return JSON.stringify($).length}catch{return String($).length}}function uW($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function QH($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function dW($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z.role==="user"&&!QH(Z))return W}return-1}function bz($){for(let W=0;W<$.length;W+=1){let Z=$[W];if(Z.role==="user"&&!QH(Z))return W}return-1}function b3($){let W=new Set;if(!Array.isArray($.content))return W;for(let Z of $.content)if(Z.type==="tool_use")W.add(Z.id);else if(Z.type==="tool_result")W.add(Z.tool_use_id);return W}function yz($){let W=new Map;for(let Z=0;Z<$.length;Z+=1)for(let Q of b3($[Z])){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function S3($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}for(let Z=$.length-1;Z>=0;Z-=1){let Q=$[Z];if(!Array.isArray(Q.content))continue;if(Q.content.some((J)=>J.type==="tool_use"&&!W.has(J.id)))return Z}return $.length}function hz($,W){let Z=yz($),Q=new Set,J=[W];while(J.length>0){let j=J.shift();if(j===void 0||Q.has(j))continue;Q.add(j);for(let X of b3($[j]))for(let Y of Z.get(X)??[])if(!Q.has(Y))J.push(Y)}return Q}function kz($){return $.type==="image"||$.type==="redacted_thinking"}function Iz($){return $.type==="image"}function xz($,W,Z){if(W.dropThinkingBlocks&&$.type==="thinking")return!0;return W.dropUnsafeOutsideLiveTail&&!Z&&kz($)}function $H($,W,Z,Q="over_budget"){let J=[],j=[];for(let X=0;X<$.length;X+=1){let Y=$[X];if(Array.isArray(Y.content)&&Y.content.length===0){Z.push({kind:"dropped_message",path:{messageIndex:W[X]},reason:Q,originalSize:R1(Y),finalSize:0});continue}J.push(Y),j.push(W[X])}return{messages:J,originalIndexes:j}}function gz($,W,Z,Q,J,j){return $.map((X,Y)=>{if(!Array.isArray(X.content))return X;let V=!1,B=Y===Q||Y>=J,H=X.content.flatMap((G,K)=>{if(xz(G,j,B))return V=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:R1(G),finalSize:0}),[];if(G.type==="tool_result"&&Array.isArray(G.content)){let F=G.content.filter((A)=>{if(j.dropUnsafeOutsideLiveTail&&!B&&Iz(A))return!1;return!0});if(F.length!==G.content.length){V=!0;let A={...G,content:F};return Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:R1(G),finalSize:R1(A)}),[A]}}return[G]});return V?{...X,content:H}:X})}function mz($,W,Z){return $.map((Q,J)=>{if(!Array.isArray(Q.content))return Q;let j=!1,X=Q.content.filter((Y,V)=>{if(Y.type!=="thinking")return!0;return j=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[J],blockIndex:V},reason:"unsafe_to_truncate",originalSize:R1(Y),finalSize:0}),!1});return j?{...Q,content:X}:Q})}function I8($,W){if(W<=0)return"";if($.length<=W)return $;if(W<=16)return $.slice(0,Math.max(1,W));let Z=`
321
+ `);for(let Q of $.slice(0,W))Z.update(JSON.stringify(Sz(Q))),Z.update(`
322
+ `);return`sha256:${Z.digest("hex")}`}function k8($){let W=$.sourceMessages.at(-1),Z=sB(W);return S4.parse({version:1,updated_at:$.updatedAt??new Date().toISOString(),...$.conversationId?.trim()?{conversation_id:$.conversationId.trim()}:{},source_message_count:$.sourceMessages.length,source_prefix_hash:tB($.sourceMessages),...Z?{source_last_message_key:Z}:{},messages:S3($.compactedMessages),...$.systemPrompt!==void 0?{system_prompt:$.systemPrompt}:{}})}function A2($,W){if(!($.source_message_count<=W.length))return;let Q=!!$.source_prefix_hash&&tB(W,$.source_message_count)===$.source_prefix_hash,J=W[$.source_message_count-1],j=!$.source_prefix_hash&&$.source_message_count>0&&!!$.source_last_message_key&&sB(J)===$.source_last_message_key;if(!(Q||j))return;return[...S3($.messages),...S3(W.slice($.source_message_count))]}function G1($){let W=S4.safeParse($);return W.success?W.data:void 0}import{createHandlerAsync as sz}from"@cline/llms";function bz($){switch($){case"agentic_summary":case"basic_compaction_projection":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!0,dropThinkingBlocks:!0};case"normal_provider_request":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!1,dropThinkingBlocks:!1}}}function $H($){return $.map((W)=>({...W,content:Array.isArray(W.content)?W.content.map((Z)=>({...Z})):W.content,...W.metadata?{metadata:{...W.metadata}}:{}}))}function R1($){try{return JSON.stringify($).length}catch{return String($).length}}function dW($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function JH($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function lW($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z.role==="user"&&!JH(Z))return W}return-1}function yz($){for(let W=0;W<$.length;W+=1){let Z=$[W];if(Z.role==="user"&&!JH(Z))return W}return-1}function y3($){let W=new Set;if(!Array.isArray($.content))return W;for(let Z of $.content)if(Z.type==="tool_use")W.add(Z.id);else if(Z.type==="tool_result")W.add(Z.tool_use_id);return W}function hz($){let W=new Map;for(let Z=0;Z<$.length;Z+=1)for(let Q of y3($[Z])){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function b3($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}for(let Z=$.length-1;Z>=0;Z-=1){let Q=$[Z];if(!Array.isArray(Q.content))continue;if(Q.content.some((J)=>J.type==="tool_use"&&!W.has(J.id)))return Z}return $.length}function kz($,W){let Z=hz($),Q=new Set,J=[W];while(J.length>0){let j=J.shift();if(j===void 0||Q.has(j))continue;Q.add(j);for(let X of y3($[j]))for(let Y of Z.get(X)??[])if(!Q.has(Y))J.push(Y)}return Q}function Iz($){return $.type==="image"||$.type==="redacted_thinking"}function xz($){return $.type==="image"}function gz($,W,Z){if(W.dropThinkingBlocks&&$.type==="thinking")return!0;return W.dropUnsafeOutsideLiveTail&&!Z&&Iz($)}function WH($,W,Z,Q="over_budget"){let J=[],j=[];for(let X=0;X<$.length;X+=1){let Y=$[X];if(Array.isArray(Y.content)&&Y.content.length===0){Z.push({kind:"dropped_message",path:{messageIndex:W[X]},reason:Q,originalSize:R1(Y),finalSize:0});continue}J.push(Y),j.push(W[X])}return{messages:J,originalIndexes:j}}function mz($,W,Z,Q,J,j){return $.map((X,Y)=>{if(!Array.isArray(X.content))return X;let V=!1,B=Y===Q||Y>=J,H=X.content.flatMap((G,K)=>{if(gz(G,j,B))return V=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:R1(G),finalSize:0}),[];if(G.type==="tool_result"&&Array.isArray(G.content)){let F=G.content.filter((A)=>{if(j.dropUnsafeOutsideLiveTail&&!B&&xz(A))return!1;return!0});if(F.length!==G.content.length){V=!0;let A={...G,content:F};return Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:R1(G),finalSize:R1(A)}),[A]}}return[G]});return V?{...X,content:H}:X})}function vz($,W,Z){return $.map((Q,J)=>{if(!Array.isArray(Q.content))return Q;let j=!1,X=Q.content.filter((Y,V)=>{if(Y.type!=="thinking")return!0;return j=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[J],blockIndex:V},reason:"unsafe_to_truncate",originalSize:R1(Y),finalSize:0}),!1});return j?{...Q,content:X}:Q})}function I8($,W){if(W<=0)return"";if($.length<=W)return $;if(W<=16)return $.slice(0,Math.max(1,W));let Z=`
323
323
  ...[truncated ${$.length-W} chars]`,Q=Math.max(1,W-Z.length),J=`
324
- ...[truncated ${$.length-Q} chars]`;return`${$.slice(0,Q)}${J}`}function WH($,W){if(typeof $==="string")return I8($,W);let Z=W;return $.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};return Q}if(Q.type==="text"){let J=I8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=I8(Q.content,Z);return Z-=J.length,{...Q,content:J}}return Q})}function vz($){if(typeof $==="string")return $.length;return $.reduce((W,Z)=>{if(Z.type==="text")return W+Z.text.length;if(Z.type==="file")return W+Z.content.length;return W},0)}function cz($,W){if(typeof $.content==="string")return{...$,content:I8($.content,W)};let Z=W;return{...$,content:$.content.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};if(Q.type==="tool_result")return{...Q,content:WH(Q.content,0)};return Q}if(Q.type==="text"){let J=I8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=I8(Q.content,Z);return Z-=J.length,{...Q,content:J}}if(Q.type==="tool_result"){let J=WH(Q.content,Z);return Z-=vz(J),{...Q,content:J}}return Q})}}function uz($){if(typeof $.content==="string")return $.content.length>0;return $.content.some((W)=>W.type==="text"||W.type==="file"||W.type==="tool_result")}function dz($,W,Z){return{messages:$.filter((Q,J)=>!Z.has(J)),originalIndexes:W.filter((Q,J)=>!Z.has(J))}}function lz($,W){if(W<0)return!1;for(let Z of $)if(Z>=W)return!0;return!1}function ZH($,W){return W>=0&&$.has(W)}function b4($){let W=[],Z=[],Q=Sz($.policyIntent);if($.targetTokens<=0)return{status:"failed",messages:eB($.messages),actions:W,liveTailHandling:"preserved_out_of_band",estimatedTokens:uW($.messages,$.estimateMessageTokens),warnings:[{code:"budget_impossible",message:"Target budget must be greater than zero."}]};let J=eB($.messages),j=J.map((B,H)=>H);if(Q.dropThinkingBlocks){let B=$H(mz(J,j,W),j,W,"unsafe_to_truncate");J=B.messages,j=B.originalIndexes}let X=Q.protectLatestTypedUser?dW(J):-1,Y=Q.protectLiveTailFromDrop?S3(J):J.length;if(Q.dropUnsafeOutsideLiveTail){let B=$H(gz(J,j,W,X,Y,Q),j,W);J=B.messages,j=B.originalIndexes}let V=uW(J,$.estimateMessageTokens);if(V<=$.targetTokens)return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z};for(let B=J.length-1;B>=0&&V>$.targetTokens;B-=1){let H=dW(J);if(B===H)continue;if(Q.protectLiveTailFromDrop&&B>=S3(J))continue;if(!uz(J[B]))continue;let G=R1(J[B]),K=Math.max(1,G/Math.max(1,$.estimateMessageTokens(J[B]))),F=Math.max(16,Math.floor($.targetTokens*K/Math.max(1,J.length)));J[B]=cz(J[B],F),W.push({kind:"truncated_text",path:{messageIndex:j[B]},reason:"over_budget",originalSize:G,finalSize:R1(J[B])}),V=uW(J,$.estimateMessageTokens)}for(let B=0;B<J.length&&V>$.targetTokens;){let H=bz(J),G=dW(J),K=Q.protectLiveTailFromDrop?S3(J):J.length;if(B===H||B===G){W.push({kind:"preserved",path:{messageIndex:j[B]},reason:"protected_live_tail",originalSize:R1(J[B]),finalSize:R1(J[B])}),B+=1;continue}let F=hz(J,B);if(ZH(F,H)){B+=1;continue}if(ZH(F,G)){B+=1;continue}if(lz(F,K)){B+=1;continue}for(let D of F)W.push({kind:"dropped_message",path:{messageIndex:j[D]},reason:F.size>1||b3(J[D]).size>0?"tool_pair_boundary":"over_budget",originalSize:R1(J[D]),finalSize:0});let A=dz(J,j,F);J=A.messages,j=A.originalIndexes,V=uW(J,$.estimateMessageTokens)}if(V>$.targetTokens)return Z.push({code:"budget_unachievable_with_protections",message:"Projection could not reach budget without violating protected content."}),{status:"failed",messages:J,actions:W,liveTailHandling:"included_degraded",estimatedTokens:V,warnings:Z};return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z}}import{CHARS_PER_TOKEN as Gd,estimateTokens as lW}from"@cline/shared";var YH=128000,pz=0.9,U2=0.9,VH=0.7,BH=20000,JH=1024,jH=2000,HH=2000,GH=8;function XH($){return typeof $==="number"&&Number.isFinite($)&&$>0}function I4($){let W=XH($.contextWindow)?$.contextWindow:void 0,Z=XH($.maxInputTokens)?$.maxInputTokens:void 0;if(Z!==void 0)return W===void 0?Z:Math.min(Z,W);return W===void 0?void 0:W*pz}function k4($,W){if($.length<=W)return $;return`${$.slice(0,W)}
325
- ...[truncated ${$.length-W} chars]`}function rz($){let W=y3($);if(typeof W==="string")return W;return W.map((Z)=>{switch(Z.type){case"text":return Z.text;case"file":return`<file path="${Z.path}">
324
+ ...[truncated ${$.length-Q} chars]`;return`${$.slice(0,Q)}${J}`}function ZH($,W){if(typeof $==="string")return I8($,W);let Z=W;return $.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};return Q}if(Q.type==="text"){let J=I8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=I8(Q.content,Z);return Z-=J.length,{...Q,content:J}}return Q})}function cz($){if(typeof $==="string")return $.length;return $.reduce((W,Z)=>{if(Z.type==="text")return W+Z.text.length;if(Z.type==="file")return W+Z.content.length;return W},0)}function uz($,W){if(typeof $.content==="string")return{...$,content:I8($.content,W)};let Z=W;return{...$,content:$.content.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};if(Q.type==="tool_result")return{...Q,content:ZH(Q.content,0)};return Q}if(Q.type==="text"){let J=I8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=I8(Q.content,Z);return Z-=J.length,{...Q,content:J}}if(Q.type==="tool_result"){let J=ZH(Q.content,Z);return Z-=cz(J),{...Q,content:J}}return Q})}}function dz($){if(typeof $.content==="string")return $.content.length>0;return $.content.some((W)=>W.type==="text"||W.type==="file"||W.type==="tool_result")}function lz($,W,Z){return{messages:$.filter((Q,J)=>!Z.has(J)),originalIndexes:W.filter((Q,J)=>!Z.has(J))}}function pz($,W){if(W<0)return!1;for(let Z of $)if(Z>=W)return!0;return!1}function QH($,W){return W>=0&&$.has(W)}function b4($){let W=[],Z=[],Q=bz($.policyIntent);if($.targetTokens<=0)return{status:"failed",messages:$H($.messages),actions:W,liveTailHandling:"preserved_out_of_band",estimatedTokens:dW($.messages,$.estimateMessageTokens),warnings:[{code:"budget_impossible",message:"Target budget must be greater than zero."}]};let J=$H($.messages),j=J.map((B,H)=>H);if(Q.dropThinkingBlocks){let B=WH(vz(J,j,W),j,W,"unsafe_to_truncate");J=B.messages,j=B.originalIndexes}let X=Q.protectLatestTypedUser?lW(J):-1,Y=Q.protectLiveTailFromDrop?b3(J):J.length;if(Q.dropUnsafeOutsideLiveTail){let B=WH(mz(J,j,W,X,Y,Q),j,W);J=B.messages,j=B.originalIndexes}let V=dW(J,$.estimateMessageTokens);if(V<=$.targetTokens)return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z};for(let B=J.length-1;B>=0&&V>$.targetTokens;B-=1){let H=lW(J);if(B===H)continue;if(Q.protectLiveTailFromDrop&&B>=b3(J))continue;if(!dz(J[B]))continue;let G=R1(J[B]),K=Math.max(1,G/Math.max(1,$.estimateMessageTokens(J[B]))),F=Math.max(16,Math.floor($.targetTokens*K/Math.max(1,J.length)));J[B]=uz(J[B],F),W.push({kind:"truncated_text",path:{messageIndex:j[B]},reason:"over_budget",originalSize:G,finalSize:R1(J[B])}),V=dW(J,$.estimateMessageTokens)}for(let B=0;B<J.length&&V>$.targetTokens;){let H=yz(J),G=lW(J),K=Q.protectLiveTailFromDrop?b3(J):J.length;if(B===H||B===G){W.push({kind:"preserved",path:{messageIndex:j[B]},reason:"protected_live_tail",originalSize:R1(J[B]),finalSize:R1(J[B])}),B+=1;continue}let F=kz(J,B);if(QH(F,H)){B+=1;continue}if(QH(F,G)){B+=1;continue}if(pz(F,K)){B+=1;continue}for(let D of F)W.push({kind:"dropped_message",path:{messageIndex:j[D]},reason:F.size>1||y3(J[D]).size>0?"tool_pair_boundary":"over_budget",originalSize:R1(J[D]),finalSize:0});let A=lz(J,j,F);J=A.messages,j=A.originalIndexes,V=dW(J,$.estimateMessageTokens)}if(V>$.targetTokens)return Z.push({code:"budget_unachievable_with_protections",message:"Projection could not reach budget without violating protected content."}),{status:"failed",messages:J,actions:W,liveTailHandling:"included_degraded",estimatedTokens:V,warnings:Z};return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z}}import{CHARS_PER_TOKEN as Kd,estimateTokens as pW}from"@cline/shared";var VH=128000,rz=0.9,U2=0.9,BH=0.7,HH=20000,jH=1024,XH=2000,GH=2000,KH=8;function YH($){return typeof $==="number"&&Number.isFinite($)&&$>0}function I4($){let W=YH($.contextWindow)?$.contextWindow:void 0,Z=YH($.maxInputTokens)?$.maxInputTokens:void 0;if(Z!==void 0)return W===void 0?Z:Math.min(Z,W);return W===void 0?void 0:W*rz}function k4($,W){if($.length<=W)return $;return`${$.slice(0,W)}
325
+ ...[truncated ${$.length-W} chars]`}function iz($){let W=h3($);if(typeof W==="string")return W;return W.map((Z)=>{switch(Z.type){case"text":return Z.text;case"file":return`<file path="${Z.path}">
326
326
  ${Z.content}
327
327
  </file>`;case"image":return`[image:${Z.mediaType}]`;default:return""}}).join(`
328
- `)}function y3($){if(typeof $==="string")return k4($,jH);return $.map((W)=>{switch(W.type){case"text":return{...W,text:k4(W.text,jH)};case"file":return{...W,content:k4(W.content,HH)};case"image":return W;default:return W}})}function iz($){return Object.entries($).map(([W,Z])=>`${W}=${JSON.stringify(Z)}`).join(", ")}function KH($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let W=[];for(let Z of $.content)switch(Z.type){case"text":W.push(`[${$.role==="user"?"User":"Bot"}]: ${Z.text}`);break;case"thinking":W.push(`[Bot thinking]: ${k4(Z.thinking,2000)}`);break;case"redacted_thinking":W.push("[Bot thinking]: [redacted]");break;case"tool_use":W.push(`[Bot tool calls]: ${Z.name}(${iz(Z.input)})`);break;case"tool_result":W.push(`[Tool result]: ${rz(Z.content)}`);break;case"file":W.push(`[${$.role==="user"?"User":"Bot"} file ${Z.path}]: ${k4(Z.content,HH)}`);break;case"image":W.push(`[${$.role==="user"?"User":"Bot"} image]: ${Z.mediaType}`);break}return W.join(`
329
- `)}function FH($){return $.map(KH).join(`
328
+ `)}function h3($){if(typeof $==="string")return k4($,XH);return $.map((W)=>{switch(W.type){case"text":return{...W,text:k4(W.text,XH)};case"file":return{...W,content:k4(W.content,GH)};case"image":return W;default:return W}})}function nz($){return Object.entries($).map(([W,Z])=>`${W}=${JSON.stringify(Z)}`).join(", ")}function FH($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let W=[];for(let Z of $.content)switch(Z.type){case"text":W.push(`[${$.role==="user"?"User":"Bot"}]: ${Z.text}`);break;case"thinking":W.push(`[Bot thinking]: ${k4(Z.thinking,2000)}`);break;case"redacted_thinking":W.push("[Bot thinking]: [redacted]");break;case"tool_use":W.push(`[Bot tool calls]: ${Z.name}(${nz(Z.input)})`);break;case"tool_result":W.push(`[Tool result]: ${iz(Z.content)}`);break;case"file":W.push(`[${$.role==="user"?"User":"Bot"} file ${Z.path}]: ${k4(Z.content,GH)}`);break;case"image":W.push(`[${$.role==="user"?"User":"Bot"} image]: ${Z.mediaType}`);break}return W.join(`
329
+ `)}function AH($){return $.map(FH).join(`
330
330
 
331
- `).trim()}function AH(){let $=new WeakMap;return(W)=>{let Z=W,Q=$.get(Z);if(typeof Q==="number")return Q;let J;try{J=JSON.stringify(W)}catch{J=KH(W)}let j=lW(J.length);return $.set(Z,j),j}}function x4($){return $.metadata?.kind==="compaction_summary"}function h3($){if(!x4($))return;let W=$.metadata;if(!W)return;let Z=W.details;return{kind:"compaction_summary",summary:String(W.summary??""),details:{readFiles:Array.isArray(Z?.readFiles)?Z.readFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[],modifiedFiles:Array.isArray(Z?.modifiedFiles)?Z.modifiedFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[]},tokensBefore:Number(W.tokensBefore??0),generatedAt:Number(W.generatedAt??0)}}function nz($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function g4($){return $.role==="user"&&!nz($)&&!x4($)}function UH($){for(let W=0;W<$.length;W+=1)if(g4($[W]))return W;return-1}function pW($){for(let W=$.length-1;W>=0;W-=1)if(g4($[W]))return W;return 0}function DH($){for(let W=$.length-1;W>=0;W-=1)if($[W].role==="assistant")return W;return-1}function _H($){for(let W=$.length-1;W>=0;W-=1)if(x4($[W]))return W;return-1}function fH($,W,Z){let Q=pW($);if(Q<=0)return 0;let J=0,j=$.length;for(let Y=$.length-1;Y>=0;Y-=1)if(J+=Z($[Y]),j=Y,J>=W)break;if(j<=0)return 0;let X=Math.min(j,Q);while(X>0&&!g4($[X]))X-=1;return X}function h4($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((W)=>h4(W));if($&&typeof $==="object"){let W=$,Z=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])Z.push(...h4(W[Q]));if(Array.isArray(W.files)){for(let Q of W.files)if(Q&&typeof Q==="object")Z.push(...h4(Q.path))}if(Array.isArray(W.file_paths))Z.push(...h4(W.file_paths));return Z}return[]}function y4($,W){let Z=new Set($);for(let Q of W){let J=Q.trim();if(!J)continue;Z.add(J)}return[...Z].sort((Q,J)=>Q.localeCompare(J))}function k3($){let W=[],Z=[];for(let Q of $){let J=h3(Q);if(J){W=y4(W,J.details.readFiles),Z=y4(Z,J.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let j of Q.content){if(j.type==="file"){W=y4(W,[j.path]);continue}if(j.type!=="tool_use")continue;let X=h4(j.input);if(j.name==="read_files"){W=y4(W,X);continue}if(j.name==="editor"||j.name==="apply_patch")Z=y4(Z,X)}}return{readFiles:W,modifiedFiles:Z}}function az($){let W=$.readFiles.length>0?$.readFiles.map((Q)=>`- ${Q}`).join(`
331
+ `).trim()}function UH(){let $=new WeakMap;return(W)=>{let Z=W,Q=$.get(Z);if(typeof Q==="number")return Q;let J;try{J=JSON.stringify(W)}catch{J=FH(W)}let j=pW(J.length);return $.set(Z,j),j}}function x4($){return $.metadata?.kind==="compaction_summary"}function k3($){if(!x4($))return;let W=$.metadata;if(!W)return;let Z=W.details;return{kind:"compaction_summary",summary:String(W.summary??""),details:{readFiles:Array.isArray(Z?.readFiles)?Z.readFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[],modifiedFiles:Array.isArray(Z?.modifiedFiles)?Z.modifiedFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[]},tokensBefore:Number(W.tokensBefore??0),generatedAt:Number(W.generatedAt??0)}}function az($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function g4($){return $.role==="user"&&!az($)&&!x4($)}function DH($){for(let W=0;W<$.length;W+=1)if(g4($[W]))return W;return-1}function rW($){for(let W=$.length-1;W>=0;W-=1)if(g4($[W]))return W;return 0}function _H($){for(let W=$.length-1;W>=0;W-=1)if($[W].role==="assistant")return W;return-1}function fH($){for(let W=$.length-1;W>=0;W-=1)if(x4($[W]))return W;return-1}function LH($,W,Z){let Q=rW($);if(Q<=0)return 0;let J=0,j=$.length;for(let Y=$.length-1;Y>=0;Y-=1)if(J+=Z($[Y]),j=Y,J>=W)break;if(j<=0)return 0;let X=Math.min(j,Q);while(X>0&&!g4($[X]))X-=1;return X}function h4($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((W)=>h4(W));if($&&typeof $==="object"){let W=$,Z=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])Z.push(...h4(W[Q]));if(Array.isArray(W.files)){for(let Q of W.files)if(Q&&typeof Q==="object")Z.push(...h4(Q.path))}if(Array.isArray(W.file_paths))Z.push(...h4(W.file_paths));return Z}return[]}function y4($,W){let Z=new Set($);for(let Q of W){let J=Q.trim();if(!J)continue;Z.add(J)}return[...Z].sort((Q,J)=>Q.localeCompare(J))}function I3($){let W=[],Z=[];for(let Q of $){let J=k3(Q);if(J){W=y4(W,J.details.readFiles),Z=y4(Z,J.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let j of Q.content){if(j.type==="file"){W=y4(W,[j.path]);continue}if(j.type!=="tool_use")continue;let X=h4(j.input);if(j.name==="read_files"){W=y4(W,X);continue}if(j.name==="editor"||j.name==="apply_patch")Z=y4(Z,X)}}return{readFiles:W,modifiedFiles:Z}}function oz($){let W=$.readFiles.length>0?$.readFiles.map((Q)=>`- ${Q}`).join(`
332
332
  `):"- none",Z=$.modifiedFiles.length>0?$.modifiedFiles.map((Q)=>`- ${Q}`).join(`
333
333
  `):"- none";return`## Files
334
334
  Read:
335
335
  ${W}
336
336
  Modified:
337
- ${Z}`}function LH($,W){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
337
+ ${Z}`}function TH($,W){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
338
338
 
339
- ${az(W)}`.trim()}function I3($){let W=[`Summarize this session for continuation. Be concise and factual.
339
+ ${oz(W)}`.trim()}function x3($){let W=[`Summarize this session for continuation. Be concise and factual.
340
340
 
341
341
  ## Goal
342
342
  One sentence: what is being built or fixed.
@@ -358,20 +358,20 @@ Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.tr
358
358
  ${$.previousSummary.trim()}`);return W.push(`Conversation:
359
359
  ${$.conversationText||"(empty)"}`),W.join(`
360
360
 
361
- `)}function TH($){let W=$.summarizer,Z=(J)=>{if(J.providerId==="openai-codex"){let{maxOutputTokens:j,...X}=J;return{...X,thinking:!1}}return{...J,maxOutputTokens:J.maxOutputTokens??JH,thinking:!1}};if(!W)return Z($.activeProviderConfig);let Q=W.providerConfig?.providerId===W.providerId?W.providerConfig:void 0;return Z({...Q??{},providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey??Q?.apiKey,baseUrl:W.baseUrl??Q?.baseUrl,headers:W.headers??Q?.headers,modelInfo:W.modelInfo??Q?.modelInfo,knownModels:W.knownModels??Q?.knownModels,maxOutputTokens:W.maxOutputTokens??JH})}function OH($){return{role:"user",content:`Context summary:
361
+ `)}function OH($){let W=$.summarizer,Z=(J)=>{if(J.providerId==="openai-codex"){let{maxOutputTokens:j,...X}=J;return{...X,thinking:!1}}return{...J,maxOutputTokens:J.maxOutputTokens??jH,thinking:!1}};if(!W)return Z($.activeProviderConfig);let Q=W.providerConfig?.providerId===W.providerId?W.providerConfig:void 0;return Z({...Q??{},providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey??Q?.apiKey,baseUrl:W.baseUrl??Q?.baseUrl,headers:W.headers??Q?.headers,modelInfo:W.modelInfo??Q?.modelInfo,knownModels:W.knownModels??Q?.knownModels,maxOutputTokens:W.maxOutputTokens??jH})}function zH($){return{role:"user",content:`Context summary:
362
362
 
363
- ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}var x3=1024;function sz($){let W=I4({maxInputTokens:$.maxInputTokens??$.modelInfo?.maxInputTokens,contextWindow:$.modelInfo?.contextWindow});if(W!==void 0)return W;let Z=$.knownModels?.[$.modelId];return I4({maxInputTokens:Z?.maxInputTokens,contextWindow:Z?.contextWindow})}function tz($){return b4({messages:$.messages,targetTokens:Math.max(1,$.targetTokens),policyIntent:"agentic_summary",estimateMessageTokens:$.estimateMessageTokens})}async function ez($){let W=await oz($.providerConfig),Z="";for await(let Q of W.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Q.type==="text"){Z+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Z.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Z.trim()}function $q($){try{return JSON.stringify($).length}catch{return String($).length}}async function zH($){let W=$.context.messages;if(W.length<2)return;let Z=fH(W,$.preserveRecentTokens,$.estimateMessageTokens);if(Z<=0||Z>=W.length)return;let Q=W.slice(0,Z),J=_H(Q),j=J>=0?h3(Q[J])?.summary:void 0,X=J>=0?Q.slice(J+1):Q;if(X.length===0)return;let Y=k3(Q),V=TH({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),B=sz(V),H=$.summarizer===void 0,G=Math.max($.context.budget.request.maxInputTokens,$.context.budget.request.triggerTokens,x3);if(B===void 0&&!H)$.logger?.log("Agentic compaction summarizer has no known input limit; using conservative summary budget",{severity:"warn",summarizerProviderId:V.providerId,summarizerModelId:V.modelId,fallbackInputLimit:x3});let K=B??(H?G:x3),F=lW(I3({previousSummary:j,conversationText:"",fileOps:Y}).length),A=K-F;if(A<=0){$.logger?.debug("Skipped agentic compaction: summarizer budget exhausted",{summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,summaryRequestOverheadTokens:F});return}let D=tz({messages:X,targetTokens:A,estimateMessageTokens:$.estimateMessageTokens});if(D.status==="failed"){$.logger?.log("Skipped agentic compaction: summary input budget failed",{severity:"warn",budgetWarnings:D.warnings.map((p)=>p.code),summaryInputEstimatedTokens:D.estimatedTokens,targetTokens:A,summarizerProviderId:V.providerId,summarizerModelId:V.modelId});return}let U=k3(D.messages),f=FH(D.messages),_=I3({previousSummary:j,conversationText:f,fileOps:U});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:X.length,preservedMessages:W.length-Z,previousSummaryChars:j?.length??0,conversationTextChars:f.length,summaryRequestChars:_.length,summaryRequestEstimatedTokens:lW(_.length),newMessagesJsonChars:$q(X),summaryInputEstimatedTokens:D.estimatedTokens,summaryInputActions:D.actions.length,summaryInputWarnings:D.warnings.map((p)=>p.code),summaryRequestOverheadTokens:F,summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,maxInputTokens:$.context.budget.request.maxInputTokens,triggerTokens:$.context.budget.request.triggerTokens});let R=await ez({providerConfig:V,request:_,logger:$.logger});if(!R.trim())return;let O=LH(R,U),T=W.reduce((p,x)=>p+$.estimateMessageTokens(x),0),L=[OH({summary:O,fileOps:U,tokensBefore:T}),...W.slice(Z)],C=L.reduce((p,x)=>p+$.estimateMessageTokens(x),0);$.logger?.debug("Performed agentic compaction",{messagesBefore:W.length,messagesAfter:L.length,messagesSummarized:Z,messagesPreserved:W.length-Z,tokensBefore:T,tokensAfter:C,maxInputTokens:$.context.budget.request.maxInputTokens});let E=D.actions.filter((p)=>p.reason==="over_budget"||p.reason==="tool_pair_boundary").length;return{messages:L,budget:{policyIntent:"agentic_summary",actionCount:E,warningCount:D.warnings.length,liveTailHandling:D.liveTailHandling}}}import{CHARS_PER_TOKEN as Wq}from"@cline/shared";function Zq($){if(x4($))return;if(typeof $.content==="string"){let Z=$.content.trim();return Z?{...$,content:Z}:void 0}let W=$.content.filter((Z)=>Z.type!=="text"||Z.text.trim());if(W.length===0)return;return{...$,content:W.map((Z)=>Z.type==="text"?{...Z,text:Z.text.trim()}:Z.type==="tool_result"?{...Z,content:y3(Z.content)}:Z)}}function qH($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function MH($,W){if($.length<=W)return $;let Z=`
364
- ...`,Q=Math.max(1,W-Z.length);return`${$.slice(0,Q)}${Z}`}function RH($,W){let Z=Number.isFinite(W)?Math.max(1,W):1,Q=Math.max(16,Z*Wq);if(typeof $.content==="string"){let X=MH($.content,Q).trim();return{...$,content:X||"..."}}let J=Q,j=$.content.map((X)=>{if(X.type!=="text"||J<=0)return X;let Y=MH(X.text,J).trim();return J-=Y.length,{...X,text:Y||"..."}});return{...$,content:j}}function Qq($,W){let Z=UH($),Q=pW($),J=DH($),j=[],X=0;for(let Y=0;Y<$.length;Y+=1){let V=Zq($[Y]);if(!V)continue;let B=W(V);X+=B,j.push({index:Y,message:V,estimatedTokens:B,toolPairIds:NH(V),isFirstUser:Y===Z,isLastUser:Y===Q,isLastAssistant:Y===J})}return{candidates:j,totalTokens:X}}function EH($,W,Z,Q){let J=$[W],j=J.estimatedTokens;return J.message=Z,J.estimatedTokens=Q(Z),J.toolPairIds=NH(Z),J.estimatedTokens-j}function NH($){if(!Array.isArray($.content))return[];let W=[];for(let Z of $.content)if(Z.type==="tool_use")W.push(Z.id);else if(Z.type==="tool_result")W.push(Z.tool_use_id);return W}function Jq($){let W=new Map;for(let Z of $)for(let Q of Z.toolPairIds){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function jq($,W,Z){let Q=new Set,J=[Z],j=0;while(j<J.length){let X=J[j];if(j+=1,X===void 0||!$.has(X)||Q.has(X))continue;Q.add(X);for(let Y of X.toolPairIds)for(let V of W.get(Y)??[])if(!Q.has(V))J.push(V)}return Q}function Xq($,W){let Z=0;for(let Q of $){if(W.has(Q))continue;$[Z]=Q,Z+=1}$.length=Z}function rW($,W,Z,Q){let J=new Set($),j=Jq($);for(let X=0;X<$.length&&Q>Z;){if(!W($[X])){X+=1;continue}let Y=jq(J,j,$[X]);if(Y.size===0){X+=1;continue}let V=0;for(let B of Y)V+=B.estimatedTokens,J.delete(B);Q-=V,Xq($,Y)}return Q}function Yq($,W,Z,Q,J){if(Z<=W)return Z;for(let X=$.length-1;X>=0&&Z>W;X-=1){let Y=$[X];if(Y.isFirstUser)continue;let V=Math.max(GH,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)continue;Z+=EH($,X,RH(Y.message,V),J)}if(Z<=W)return Z;let j=$.findIndex((X)=>X.isFirstUser);if(j>=0){if($[j].estimatedTokens<=Q)return Z;while(Z>W){let Y=$[j],V=Math.max(1,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)break;let B=Y.estimatedTokens;if(Z+=EH($,j,RH(Y.message,V),J),Y.estimatedTokens>=B)break}}return Z}function Vq($,W){return JSON.stringify($)!==JSON.stringify(W)}function Bq($){let W=pW($);if(W<0||W===0&&!g4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,W),protectedTail:$.slice(W)}}function wH($){let W=Math.max(1,Math.min($.context.budget.messages.targetTokens,$.context.budget.messages.triggerTokens)),{compactable:Z,protectedTail:Q}=Bq($.context.messages);if(Z.length===0)return;let J=qH(Q,$.estimateMessageTokens),j=Math.max(1,W-J),X=Qq(Z,$.estimateMessageTokens),{candidates:Y}=X;if(Y.length===0)return;let V=X.totalTokens,B=V;B=rW(Y,(U)=>U.message.role==="assistant"&&!U.isLastAssistant,j,B),B=rW(Y,(U)=>U.message.role==="user"&&!U.isFirstUser&&!U.isLastUser,j,B),B=rW(Y,(U)=>U.message.role==="assistant"&&U.isLastAssistant,j,B),B=rW(Y,(U)=>U.message.role==="user"&&U.isLastUser&&!U.isFirstUser,j,B),B=Yq(Y,j,B,$.context.budget.messages.triggerTokens,$.estimateMessageTokens);let H=[...Y.map((U)=>U.message),...Q],G=b4({messages:H,targetTokens:W,policyIntent:"basic_compaction_projection",estimateMessageTokens:$.estimateMessageTokens});if(G.status==="failed")$.logger?.debug("Basic compaction returned best-effort projection",{budgetWarnings:G.warnings.map((U)=>U.code),projectedTokens:G.estimatedTokens,targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens});let K=G.messages;if(!Vq($.context.messages,K))return;let F=V+J,A=qH(K,$.estimateMessageTokens),D=G.actions.filter((U)=>U.reason==="over_budget"||U.reason==="tool_pair_boundary").length;return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:K.length,messagesRemoved:$.context.messages.length-K.length,tokensBefore:F,tokensAfter:A,budgetStatus:G.status,budgetActions:D,budgetWarnings:G.warnings.map((U)=>U.code),targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens}),{messages:K,budget:{policyIntent:"basic_compaction_projection",actionCount:D,warningCount:G.warnings.length,liveTailHandling:G.liveTailHandling}}}var Gq=0.5;function PH($){try{return JSON.stringify($).length}catch{return String($).length}}function Kq($){let W=0,Z=0,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result")continue;let X=PH(j.content);W+=1,Z+=X,Q=Math.max(Q,X)}}return{toolResultCount:W,toolResultSerializedChars:Z,maxToolResultSerializedChars:Q}}var Fq={basic:({context:$,estimateMessageTokens:W,logger:Z})=>wH({context:$,estimateMessageTokens:W,logger:Z}),agentic:({context:$,providerConfig:W,compaction:Z,estimateMessageTokens:Q,logger:J})=>zH({context:$,providerConfig:W,summarizer:Z?.summarizer,preserveRecentTokens:Math.min(Z?.preserveRecentTokens??BH,$.budget.messages.targetTokens),estimateMessageTokens:Q,logger:J})};function Aq($){let W=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Z=Math.min(0.95,Math.max(0.05,W));return Math.max(1,Math.floor(Math.min($.messageTriggerTokens,$.messageInputTokens*Z)))}function Uq($){let W=$.messagePairCount>=5&&typeof $.modelMaxTokens==="number"&&Number.isFinite($.modelMaxTokens)&&$.modelMaxTokens<$.maxInputTokens?Math.floor($.maxInputTokens*Gq):Math.floor($.triggerTokens*VH),Z=Math.max(1,$.triggerTokens-1);return Math.max(1,Math.min(W,$.maxInputTokens,Z))}function CH($,W){return Math.max(1,Math.floor($-W))}function Dq($){let W=0,Z=!1;for(let Q of $)if(Q.role==="user")Z=!0;else if(Q.role==="assistant"&&Z)W+=1,Z=!1;return W}function m4($,W={}){let Z=$.compaction;if(Z?.enabled!==!0)return;let Q=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},J=AH(),j=Z?.strategy??"basic",X=Fq[j],Y=W.mode??"auto",V=Z?.compact?"custom":j;return async(B)=>{let H=B.apiMessages.reduce((r,d)=>r+J(d),0),G=Hq({systemPrompt:B.systemPrompt,messages:B.apiMessages,tools:B.tools}),K=B.messages.reduce((r,d)=>r+J(d),0),F=Math.max(0,G-H),A=I4({maxInputTokens:B.model.info?.maxInputTokens,contextWindow:B.model.info?.contextWindow})??YH,D=A*U2,U=CH(D,F),f=G>=D;if($.logger?.debug("Context compaction diagnostics",{mode:Y,strategy:j,iteration:B.iteration,providerId:$.providerId,modelId:$.modelId,requestInputTokens:G,apiMessageTokens:H,messageInputTokens:K,requestOverheadTokens:F,maxInputTokens:A,requestTriggerTokens:D,messageTriggerTokens:U,thresholdRatio:U2,shouldCompact:f,messageCount:B.messages.length,apiMessageCount:B.apiMessages.length,apiMessagesJsonChars:PH(B.apiMessages),...Kq(B.apiMessages)}),Y==="auto"&&!f)return;let _,R;if(Y==="auto")_=Uq({maxInputTokens:A,modelMaxTokens:B.model.info?.maxTokens,triggerTokens:D,messagePairCount:Dq(B.messages)}),R=CH(_,F);else R=Aq({messageInputTokens:K,messageTriggerTokens:U,manualTargetRatio:W.manualTargetRatio}),_=F+R;let O={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId,iteration:B.iteration,messages:B.messages,model:B.model,mode:Y,budget:{request:{inputTokens:G,maxInputTokens:A,triggerTokens:D,targetTokens:_,overheadTokens:F,thresholdRatio:U2,utilizationRatio:A>0?G/A:0},messages:{inputTokens:K,triggerTokens:U,targetTokens:R}}},T=Y==="manual"?"manual_compaction":"auto_compaction";B.emitStatusNotice?.(Y==="manual"?"compacting":"auto-compacting",{kind:T,reason:T,phase:"started",iteration:B.iteration,triggerTokens:D,targetTokens:_,maxInputTokens:A,messageTargetTokens:R});let L=B.messages.length,C=Date.now(),E=Z?.compact?await Z.compact(O):await X({context:O,providerConfig:{...Q,abortSignal:B.abortSignal},compaction:Z,estimateMessageTokens:J,logger:$.logger}),p=Date.now()-C,x=$.sessionId??B.conversationId,P={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId??void 0};if(E?.messages){let r=E.messages.reduce((I1,$2)=>I1+J($2),0),d=F+r;if($.logger?.log("Context compaction completed",{severity:"info",strategy:j,maxInputTokens:A,messageInputTokens:K,apiInputTokens:H,requestInputTokens:G,requestOverheadTokens:F,afterMessageTokens:r,afterRequestTokens:d,tokensSaved:G-d,utilizationBefore:`${(G/A*100).toFixed(1)}%`,utilizationAfter:`${(d/A*100).toFixed(1)}%`,thresholdTrigger:`${(U2*100).toFixed(1)}%`,messagesBefore:L,messagesAfter:E.messages.length,messagesRemoved:L-E.messages.length}),B.emitStatusNotice?.(Y==="manual"?"compacted":"auto-compacted",{kind:T,reason:T,phase:"completed",iteration:B.iteration,tokensBefore:G,tokensAfter:d,messagesBefore:L,messagesAfter:E.messages.length,maxInputTokens:A}),HW($.telemetry,{ulid:x,strategy:V,mode:Y,messagesBefore:L,messagesAfter:E.messages.length,messagesRemoved:L-E.messages.length,tokensBefore:G,tokensAfter:d,tokensSaved:G-d,triggerTokens:D,maxInputTokens:A,thresholdRatio:U2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P}),E.budget&&(E.budget.actionCount>0||E.budget.warningCount>0))EV($.telemetry,{ulid:x,strategy:V,mode:Y,policyIntent:E.budget.policyIntent,actionCount:E.budget.actionCount,warningCount:E.budget.warningCount,liveTailHandling:E.budget.liveTailHandling,provider:$.providerId,modelId:$.modelId,...P}),B.emitStatusNotice?.("compaction-budget-adjusted",{kind:"compaction_budget_emergency",reason:"compaction_budget_emergency",iteration:B.iteration,policyIntent:E.budget.policyIntent,actionCount:E.budget.actionCount,warningCount:E.budget.warningCount})}else B.emitStatusNotice?.(Y==="manual"?"compaction-skipped":"auto-compaction-skipped",{kind:T,reason:T,phase:"skipped",iteration:B.iteration,maxInputTokens:A}),GW($.telemetry,{ulid:x,strategy:V,mode:Y,reason:"no_result",tokensBefore:G,triggerTokens:D,maxInputTokens:A,thresholdRatio:U2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P});return E}}function v4($){return async(W)=>{let Z=$.getState?.(),Q=Z?A2(Z,W.messages):void 0;if(Z&&Q){let j=$.compact?await $.compact({...W,messages:Q,apiMessages:Q}):void 0;if(j?.messages){let X=j.systemPrompt??Z.system_prompt,Y=k8({sourceMessages:W.messages,compactedMessages:j.messages,conversationId:W.conversationId,systemPrompt:X});return await $.saveState?.(Y),{...j,...X!==void 0?{systemPrompt:X}:{}}}return{messages:Q,...j?.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:Z.system_prompt!==void 0?{systemPrompt:Z.system_prompt}:{}}}let J=$.compact?await $.compact(W):void 0;if(J?.messages){let j=k8({sourceMessages:W.messages,compactedMessages:J.messages,conversationId:W.conversationId,systemPrompt:J.systemPrompt});await $.saveState?.(j)}return J}}var XK={};w(XK,{zodToJsonSchema:()=>fE,validateWithZod:()=>_E,truncateCommandOutput:()=>L2,resolveToolRoutingConfig:()=>r8,resolveToolPresetName:()=>e1,resolveCoreSelectedToolIds:()=>FZ,getCoreHeadlessToolNames:()=>j5,getCoreDefaultEnabledToolIds:()=>KZ,getCoreBuiltinToolCatalog:()=>b2,getCoreAcpToolNames:()=>AZ,createWebFetchTool:()=>d3,createWebFetchExecutor:()=>e4,createToolPoliciesWithPreset:()=>QZ,createSubmitAndExitTool:()=>i3,createSkillsTool:()=>O2,createShellTool:()=>o4,createShellExecutor:()=>T2,createSearchTool:()=>u3,createSearchExecutor:()=>t4,createReadFilesTool:()=>c3,createFileReadExecutor:()=>s4,createEditorTool:()=>p3,createEditorExecutor:()=>M2,createDefaultToolsWithPreset:()=>JZ,createDefaultTools:()=>N$,createDefaultShellExecutor:()=>$5,createDefaultExecutors:()=>l8,createBuiltinTools:()=>y2,createAskQuestionTool:()=>r3,createApplyPatchTool:()=>l3,createApplyPatchExecutor:()=>q2,computePatchChanges:()=>c8,WebFetchRequestSchema:()=>g3,ToolPresets:()=>a0,TEAM_TOOL_NAMES:()=>a8,SubmitInputSchema:()=>a4,StructuredCommandInputSchema:()=>_2,SkillsInputSchema:()=>i4,SearchCodebaseInputSchema:()=>u4,RunCommandsInputSchema:()=>d4,ReadFilesInputSchema:()=>c4,ReadFileRequestSchema:()=>oW,PatchActionType:()=>z2,MAX_COMMAND_OUTPUT_CHARS:()=>a1,FetchWebContentInputSchema:()=>l4,EditFileInputSchema:()=>p4,DefaultToolNames:()=>O0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>p8,CommandExitError:()=>o1,AskQuestionInputSchema:()=>n4,ApplyPatchInputSchema:()=>r4,ALL_DEFAULT_TOOL_NAMES:()=>D$});import{validateWithZod as _E,zodToJsonSchema as fE}from"@cline/shared";R0();import{createTool as R$,validateWithZod as E$,zodToJsonSchema as s1}from"@cline/shared";var iW="__clineInternalTelemetry";function bH($){let W=$?.__clineInternalTelemetry;return W&&typeof W==="object"&&"capture"in W&&typeof W.capture==="function"?W:void 0}import{spawn as pH}from"node:child_process";import{StringDecoder as zq}from"node:string_decoder";import{getDefaultShell as qq,getShellArgs as Mq}from"@cline/shared";import{validateWithZod as fq}from"@cline/shared";import{z}from"zod";var M$=6000,D2=z.string().describe("The absolute path of a text file to read content from"),nW=z.object({start_line:z.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:z.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit to read to the end of the file or the read cap, whichever comes first")}).describe("Optional inclusive one-based file line range"),oW=z.object({path:D2,start_line:nW.shape.start_line,end_line:nW.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds. Always include path; start_line/end_line must be on the same object as the path they apply to, never in a separate array element"),c4=z.object({files:z.array(oW).describe("Array of file read requests; each element is one file and must include path. Omit start_line/end_line or set them to null to read from the start; provide integers on the same object as the path to return only that inclusive one-based line range — never emit a range as its own array element. Reads are capped, so page through long files with start_line/end_line. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),yH={start_line:nW.shape.start_line,end_line:nW.shape.end_line},x8=z.union([oW,z.object({file_path:D2,...yH}).transform(({file_path:$,...W})=>({path:$,...W})),z.object({filePath:D2,...yH}).transform(({filePath:$,...W})=>({path:$,...W}))]),hH=z.union([c4,x8,z.array(x8),z.array(z.string()),z.string(),z.object({files:z.array(z.union([D2,x8]))}),z.object({files:x8}),z.object({files:D2}),z.object({file_paths:z.array(D2)}),z.object({file_paths:z.string()}),z.object({paths:z.array(z.union([D2,x8]))}),z.object({paths:x8}),z.object({paths:z.string()})]),u4=z.object({queries:z.array(z.string()).describe("Array of regex search queries to execute")}),kH=z.union([u4,z.array(z.string()),z.string(),z.object({queries:z.string()})]),aW=z.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${M$*2} characters) to avoid timeouts.`),_2=z.object({command:z.string().min(1).describe("The executable to run directly without shell parsing."),args:z.array(z.string()).optional().describe("Optional argv list passed directly to the executable.")}),IH=z.union([aW,_2]),d4=z.object({commands:z.array(aW).describe("Array of complete shell command strings to execute.")}),_q=z.object({commands:z.array(IH)}),xH=z.union([d4,_q,z.object({commands:IH}),z.array(_2),_2,z.object({command:aW}),z.object({cmd:aW}),z.array(z.string()),z.string()]),g3=z.object({url:z.string().describe("The URL to fetch"),prompt:z.string().min(2).describe("Analysis prompt for the fetched content")}),l4=z.object({requests:z.array(g3).describe("Array of the URLs for the web fetch requests")}),p4=z.object({path:z.string().min(1).describe("The absolute path for the action to be performed on"),old_text:z.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${M$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:z.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${M$} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:z.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),r4=z.object({input:z.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),gH=z.union([r4,z.string()]),i4=z.object({skill:z.string().min(1).describe("Name of the skill to execute."),args:z.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),n4=z.object({question:z.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:z.array(z.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),a4=z.object({summary:z.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:z.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
363
+ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}var g3=1024;function tz($){let W=I4({maxInputTokens:$.maxInputTokens??$.modelInfo?.maxInputTokens,contextWindow:$.modelInfo?.contextWindow});if(W!==void 0)return W;let Z=$.knownModels?.[$.modelId];return I4({maxInputTokens:Z?.maxInputTokens,contextWindow:Z?.contextWindow})}function ez($){return b4({messages:$.messages,targetTokens:Math.max(1,$.targetTokens),policyIntent:"agentic_summary",estimateMessageTokens:$.estimateMessageTokens})}async function $q($){let W=await sz($.providerConfig),Z="";for await(let Q of W.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Q.type==="text"){Z+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Z.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Z.trim()}function Wq($){try{return JSON.stringify($).length}catch{return String($).length}}async function qH($){let W=$.context.messages;if(W.length<2)return;let Z=LH(W,$.preserveRecentTokens,$.estimateMessageTokens);if(Z<=0||Z>=W.length)return;let Q=W.slice(0,Z),J=fH(Q),j=J>=0?k3(Q[J])?.summary:void 0,X=J>=0?Q.slice(J+1):Q;if(X.length===0)return;let Y=I3(Q),V=OH({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),B=tz(V),H=$.summarizer===void 0,G=Math.max($.context.budget.request.maxInputTokens,$.context.budget.request.triggerTokens,g3);if(B===void 0&&!H)$.logger?.log("Agentic compaction summarizer has no known input limit; using conservative summary budget",{severity:"warn",summarizerProviderId:V.providerId,summarizerModelId:V.modelId,fallbackInputLimit:g3});let K=B??(H?G:g3),F=pW(x3({previousSummary:j,conversationText:"",fileOps:Y}).length),A=K-F;if(A<=0){$.logger?.debug("Skipped agentic compaction: summarizer budget exhausted",{summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,summaryRequestOverheadTokens:F});return}let D=ez({messages:X,targetTokens:A,estimateMessageTokens:$.estimateMessageTokens});if(D.status==="failed"){$.logger?.log("Skipped agentic compaction: summary input budget failed",{severity:"warn",budgetWarnings:D.warnings.map((p)=>p.code),summaryInputEstimatedTokens:D.estimatedTokens,targetTokens:A,summarizerProviderId:V.providerId,summarizerModelId:V.modelId});return}let U=I3(D.messages),f=AH(D.messages),_=x3({previousSummary:j,conversationText:f,fileOps:U});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:X.length,preservedMessages:W.length-Z,previousSummaryChars:j?.length??0,conversationTextChars:f.length,summaryRequestChars:_.length,summaryRequestEstimatedTokens:pW(_.length),newMessagesJsonChars:Wq(X),summaryInputEstimatedTokens:D.estimatedTokens,summaryInputActions:D.actions.length,summaryInputWarnings:D.warnings.map((p)=>p.code),summaryRequestOverheadTokens:F,summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,maxInputTokens:$.context.budget.request.maxInputTokens,triggerTokens:$.context.budget.request.triggerTokens});let R=await $q({providerConfig:V,request:_,logger:$.logger});if(!R.trim())return;let O=TH(R,U),T=W.reduce((p,x)=>p+$.estimateMessageTokens(x),0),L=[zH({summary:O,fileOps:U,tokensBefore:T}),...W.slice(Z)],C=L.reduce((p,x)=>p+$.estimateMessageTokens(x),0);$.logger?.debug("Performed agentic compaction",{messagesBefore:W.length,messagesAfter:L.length,messagesSummarized:Z,messagesPreserved:W.length-Z,tokensBefore:T,tokensAfter:C,maxInputTokens:$.context.budget.request.maxInputTokens});let E=D.actions.filter((p)=>p.reason==="over_budget"||p.reason==="tool_pair_boundary").length;return{messages:L,budget:{policyIntent:"agentic_summary",actionCount:E,warningCount:D.warnings.length,liveTailHandling:D.liveTailHandling}}}import{CHARS_PER_TOKEN as Zq}from"@cline/shared";function Qq($){if(x4($))return;if(typeof $.content==="string"){let Z=$.content.trim();return Z?{...$,content:Z}:void 0}let W=$.content.filter((Z)=>Z.type!=="text"||Z.text.trim());if(W.length===0)return;return{...$,content:W.map((Z)=>Z.type==="text"?{...Z,text:Z.text.trim()}:Z.type==="tool_result"?{...Z,content:h3(Z.content)}:Z)}}function MH($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function RH($,W){if($.length<=W)return $;let Z=`
364
+ ...`,Q=Math.max(1,W-Z.length);return`${$.slice(0,Q)}${Z}`}function EH($,W){let Z=Number.isFinite(W)?Math.max(1,W):1,Q=Math.max(16,Z*Zq);if(typeof $.content==="string"){let X=RH($.content,Q).trim();return{...$,content:X||"..."}}let J=Q,j=$.content.map((X)=>{if(X.type!=="text"||J<=0)return X;let Y=RH(X.text,J).trim();return J-=Y.length,{...X,text:Y||"..."}});return{...$,content:j}}function Jq($,W){let Z=DH($),Q=rW($),J=_H($),j=[],X=0;for(let Y=0;Y<$.length;Y+=1){let V=Qq($[Y]);if(!V)continue;let B=W(V);X+=B,j.push({index:Y,message:V,estimatedTokens:B,toolPairIds:wH(V),isFirstUser:Y===Z,isLastUser:Y===Q,isLastAssistant:Y===J})}return{candidates:j,totalTokens:X}}function NH($,W,Z,Q){let J=$[W],j=J.estimatedTokens;return J.message=Z,J.estimatedTokens=Q(Z),J.toolPairIds=wH(Z),J.estimatedTokens-j}function wH($){if(!Array.isArray($.content))return[];let W=[];for(let Z of $.content)if(Z.type==="tool_use")W.push(Z.id);else if(Z.type==="tool_result")W.push(Z.tool_use_id);return W}function jq($){let W=new Map;for(let Z of $)for(let Q of Z.toolPairIds){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function Xq($,W,Z){let Q=new Set,J=[Z],j=0;while(j<J.length){let X=J[j];if(j+=1,X===void 0||!$.has(X)||Q.has(X))continue;Q.add(X);for(let Y of X.toolPairIds)for(let V of W.get(Y)??[])if(!Q.has(V))J.push(V)}return Q}function Yq($,W){let Z=0;for(let Q of $){if(W.has(Q))continue;$[Z]=Q,Z+=1}$.length=Z}function iW($,W,Z,Q){let J=new Set($),j=jq($);for(let X=0;X<$.length&&Q>Z;){if(!W($[X])){X+=1;continue}let Y=Xq(J,j,$[X]);if(Y.size===0){X+=1;continue}let V=0;for(let B of Y)V+=B.estimatedTokens,J.delete(B);Q-=V,Yq($,Y)}return Q}function Vq($,W,Z,Q,J){if(Z<=W)return Z;for(let X=$.length-1;X>=0&&Z>W;X-=1){let Y=$[X];if(Y.isFirstUser)continue;let V=Math.max(KH,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)continue;Z+=NH($,X,EH(Y.message,V),J)}if(Z<=W)return Z;let j=$.findIndex((X)=>X.isFirstUser);if(j>=0){if($[j].estimatedTokens<=Q)return Z;while(Z>W){let Y=$[j],V=Math.max(1,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)break;let B=Y.estimatedTokens;if(Z+=NH($,j,EH(Y.message,V),J),Y.estimatedTokens>=B)break}}return Z}function Bq($,W){return JSON.stringify($)!==JSON.stringify(W)}function Hq($){let W=rW($);if(W<0||W===0&&!g4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,W),protectedTail:$.slice(W)}}function CH($){let W=Math.max(1,Math.min($.context.budget.messages.targetTokens,$.context.budget.messages.triggerTokens)),{compactable:Z,protectedTail:Q}=Hq($.context.messages);if(Z.length===0)return;let J=MH(Q,$.estimateMessageTokens),j=Math.max(1,W-J),X=Jq(Z,$.estimateMessageTokens),{candidates:Y}=X;if(Y.length===0)return;let V=X.totalTokens,B=V;B=iW(Y,(U)=>U.message.role==="assistant"&&!U.isLastAssistant,j,B),B=iW(Y,(U)=>U.message.role==="user"&&!U.isFirstUser&&!U.isLastUser,j,B),B=iW(Y,(U)=>U.message.role==="assistant"&&U.isLastAssistant,j,B),B=iW(Y,(U)=>U.message.role==="user"&&U.isLastUser&&!U.isFirstUser,j,B),B=Vq(Y,j,B,$.context.budget.messages.triggerTokens,$.estimateMessageTokens);let H=[...Y.map((U)=>U.message),...Q],G=b4({messages:H,targetTokens:W,policyIntent:"basic_compaction_projection",estimateMessageTokens:$.estimateMessageTokens});if(G.status==="failed")$.logger?.debug("Basic compaction returned best-effort projection",{budgetWarnings:G.warnings.map((U)=>U.code),projectedTokens:G.estimatedTokens,targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens});let K=G.messages;if(!Bq($.context.messages,K))return;let F=V+J,A=MH(K,$.estimateMessageTokens),D=G.actions.filter((U)=>U.reason==="over_budget"||U.reason==="tool_pair_boundary").length;return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:K.length,messagesRemoved:$.context.messages.length-K.length,tokensBefore:F,tokensAfter:A,budgetStatus:G.status,budgetActions:D,budgetWarnings:G.warnings.map((U)=>U.code),targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens}),{messages:K,budget:{policyIntent:"basic_compaction_projection",actionCount:D,warningCount:G.warnings.length,liveTailHandling:G.liveTailHandling}}}var Kq=0.5;function SH($){try{return JSON.stringify($).length}catch{return String($).length}}function Fq($){let W=0,Z=0,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result")continue;let X=SH(j.content);W+=1,Z+=X,Q=Math.max(Q,X)}}return{toolResultCount:W,toolResultSerializedChars:Z,maxToolResultSerializedChars:Q}}var Aq={basic:({context:$,estimateMessageTokens:W,logger:Z})=>CH({context:$,estimateMessageTokens:W,logger:Z}),agentic:({context:$,providerConfig:W,compaction:Z,estimateMessageTokens:Q,logger:J})=>qH({context:$,providerConfig:W,summarizer:Z?.summarizer,preserveRecentTokens:Math.min(Z?.preserveRecentTokens??HH,$.budget.messages.targetTokens),estimateMessageTokens:Q,logger:J})};function Uq($){let W=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Z=Math.min(0.95,Math.max(0.05,W));return Math.max(1,Math.floor(Math.min($.messageTriggerTokens,$.messageInputTokens*Z)))}function Dq($){let W=$.messagePairCount>=5&&typeof $.modelMaxTokens==="number"&&Number.isFinite($.modelMaxTokens)&&$.modelMaxTokens<$.maxInputTokens?Math.floor($.maxInputTokens*Kq):Math.floor($.triggerTokens*BH),Z=Math.max(1,$.triggerTokens-1);return Math.max(1,Math.min(W,$.maxInputTokens,Z))}function PH($,W){return Math.max(1,Math.floor($-W))}function _q($){let W=0,Z=!1;for(let Q of $)if(Q.role==="user")Z=!0;else if(Q.role==="assistant"&&Z)W+=1,Z=!1;return W}function m4($,W={}){let Z=$.compaction;if(Z?.enabled!==!0)return;let Q=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},J=UH(),j=Z?.strategy??"basic",X=Aq[j],Y=W.mode??"auto",V=Z?.compact?"custom":j;return async(B)=>{let H=B.apiMessages.reduce((r,d)=>r+J(d),0),G=Gq({systemPrompt:B.systemPrompt,messages:B.apiMessages,tools:B.tools}),K=B.messages.reduce((r,d)=>r+J(d),0),F=Math.max(0,G-H),A=I4({maxInputTokens:B.model.info?.maxInputTokens,contextWindow:B.model.info?.contextWindow})??VH,D=A*U2,U=PH(D,F),f=G>=D;if($.logger?.debug("Context compaction diagnostics",{mode:Y,strategy:j,iteration:B.iteration,providerId:$.providerId,modelId:$.modelId,requestInputTokens:G,apiMessageTokens:H,messageInputTokens:K,requestOverheadTokens:F,maxInputTokens:A,requestTriggerTokens:D,messageTriggerTokens:U,thresholdRatio:U2,shouldCompact:f,messageCount:B.messages.length,apiMessageCount:B.apiMessages.length,apiMessagesJsonChars:SH(B.apiMessages),...Fq(B.apiMessages)}),Y==="auto"&&!f)return;let _,R;if(Y==="auto")_=Dq({maxInputTokens:A,modelMaxTokens:B.model.info?.maxTokens,triggerTokens:D,messagePairCount:_q(B.messages)}),R=PH(_,F);else R=Uq({messageInputTokens:K,messageTriggerTokens:U,manualTargetRatio:W.manualTargetRatio}),_=F+R;let O={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId,iteration:B.iteration,messages:B.messages,model:B.model,mode:Y,budget:{request:{inputTokens:G,maxInputTokens:A,triggerTokens:D,targetTokens:_,overheadTokens:F,thresholdRatio:U2,utilizationRatio:A>0?G/A:0},messages:{inputTokens:K,triggerTokens:U,targetTokens:R}}},T=Y==="manual"?"manual_compaction":"auto_compaction";B.emitStatusNotice?.(Y==="manual"?"compacting":"auto-compacting",{kind:T,reason:T,phase:"started",iteration:B.iteration,triggerTokens:D,targetTokens:_,maxInputTokens:A,messageTargetTokens:R});let L=B.messages.length,C=Date.now(),E=Z?.compact?await Z.compact(O):await X({context:O,providerConfig:{...Q,abortSignal:B.abortSignal},compaction:Z,estimateMessageTokens:J,logger:$.logger}),p=Date.now()-C,x=$.sessionId??B.conversationId,P={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId??void 0};if(E?.messages){let r=E.messages.reduce((I1,$2)=>I1+J($2),0),d=F+r;if($.logger?.log("Context compaction completed",{severity:"info",strategy:j,maxInputTokens:A,messageInputTokens:K,apiInputTokens:H,requestInputTokens:G,requestOverheadTokens:F,afterMessageTokens:r,afterRequestTokens:d,tokensSaved:G-d,utilizationBefore:`${(G/A*100).toFixed(1)}%`,utilizationAfter:`${(d/A*100).toFixed(1)}%`,thresholdTrigger:`${(U2*100).toFixed(1)}%`,messagesBefore:L,messagesAfter:E.messages.length,messagesRemoved:L-E.messages.length}),B.emitStatusNotice?.(Y==="manual"?"compacted":"auto-compacted",{kind:T,reason:T,phase:"completed",iteration:B.iteration,tokensBefore:G,tokensAfter:d,messagesBefore:L,messagesAfter:E.messages.length,maxInputTokens:A}),GW($.telemetry,{ulid:x,strategy:V,mode:Y,messagesBefore:L,messagesAfter:E.messages.length,messagesRemoved:L-E.messages.length,tokensBefore:G,tokensAfter:d,tokensSaved:G-d,triggerTokens:D,maxInputTokens:A,thresholdRatio:U2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P}),E.budget&&(E.budget.actionCount>0||E.budget.warningCount>0))NV($.telemetry,{ulid:x,strategy:V,mode:Y,policyIntent:E.budget.policyIntent,actionCount:E.budget.actionCount,warningCount:E.budget.warningCount,liveTailHandling:E.budget.liveTailHandling,provider:$.providerId,modelId:$.modelId,...P}),B.emitStatusNotice?.("compaction-budget-adjusted",{kind:"compaction_budget_emergency",reason:"compaction_budget_emergency",iteration:B.iteration,policyIntent:E.budget.policyIntent,actionCount:E.budget.actionCount,warningCount:E.budget.warningCount})}else B.emitStatusNotice?.(Y==="manual"?"compaction-skipped":"auto-compaction-skipped",{kind:T,reason:T,phase:"skipped",iteration:B.iteration,maxInputTokens:A}),KW($.telemetry,{ulid:x,strategy:V,mode:Y,reason:"no_result",tokensBefore:G,triggerTokens:D,maxInputTokens:A,thresholdRatio:U2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P});return E}}function v4($){return async(W)=>{let Z=$.getState?.(),Q=Z?A2(Z,W.messages):void 0;if(Z&&Q){let j=$.compact?await $.compact({...W,messages:Q,apiMessages:Q}):void 0;if(j?.messages){let X=j.systemPrompt??Z.system_prompt,Y=k8({sourceMessages:W.messages,compactedMessages:j.messages,conversationId:W.conversationId,systemPrompt:X});return await $.saveState?.(Y),{...j,...X!==void 0?{systemPrompt:X}:{}}}return{messages:Q,...j?.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:Z.system_prompt!==void 0?{systemPrompt:Z.system_prompt}:{}}}let J=$.compact?await $.compact(W):void 0;if(J?.messages){let j=k8({sourceMessages:W.messages,compactedMessages:J.messages,conversationId:W.conversationId,systemPrompt:J.systemPrompt});await $.saveState?.(j)}return J}}var YK={};w(YK,{zodToJsonSchema:()=>LE,validateWithZod:()=>fE,truncateCommandOutput:()=>L2,resolveToolRoutingConfig:()=>r8,resolveToolPresetName:()=>e1,resolveCoreSelectedToolIds:()=>AZ,getCoreHeadlessToolNames:()=>j5,getCoreDefaultEnabledToolIds:()=>FZ,getCoreBuiltinToolCatalog:()=>b2,getCoreAcpToolNames:()=>UZ,createWebFetchTool:()=>l3,createWebFetchExecutor:()=>e4,createToolPoliciesWithPreset:()=>JZ,createSubmitAndExitTool:()=>n3,createSkillsTool:()=>O2,createShellTool:()=>o4,createShellExecutor:()=>T2,createSearchTool:()=>d3,createSearchExecutor:()=>t4,createReadFilesTool:()=>u3,createFileReadExecutor:()=>s4,createEditorTool:()=>r3,createEditorExecutor:()=>M2,createDefaultToolsWithPreset:()=>jZ,createDefaultTools:()=>N$,createDefaultShellExecutor:()=>$5,createDefaultExecutors:()=>l8,createBuiltinTools:()=>y2,createAskQuestionTool:()=>i3,createApplyPatchTool:()=>p3,createApplyPatchExecutor:()=>q2,computePatchChanges:()=>c8,WebFetchRequestSchema:()=>m3,ToolPresets:()=>a0,TEAM_TOOL_NAMES:()=>a8,SubmitInputSchema:()=>a4,StructuredCommandInputSchema:()=>_2,SkillsInputSchema:()=>i4,SearchCodebaseInputSchema:()=>u4,RunCommandsInputSchema:()=>d4,ReadFilesInputSchema:()=>c4,ReadFileRequestSchema:()=>sW,PatchActionType:()=>z2,MAX_COMMAND_OUTPUT_CHARS:()=>a1,FetchWebContentInputSchema:()=>l4,EditFileInputSchema:()=>p4,DefaultToolNames:()=>O0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>p8,CommandExitError:()=>o1,AskQuestionInputSchema:()=>n4,ApplyPatchInputSchema:()=>r4,ALL_DEFAULT_TOOL_NAMES:()=>D$});import{validateWithZod as fE,zodToJsonSchema as LE}from"@cline/shared";z0();import{createTool as R$,validateWithZod as E$,zodToJsonSchema as s1}from"@cline/shared";var nW="__clineInternalTelemetry";function yH($){let W=$?.__clineInternalTelemetry;return W&&typeof W==="object"&&"capture"in W&&typeof W.capture==="function"?W:void 0}import{spawn as rH}from"node:child_process";import{StringDecoder as qq}from"node:string_decoder";import{getDefaultShell as Mq,getShellArgs as Rq}from"@cline/shared";import{validateWithZod as Lq}from"@cline/shared";import{z}from"zod";var M$=6000,D2=z.string().describe("The absolute path of a text file to read content from"),aW=z.object({start_line:z.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:z.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit to read to the end of the file or the read cap, whichever comes first")}).describe("Optional inclusive one-based file line range"),sW=z.object({path:D2,start_line:aW.shape.start_line,end_line:aW.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds. Always include path; start_line/end_line must be on the same object as the path they apply to, never in a separate array element"),c4=z.object({files:z.array(sW).describe("Array of file read requests; each element is one file and must include path. Omit start_line/end_line or set them to null to read from the start; provide integers on the same object as the path to return only that inclusive one-based line range — never emit a range as its own array element. Reads are capped, so page through long files with start_line/end_line. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),hH={start_line:aW.shape.start_line,end_line:aW.shape.end_line},x8=z.union([sW,z.object({file_path:D2,...hH}).transform(({file_path:$,...W})=>({path:$,...W})),z.object({filePath:D2,...hH}).transform(({filePath:$,...W})=>({path:$,...W}))]),kH=z.union([c4,x8,z.array(x8),z.array(z.string()),z.string(),z.object({files:z.array(z.union([D2,x8]))}),z.object({files:x8}),z.object({files:D2}),z.object({file_paths:z.array(D2)}),z.object({file_paths:z.string()}),z.object({paths:z.array(z.union([D2,x8]))}),z.object({paths:x8}),z.object({paths:z.string()})]),u4=z.object({queries:z.array(z.string()).describe("Array of regex search queries to execute")}),IH=z.union([u4,z.array(z.string()),z.string(),z.object({queries:z.string()})]),oW=z.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${M$*2} characters) to avoid timeouts.`),_2=z.object({command:z.string().min(1).describe("The executable to run directly without shell parsing."),args:z.array(z.string()).optional().describe("Optional argv list passed directly to the executable.")}),xH=z.union([oW,_2]),d4=z.object({commands:z.array(oW).describe("Array of complete shell command strings to execute.")}),fq=z.object({commands:z.array(xH)}),gH=z.union([d4,fq,z.object({commands:xH}),z.array(_2),_2,z.object({command:oW}),z.object({cmd:oW}),z.array(z.string()),z.string()]),m3=z.object({url:z.string().describe("The URL to fetch"),prompt:z.string().min(2).describe("Analysis prompt for the fetched content")}),l4=z.object({requests:z.array(m3).describe("Array of the URLs for the web fetch requests")}),p4=z.object({path:z.string().min(1).describe("The absolute path for the action to be performed on"),old_text:z.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${M$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:z.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${M$} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:z.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),r4=z.object({input:z.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),mH=z.union([r4,z.string()]),i4=z.object({skill:z.string().min(1).describe("Name of the skill to execute."),args:z.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),n4=z.object({question:z.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:z.array(z.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),a4=z.object({summary:z.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:z.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
365
365
  'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
366
- IMPORTANT: You must run the specific failing test(s) mentioned in the issue or test patch and include the test output in your reasoning. If the test still fails after your fix, you must revise. Do NOT submit with 'true' unless the test output shows the test passing.`)});function f2($){if($ instanceof Error)return $.message;return String($)}function vH($){if(typeof $.old_text==="string"&&$.old_text.length>M$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${M$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>M$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${M$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class g8 extends Error{timeoutMs;constructor($,W){super($);this.name="TimeoutError",this.timeoutMs=W}}function n1($,W,Z){return Promise.race([$,new Promise((Q,J)=>{setTimeout(()=>J(new g8(Z,W)),W)})])}function sW($){let{path:W,start_line:Z,end_line:Q}=$;if(Z==null&&Q==null)return W;return`${W}:${Z??1}-${Q??"EOF"}`}function cH($){let{start_line:W,end_line:Z}=$;if(W==null||Z==null||W<=Z)return null;return`start_line must be less than or equal to end_line (received start_line: ${W}, end_line: ${Z})`}var Lq=new Set(["start_line","end_line"]);function Tq($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let W=Object.keys($);return W.length>0&&W.every((Z)=>Lq.has(Z))}function mH($){let W=[];for(let Z of $){if(Tq(Z)){let Q=W[W.length-1];if(typeof Q==="string"){W[W.length-1]={path:Q,...Z};continue}if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q)&&"path"in Q&&Object.keys(Z).every((J)=>!(J in Q))){W[W.length-1]={...Q,...Z};continue}}W.push(Z)}return W}function uH($){if(Array.isArray($))return mH($);if($!==null&&typeof $==="object")for(let W of["files","paths"]){let Z=$[W];if(Array.isArray(Z))return{...$,[W]:mH(Z)}}return $}function dH($){let W=fq(xH,$);if(typeof W==="string")return[W];if(Array.isArray(W))return W;if("commands"in W)return Array.isArray(W.commands)?W.commands:[W.commands];if("command"in W)return"args"in W?[W]:[W.command];if("cmd"in W)return[W.cmd];return[W]}function Oq($){if(typeof $==="string")return $;let W=$.args??[];if(W.length===0)return $.command;let Z=W.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${$.command} ${Z.join(" ")}`}var m3=200;function lH($){let W=Oq($);if(W.length<=m3)return W;let Z=W.length-m3;return`${W.slice(0,m3)} ... [command truncated: ${Z} more chars; full command is in the tool call input]`}var a1=48000;function L2($,W={}){let Z=W.maxChars??48000,Q=W.totalChars??$.length;if($.length<=Z&&Q<=Z)return $;let J=Math.ceil(Z/2),j=Math.max(1,Z-J);return`${$.slice(0,J)}
366
+ IMPORTANT: You must run the specific failing test(s) mentioned in the issue or test patch and include the test output in your reasoning. If the test still fails after your fix, you must revise. Do NOT submit with 'true' unless the test output shows the test passing.`)});function f2($){if($ instanceof Error)return $.message;return String($)}function cH($){if(typeof $.old_text==="string"&&$.old_text.length>M$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${M$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>M$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${M$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class g8 extends Error{timeoutMs;constructor($,W){super($);this.name="TimeoutError",this.timeoutMs=W}}function n1($,W,Z){return Promise.race([$,new Promise((Q,J)=>{setTimeout(()=>J(new g8(Z,W)),W)})])}function tW($){let{path:W,start_line:Z,end_line:Q}=$;if(Z==null&&Q==null)return W;return`${W}:${Z??1}-${Q??"EOF"}`}function uH($){let{start_line:W,end_line:Z}=$;if(W==null||Z==null||W<=Z)return null;return`start_line must be less than or equal to end_line (received start_line: ${W}, end_line: ${Z})`}var Tq=new Set(["start_line","end_line"]);function Oq($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let W=Object.keys($);return W.length>0&&W.every((Z)=>Tq.has(Z))}function vH($){let W=[];for(let Z of $){if(Oq(Z)){let Q=W[W.length-1];if(typeof Q==="string"){W[W.length-1]={path:Q,...Z};continue}if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q)&&"path"in Q&&Object.keys(Z).every((J)=>!(J in Q))){W[W.length-1]={...Q,...Z};continue}}W.push(Z)}return W}function dH($){if(Array.isArray($))return vH($);if($!==null&&typeof $==="object")for(let W of["files","paths"]){let Z=$[W];if(Array.isArray(Z))return{...$,[W]:vH(Z)}}return $}function lH($){let W=Lq(gH,$);if(typeof W==="string")return[W];if(Array.isArray(W))return W;if("commands"in W)return Array.isArray(W.commands)?W.commands:[W.commands];if("command"in W)return"args"in W?[W]:[W.command];if("cmd"in W)return[W.cmd];return[W]}function zq($){if(typeof $==="string")return $;let W=$.args??[];if(W.length===0)return $.command;let Z=W.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${$.command} ${Z.join(" ")}`}var v3=200;function pH($){let W=zq($);if(W.length<=v3)return W;let Z=W.length-v3;return`${W.slice(0,v3)} ... [command truncated: ${Z} more chars; full command is in the tool call input]`}var a1=48000;function L2($,W={}){let Z=W.maxChars??48000,Q=W.totalChars??$.length;if($.length<=Z&&Q<=Z)return $;let J=Math.ceil(Z/2),j=Math.max(1,Z-J);return`${$.slice(0,J)}
367
367
  [... output truncated: ${Q} chars total. Refine the command (grep, head, tail) to view the elided middle ...]
368
- `+$.slice(-j)}var m8=2000,v3=2000,tW=48000,v8=48000;class o1 extends Error{exitCode;output;constructor($,W){super(`Command exited with code ${$}`);this.exitCode=$;this.output=W;this.name="CommandExitError"}}function rH($){let W=Math.ceil($/2),Z=Math.max(1,$-W),Q=new zq("utf8"),J="",j="",X=0,Y=(V)=>{if(!V)return;X+=V.length;let B=W-J.length;if(B>0){J+=V.slice(0,B),j=(j+V.slice(B)).slice(-Z);return}j=(j+V).slice(-Z)};return{append(V){Y(Q.write(V))},snapshot(){return Y(Q.end()),{text:J+j,totalChars:X,dropped:X>J.length+j.length}}}}function Rq($,W,Z,Q,J){return new Promise((j,X)=>{let Y=process.platform==="win32",V=pH($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!Y,windowsHide:!0}),B=V.pid,H=rH(Q),G=rH(Q),K=!1,F=!1,A=(O)=>{if(F)return;F=!0,O()},D=()=>{if(!B)return;if(Y){pH("taskkill",["/pid",String(B),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-B,"SIGKILL")}catch{V.kill("SIGKILL")}},U=(O)=>{K=!0,D(),A(()=>X(O))},f=setTimeout(()=>U(new g8(`Command timed out after ${Z}ms`,Z)),Z),_=()=>U(Error("Command was aborted"));if(W.signal)W.signal.addEventListener("abort",_);let R=()=>{clearTimeout(f),W.signal?.removeEventListener("abort",_)};V.stdout?.on("data",(O)=>{H.append(O)}),V.stderr?.on("data",(O)=>{G.append(O)}),V.on("close",(O)=>{if(R(),K)return;let T=H.snapshot(),L=G.snapshot();if(O!==0){let C=O??1,E=J?T.text+(L.text?`
368
+ `+$.slice(-j)}var m8=2000,c3=2000,eW=48000,v8=48000;class o1 extends Error{exitCode;output;constructor($,W){super(`Command exited with code ${$}`);this.exitCode=$;this.output=W;this.name="CommandExitError"}}function iH($){let W=Math.ceil($/2),Z=Math.max(1,$-W),Q=new qq("utf8"),J="",j="",X=0,Y=(V)=>{if(!V)return;X+=V.length;let B=W-J.length;if(B>0){J+=V.slice(0,B),j=(j+V.slice(B)).slice(-Z);return}j=(j+V).slice(-Z)};return{append(V){Y(Q.write(V))},snapshot(){return Y(Q.end()),{text:J+j,totalChars:X,dropped:X>J.length+j.length}}}}function Eq($,W,Z,Q,J){return new Promise((j,X)=>{let Y=process.platform==="win32",V=rH($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!Y,windowsHide:!0}),B=V.pid,H=iH(Q),G=iH(Q),K=!1,F=!1,A=(O)=>{if(F)return;F=!0,O()},D=()=>{if(!B)return;if(Y){rH("taskkill",["/pid",String(B),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-B,"SIGKILL")}catch{V.kill("SIGKILL")}},U=(O)=>{K=!0,D(),A(()=>X(O))},f=setTimeout(()=>U(new g8(`Command timed out after ${Z}ms`,Z)),Z),_=()=>U(Error("Command was aborted"));if(W.signal)W.signal.addEventListener("abort",_);let R=()=>{clearTimeout(f),W.signal?.removeEventListener("abort",_)};V.stdout?.on("data",(O)=>{H.append(O)}),V.stderr?.on("data",(O)=>{G.append(O)}),V.on("close",(O)=>{if(R(),K)return;let T=H.snapshot(),L=G.snapshot();if(O!==0){let C=O??1,E=J?T.text+(L.text?`
369
369
  [stderr]
370
370
  ${L.text}`:""):T.text,p=T.dropped||J&&L.dropped,x=J?T.totalChars+L.totalChars:T.totalChars;if(p||E.length>Q)E=L2(E,{maxChars:Q,totalChars:x});let P=E.length>0?`[Command exited with code ${C}]
371
371
  ${E}`:`[Command exited with code ${C}]`;A(()=>X(new o1(C,P)))}else{let C=J?T.text+(L.text?`
372
372
  [stderr]
373
- ${L.text}`:""):T.text;if(T.dropped||J&&L.dropped||C.length>Q){let p=J?T.totalChars+L.totalChars:T.totalChars;C=L2(C,{maxChars:Q,totalChars:p})}A(()=>j(C))}}),V.on("error",(O)=>{R(),A(()=>X(Error(`Failed to execute command: ${O.message}`)))})})}function T2($={}){let{shell:W=qq(process.platform),timeoutMs:Z=30000,env:Q={},combineOutput:J=!0}=$,j=$.maxOutputChars??$.maxOutputBytes??a1;return(X,Y,V)=>{let B=typeof X!=="string";return Rq({executable:B?X.command:W,args:B?X.args??[]:Mq(W,X),cwd:Y,env:Q},V,Z,j,J)}}function iH($,W){let Z=$.metadata?.[W];return typeof Z==="string"?Z:void 0}function Eq($,W){RV(bH($.metadata),{tool_name:"run_commands",effective_timeout_ms:W.effectiveTimeoutMs,timeout_source:W.timeoutSource,command_count:W.commandCount,duration_ms:W.durationMs,ulid:$.sessionId,mode:iH($,"mode"),source:iH($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function Nq($){let W=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return W?.[1]??W?.[2]??W?.[3]}function wq($){let W=[];for(let Z=0;Z<$.length;Z+=1){let Q=$[Z],J=Nq(Q);if(!J){W.push(Q);continue}let j=$.findIndex((Y,V)=>V>Z&&Y.trim()===J);if(j===-1){W.push(Q);continue}let X=[Q];while(Z<j){Z+=1;let Y=$[Z];X.push(Y)}W.push(X.join(`
374
- `))}return W}function Cq($){let W=[],Z=[],Q=()=>{if(Z.length>0)W.push(...wq(Z)),Z=[]};for(let J of $){if(typeof J==="string"){Z.push(J);continue}Q(),W.push(J)}return Q(),W}async function Pq($,W){let{executor:Z,cwd:Q,context:J,timeoutMs:j,timeoutSource:X}=W;return Promise.all($.map(async(Y)=>{let V=Date.now(),B=lH(Y);try{let H=await n1(Z(Y,Q,J),j,`Command timed out after ${j}ms`);return{query:B,result:H,success:!0}}catch(H){if(H instanceof g8)Eq(J,{effectiveTimeoutMs:H.timeoutMs,timeoutSource:X,commandCount:$.length,durationMs:Date.now()-V});if(H instanceof o1)return{query:B,result:H.output,error:H.message,success:!1};let G=f2(H);return{query:B,result:"",error:`Command failed: ${G}`,success:!1}}}))}function c3($,W={}){let Z=W.fileReadTimeoutMs??1e4;return R$({name:"read_files",description:`Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided on the same file entry as its path. When you already know multiple files you need, read them together in one call, and call this tool in the same response as other independent tool calls. Each read returns at most ${m8} lines / ~${Math.round(tW/1024)}k characters; longer files report their total line count, page through them with start_line/end_line on that file's entry. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:s1(c4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(Q,J)=>{let j=E$(hH,uH(Q)),X;if(typeof j==="string")X=[{path:j}];else if(Array.isArray(j))X=j.map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("files"in j)X=(Array.isArray(j.files)?j.files:[j.files]).map((V)=>typeof V==="string"?{path:V}:V);else if("file_paths"in j)X=(Array.isArray(j.file_paths)?j.file_paths:[j.file_paths]).map((V)=>({path:V}));else if("paths"in j)X=(Array.isArray(j.paths)?j.paths:[j.paths]).map((V)=>typeof V==="string"?{path:V}:V);else X=[j];return Promise.all(X.map(async(Y)=>{let V=cH(Y);if(V)return{query:sW(Y),result:"",error:`Invalid file range: ${V}`,success:!1};try{let B=await n1($(Y,J),Z,`File read timed out after ${Z}ms`);return{query:sW(Y),result:B,success:!0}}catch(B){let H=f2(B);return{query:sW(Y),result:"",error:`Error reading file: ${H}`,success:!1}}}))}})}function u3($,W={}){let Z=W.searchTimeoutMs??30000,Q=W.cwd??process.cwd();return R$({name:"search_codebase",description:`Perform regex pattern searches across the codebase. Supports multiple parallel searches. When several search patterns could be useful and do not depend on each other, run them together in one call, and call this tool in the same response as other independent tool calls. Use for finding code patterns, function definitions, class names, imports, etc. Output beyond ~${Math.round(v8/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:s1(u4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(J,j)=>{let X=E$(kH,J),Y=Array.isArray(X)?X:typeof X==="object"?Array.isArray(X.queries)?X.queries:[X.queries]:[X];return Promise.all(Y.map(async(V)=>{try{let B=await n1($(V,Q,j),Z,`Search timed out after ${Z}ms`);return{query:V,result:B,success:!0}}catch(B){let H=f2(B);return{query:V,result:"",error:`Search failed: ${H}`,success:!1}}}))}})}var nH="Use for listing files, checking git status, running builds, executing tests, etc. Commands must be non-interactive. Commands that require follow-up input like pagers should be skipped or used with supported flags/env (e.g. git --no-pager, --non-interactive) to bypass the interaction steps. ";function o4($,W={}){let Z=W.bashTimeoutMs??30000,Q=W.bashTimeoutMs===void 0?"default_setting":"configured_setting",J=W.cwd??process.cwd(),j=process.platform==="win32";return R$({name:"run_commands",description:j?"Run non-interactive shell commands from the root of the workspace in Windows environment. "+nH+`Output beyond ~${Math.round(a1/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Commands run through PowerShell; quote paths and arguments for PowerShell and use ';' to sequence commands. Include multiple commands in the same call when they are independent and safe to run concurrently. When independent reads, searches, or edits are also needed, call those tools in the same response.`:"Run non-interactive shell commands from the root of the workspace. "+nH+`Commands should be properly shell-escaped and targeted to avoid error or timeout. Include multiple commands in the same call when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. When independent reads, searches, or edits are also needed, call those tools in the same response. Output beyond ~${Math.round(a1/1000)}k characters is middle-truncated (start and end preserved); pipe through grep/head/tail when you need specific sections of large output. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.`,inputSchema:s1(d4),timeoutMs:Z*2,retryable:!1,maxRetries:0,execute:async(X,Y)=>{let V=Cq(dH(X));return Pq(V,{executor:$,cwd:J,context:Y,timeoutMs:Z,timeoutSource:Q})}})}function d3($,W={}){let Z=W.webFetchTimeoutMs??30000;return R$({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract. Fetch independent URLs together in one call, and call this tool in the same response as other independent tool calls.",inputSchema:s1(l4),timeoutMs:Z*2,retryable:!0,maxRetries:2,execute:async(Q,J)=>{let j=E$(l4,Q);return Promise.all(j.requests.map(async(X)=>{try{let Y=await n1($(X.url,X.prompt,J),Z,`Web fetch timed out after ${Z}ms`);return{query:X.url,result:Y,success:!0}}catch(Y){let V=f2(Y);return{query:X.url,result:"",error:`Error fetching web content: ${V}`,success:!1}}}))}})}var Sq=`Use \`apply_patch\` to edit files with the canonical freeform patch grammar. Pass the patch text directly as the \`input\` string. Prefer the exact format below:
373
+ ${L.text}`:""):T.text;if(T.dropped||J&&L.dropped||C.length>Q){let p=J?T.totalChars+L.totalChars:T.totalChars;C=L2(C,{maxChars:Q,totalChars:p})}A(()=>j(C))}}),V.on("error",(O)=>{R(),A(()=>X(Error(`Failed to execute command: ${O.message}`)))})})}function T2($={}){let{shell:W=Mq(process.platform),timeoutMs:Z=30000,env:Q={},combineOutput:J=!0}=$,j=$.maxOutputChars??$.maxOutputBytes??a1;return(X,Y,V)=>{let B=typeof X!=="string";return Eq({executable:B?X.command:W,args:B?X.args??[]:Rq(W,X),cwd:Y,env:Q},V,Z,j,J)}}function nH($,W){let Z=$.metadata?.[W];return typeof Z==="string"?Z:void 0}function Nq($,W){EV(yH($.metadata),{tool_name:"run_commands",effective_timeout_ms:W.effectiveTimeoutMs,timeout_source:W.timeoutSource,command_count:W.commandCount,duration_ms:W.durationMs,ulid:$.sessionId,mode:nH($,"mode"),source:nH($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function wq($){let W=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return W?.[1]??W?.[2]??W?.[3]}function Cq($){let W=[];for(let Z=0;Z<$.length;Z+=1){let Q=$[Z],J=wq(Q);if(!J){W.push(Q);continue}let j=$.findIndex((Y,V)=>V>Z&&Y.trim()===J);if(j===-1){W.push(Q);continue}let X=[Q];while(Z<j){Z+=1;let Y=$[Z];X.push(Y)}W.push(X.join(`
374
+ `))}return W}function Pq($){let W=[],Z=[],Q=()=>{if(Z.length>0)W.push(...Cq(Z)),Z=[]};for(let J of $){if(typeof J==="string"){Z.push(J);continue}Q(),W.push(J)}return Q(),W}async function Sq($,W){let{executor:Z,cwd:Q,context:J,timeoutMs:j,timeoutSource:X}=W;return Promise.all($.map(async(Y)=>{let V=Date.now(),B=pH(Y);try{let H=await n1(Z(Y,Q,J),j,`Command timed out after ${j}ms`);return{query:B,result:H,success:!0}}catch(H){if(H instanceof g8)Nq(J,{effectiveTimeoutMs:H.timeoutMs,timeoutSource:X,commandCount:$.length,durationMs:Date.now()-V});if(H instanceof o1)return{query:B,result:H.output,error:H.message,success:!1};let G=f2(H);return{query:B,result:"",error:`Command failed: ${G}`,success:!1}}}))}function u3($,W={}){let Z=W.fileReadTimeoutMs??1e4;return R$({name:"read_files",description:`Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided on the same file entry as its path. When you already know multiple files you need, read them together in one call, and call this tool in the same response as other independent tool calls. Each read returns at most ${m8} lines / ~${Math.round(eW/1024)}k characters; longer files report their total line count, page through them with start_line/end_line on that file's entry. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:s1(c4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(Q,J)=>{let j=E$(kH,dH(Q)),X;if(typeof j==="string")X=[{path:j}];else if(Array.isArray(j))X=j.map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("files"in j)X=(Array.isArray(j.files)?j.files:[j.files]).map((V)=>typeof V==="string"?{path:V}:V);else if("file_paths"in j)X=(Array.isArray(j.file_paths)?j.file_paths:[j.file_paths]).map((V)=>({path:V}));else if("paths"in j)X=(Array.isArray(j.paths)?j.paths:[j.paths]).map((V)=>typeof V==="string"?{path:V}:V);else X=[j];return Promise.all(X.map(async(Y)=>{let V=uH(Y);if(V)return{query:tW(Y),result:"",error:`Invalid file range: ${V}`,success:!1};try{let B=await n1($(Y,J),Z,`File read timed out after ${Z}ms`);return{query:tW(Y),result:B,success:!0}}catch(B){let H=f2(B);return{query:tW(Y),result:"",error:`Error reading file: ${H}`,success:!1}}}))}})}function d3($,W={}){let Z=W.searchTimeoutMs??30000,Q=W.cwd??process.cwd();return R$({name:"search_codebase",description:`Perform regex pattern searches across the codebase. Supports multiple parallel searches. When several search patterns could be useful and do not depend on each other, run them together in one call, and call this tool in the same response as other independent tool calls. Use for finding code patterns, function definitions, class names, imports, etc. Output beyond ~${Math.round(v8/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:s1(u4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(J,j)=>{let X=E$(IH,J),Y=Array.isArray(X)?X:typeof X==="object"?Array.isArray(X.queries)?X.queries:[X.queries]:[X];return Promise.all(Y.map(async(V)=>{try{let B=await n1($(V,Q,j),Z,`Search timed out after ${Z}ms`);return{query:V,result:B,success:!0}}catch(B){let H=f2(B);return{query:V,result:"",error:`Search failed: ${H}`,success:!1}}}))}})}var aH="Use for listing files, checking git status, running builds, executing tests, etc. Commands must be non-interactive. Commands that require follow-up input like pagers should be skipped or used with supported flags/env (e.g. git --no-pager, --non-interactive) to bypass the interaction steps. ";function o4($,W={}){let Z=W.bashTimeoutMs??30000,Q=W.bashTimeoutMs===void 0?"default_setting":"configured_setting",J=W.cwd??process.cwd(),j=process.platform==="win32";return R$({name:"run_commands",description:j?"Run non-interactive shell commands from the root of the workspace in Windows environment. "+aH+`Output beyond ~${Math.round(a1/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Commands run through PowerShell; quote paths and arguments for PowerShell and use ';' to sequence commands. Include multiple commands in the same call when they are independent and safe to run concurrently. When independent reads, searches, or edits are also needed, call those tools in the same response.`:"Run non-interactive shell commands from the root of the workspace. "+aH+`Commands should be properly shell-escaped and targeted to avoid error or timeout. Include multiple commands in the same call when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. When independent reads, searches, or edits are also needed, call those tools in the same response. Output beyond ~${Math.round(a1/1000)}k characters is middle-truncated (start and end preserved); pipe through grep/head/tail when you need specific sections of large output. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.`,inputSchema:s1(d4),timeoutMs:Z*2,retryable:!1,maxRetries:0,execute:async(X,Y)=>{let V=Pq(lH(X));return Sq(V,{executor:$,cwd:J,context:Y,timeoutMs:Z,timeoutSource:Q})}})}function l3($,W={}){let Z=W.webFetchTimeoutMs??30000;return R$({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract. Fetch independent URLs together in one call, and call this tool in the same response as other independent tool calls.",inputSchema:s1(l4),timeoutMs:Z*2,retryable:!0,maxRetries:2,execute:async(Q,J)=>{let j=E$(l4,Q);return Promise.all(j.requests.map(async(X)=>{try{let Y=await n1($(X.url,X.prompt,J),Z,`Web fetch timed out after ${Z}ms`);return{query:X.url,result:Y,success:!0}}catch(Y){let V=f2(Y);return{query:X.url,result:"",error:`Error fetching web content: ${V}`,success:!1}}}))}})}var bq=`Use \`apply_patch\` to edit files with the canonical freeform patch grammar. Pass the patch text directly as the \`input\` string. Prefer the exact format below:
375
375
 
376
376
  *** Begin Patch
377
377
  *** Update File: path/to/file.ts
@@ -407,48 +407,48 @@ Example:
407
407
  </div>
408
408
  );
409
409
  }
410
- *** End Patch`;function l3($,W={}){let Z=W.applyPatchTimeoutMs??30000,Q=W.cwd??process.cwd();return R$({name:"apply_patch",description:Sq,inputSchema:s1(r4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=E$(gH,J),Y=typeof X==="string"?X:X.input;try{return{query:"apply_patch",result:await n1($({input:Y},Q,j),Z,`apply_patch timed out after ${Z}ms`),success:!0}}catch(V){return{query:"apply_patch",result:"",error:`apply_patch failed: ${f2(V)}`,success:!1}}}})}function p3($,W={}){let Z=W.editorTimeoutMs??30000,Q=W.cwd??process.cwd();return R$({name:"editor",description:"An editor for controlled filesystem edits on the text file at the provided path. Provide `insert_line` to insert `new_text` at a specific line number. Otherwise, the tool replaces `old_text` with `new_text`, or creates the file with `new_text` if file does not exist. Use this tool for making small, precise edits to existing files or creating new files over shell commands. If several edits to different files or non-overlapping regions are already known, emit multiple editor tool calls in the same response instead of serializing them across turns.",inputSchema:s1(p4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=E$(p4,J),Y=X.insert_line==null?"edit":"insert",V=vH(X);if(V)return{query:`${Y}:${X.path}`,result:"",error:V,success:!1};try{let B=await n1($(X,Q,j),Z,`Editor operation timed out after ${Z}ms`);return{query:`${Y}:${X.path}`,result:B,success:!0}}catch(B){let H=f2(B);return{query:`${Y}:${X.path}`,result:"",error:`Editor operation failed: ${H}`,success:!1}}}})}function O2($,W={}){let Z=W.skillsTimeoutMs??15000,Q='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',J=R$({name:"skills",description:Q,inputSchema:s1(i4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(j,X)=>{let Y=E$(i4,j);return n1($(Y.skill,Y.args||void 0,X),Z,`Skills operation timed out after ${Z}ms`)}});return Object.defineProperty(J,"description",{get(){let j=$.configuredSkills?.filter((X)=>!X.disabled).map((X)=>X.name);if(j&&j.length>0)return`${Q} Available skills: ${j.join(", ")}.`;return Q},enumerable:!0,configurable:!0}),J}function r3($){return{name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:s1(n4),retryable:!1,maxRetries:0,execute:async(W,Z)=>{let Q=E$(n4,W);return $(Q.question,Q.options,Z)}}}function i3($,W={}){let Z=W.submitTimeoutMs??15000;return R$({name:"submit_and_exit",description:"Submit the final answer and exit the conversation. For example, submit a summary of the investigation and confirm the issue is resolved. You should only submit once all necessary steps are completed. Make sure to verify your output matches the expected format, data types, and file locations specified. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:s1(a4),lifecycle:{completesRun:!0},timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(Q,J)=>{let j=E$(a4,Q);return n1($(j.summary,j.verified,J),Z,`submit_and_exit timed out after ${Z}ms`)}})}function N$($){let{executors:W,enableReadFiles:Z=!0,enableSearch:Q=!0,enableBash:J=!0,enableWebFetch:j=!0,enableApplyPatch:X=!1,enableEditor:Y=!0,enableSkills:V=!0,enableAskQuestion:B=!0,enableSubmitAndExit:H=!1,...G}=$,K=[];if(Z&&W.readFile)K.push(c3(W.readFile,G));if(Q&&W.search)K.push(u3(W.search,G));if(J&&W.bash)K.push(o4(W.bash,G));if(j&&W.webFetch)K.push(d3(W.webFetch,G));if(Y&&W.editor)K.push(p3(W.editor,G));else if(X&&W.applyPatch)K.push(l3(W.applyPatch,G));if(V&&W.skills)K.push(O2(W.skills,G));let F=H?W.submit:void 0;if(B&&W.askQuestion&&!F)K.push(r3(W.askQuestion));if(F)K.push(i3(F,G));return K}import*as i0 from"node:fs/promises";import*as n0 from"node:path";var n={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},oH=["%%bash","apply_patch","EOF","```"],z2;((Q)=>{Q.ADD="add";Q.DELETE="delete";Q.UPDATE="update"})(z2||={});class G0 extends Error{constructor($){super($);this.name="DiffError"}}function r0($){let W={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Z)=>W[Z]??Z).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class n3{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,W){this.lines=$;this.currentFiles=W}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(n.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(n.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(n.UPDATE)){this.parseUpdate($.substring(n.UPDATE.length).trim());return}if($?.startsWith(n.DELETE)){this.parseDelete($.substring(n.DELETE.length).trim());return}if($?.startsWith(n.ADD)){this.parseAdd($.substring(n.ADD.length).trim());return}throw new G0(`Unknown line while parsing: ${$}`)}checkDuplicate($,W){if($ in this.patch.actions)throw new G0(`Duplicate ${W} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let W=this.lines[this.index]?.startsWith(n.MOVE)?(this.lines[this.index++]??"").substring(n.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new G0(`Update File Error: Missing File: ${$}`);let Z=this.currentFiles[$]??"",Q=this.parseUpdateFile(Z,$);Q.movePath=W,this.patch.actions[$]=Q,this.currentPath=void 0}parseUpdateFile($,W){let Z={type:"update",chunks:[]},Q=$.split(`
411
- `),J=0,j=[n.END,n.UPDATE,n.DELETE,n.ADD,n.END_FILE];while(!j.some((X)=>this.lines[this.index]?.startsWith(X.trim()))){let X=this.lines[this.index],Y=X?.startsWith("@@ ")?X.substring(3):void 0;if(Y!==void 0||(X==="@@"?X:void 0)!==void 0)this.index++;else if(J!==0)throw new G0(`Invalid Line:
412
- ${this.lines[this.index]}`);if(Y?.trim()){let U=r0(Y.trim());for(let f=J;f<Q.length;f++){let _=Q[f];if(_&&(r0(_)===U||r0(_.trim())===U)){if(J=f+1,r0(_.trim())===U&&r0(_)!==U)this.fuzz++;break}}}let[B,H,G,K]=hq(this.lines,this.index),[F,A,D]=yq(Q,B,J,K);if(F===-1){let U=B.join(`
413
- `);this.addWarning({path:this.currentPath||W,chunkIndex:Z.chunks.length,message:`Could not find matching context (similarity: ${D.toFixed(2)}). Chunk skipped.`,context:U.length>200?`${U.substring(0,200)}...`:U}),this.index=G}else{this.fuzz+=A;for(let U of H)U.origIndex+=F,Z.chunks.push(U);J=F+B.length,this.index=G}}return Z}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new G0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new G0(`Add File Error: File already exists: ${$}`);this.index++;let W=[],Z=[n.END,n.UPDATE,n.DELETE,n.ADD];while(this.hasMoreLines()&&!Z.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index++];if(Q===void 0)break;if(!Q.startsWith("+"))throw new G0(`Invalid Add File line (missing '+'): ${Q}`);W.push(Q.substring(1))}this.patch.actions[$]={type:"add",newFile:W.join(`
414
- `),chunks:[]}}}function aH($,W){let Z=$.length>W.length?$:W,Q=$.length>W.length?W:$;if(Z.length===0)return 1;let J=bq(Q,Z);return(Z.length-J)/Z.length}function bq($,W){let Z=W.length+1,Q=$.length+1,J=Array(Z*Q).fill(0),j=(Y,V)=>J[Y*Q+V]??0,X=(Y,V,B)=>{J[Y*Q+V]=B};for(let Y=0;Y<=W.length;Y++)X(Y,0,Y);for(let Y=0;Y<=$.length;Y++)X(0,Y,Y);for(let Y=1;Y<=W.length;Y++)for(let V=1;V<=$.length;V++)if(W[Y-1]===$[V-1])X(Y,V,j(Y-1,V-1));else X(Y,V,1+Math.min(j(Y-1,V-1),j(Y,V-1),j(Y-1,V)));return j(W.length,$.length)}function yq($,W,Z,Q){if(W.length===0)return[Z,0,1];let J=0,j=(X)=>{let Y=r0(W.join(`
410
+ *** End Patch`;function p3($,W={}){let Z=W.applyPatchTimeoutMs??30000,Q=W.cwd??process.cwd();return R$({name:"apply_patch",description:bq,inputSchema:s1(r4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=E$(mH,J),Y=typeof X==="string"?X:X.input;try{return{query:"apply_patch",result:await n1($({input:Y},Q,j),Z,`apply_patch timed out after ${Z}ms`),success:!0}}catch(V){return{query:"apply_patch",result:"",error:`apply_patch failed: ${f2(V)}`,success:!1}}}})}function r3($,W={}){let Z=W.editorTimeoutMs??30000,Q=W.cwd??process.cwd();return R$({name:"editor",description:"An editor for controlled filesystem edits on the text file at the provided path. Provide `insert_line` to insert `new_text` at a specific line number. Otherwise, the tool replaces `old_text` with `new_text`, or creates the file with `new_text` if file does not exist. Use this tool for making small, precise edits to existing files or creating new files over shell commands. If several edits to different files or non-overlapping regions are already known, emit multiple editor tool calls in the same response instead of serializing them across turns.",inputSchema:s1(p4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=E$(p4,J),Y=X.insert_line==null?"edit":"insert",V=cH(X);if(V)return{query:`${Y}:${X.path}`,result:"",error:V,success:!1};try{let B=await n1($(X,Q,j),Z,`Editor operation timed out after ${Z}ms`);return{query:`${Y}:${X.path}`,result:B,success:!0}}catch(B){let H=f2(B);return{query:`${Y}:${X.path}`,result:"",error:`Editor operation failed: ${H}`,success:!1}}}})}function O2($,W={}){let Z=W.skillsTimeoutMs??15000,Q='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',J=R$({name:"skills",description:Q,inputSchema:s1(i4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(j,X)=>{let Y=E$(i4,j);return n1($(Y.skill,Y.args||void 0,X),Z,`Skills operation timed out after ${Z}ms`)}});return Object.defineProperty(J,"description",{get(){let j=$.configuredSkills?.filter((X)=>!X.disabled).map((X)=>X.name);if(j&&j.length>0)return`${Q} Available skills: ${j.join(", ")}.`;return Q},enumerable:!0,configurable:!0}),J}function i3($){return{name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:s1(n4),retryable:!1,maxRetries:0,execute:async(W,Z)=>{let Q=E$(n4,W);return $(Q.question,Q.options,Z)}}}function n3($,W={}){let Z=W.submitTimeoutMs??15000;return R$({name:"submit_and_exit",description:"Submit the final answer and exit the conversation. For example, submit a summary of the investigation and confirm the issue is resolved. You should only submit once all necessary steps are completed. Make sure to verify your output matches the expected format, data types, and file locations specified. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:s1(a4),lifecycle:{completesRun:!0},timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(Q,J)=>{let j=E$(a4,Q);return n1($(j.summary,j.verified,J),Z,`submit_and_exit timed out after ${Z}ms`)}})}function N$($){let{executors:W,enableReadFiles:Z=!0,enableSearch:Q=!0,enableBash:J=!0,enableWebFetch:j=!0,enableApplyPatch:X=!1,enableEditor:Y=!0,enableSkills:V=!0,enableAskQuestion:B=!0,enableSubmitAndExit:H=!1,...G}=$,K=[];if(Z&&W.readFile)K.push(u3(W.readFile,G));if(Q&&W.search)K.push(d3(W.search,G));if(J&&W.bash)K.push(o4(W.bash,G));if(j&&W.webFetch)K.push(l3(W.webFetch,G));if(Y&&W.editor)K.push(r3(W.editor,G));else if(X&&W.applyPatch)K.push(p3(W.applyPatch,G));if(V&&W.skills)K.push(O2(W.skills,G));let F=H?W.submit:void 0;if(B&&W.askQuestion&&!F)K.push(i3(W.askQuestion));if(F)K.push(n3(F,G));return K}import*as i0 from"node:fs/promises";import*as n0 from"node:path";var a={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","```"],z2;((Q)=>{Q.ADD="add";Q.DELETE="delete";Q.UPDATE="update"})(z2||={});class G0 extends Error{constructor($){super($);this.name="DiffError"}}function r0($){let W={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Z)=>W[Z]??Z).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class a3{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,W){this.lines=$;this.currentFiles=W}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(a.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(a.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(a.UPDATE)){this.parseUpdate($.substring(a.UPDATE.length).trim());return}if($?.startsWith(a.DELETE)){this.parseDelete($.substring(a.DELETE.length).trim());return}if($?.startsWith(a.ADD)){this.parseAdd($.substring(a.ADD.length).trim());return}throw new G0(`Unknown line while parsing: ${$}`)}checkDuplicate($,W){if($ in this.patch.actions)throw new G0(`Duplicate ${W} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let W=this.lines[this.index]?.startsWith(a.MOVE)?(this.lines[this.index++]??"").substring(a.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new G0(`Update File Error: Missing File: ${$}`);let Z=this.currentFiles[$]??"",Q=this.parseUpdateFile(Z,$);Q.movePath=W,this.patch.actions[$]=Q,this.currentPath=void 0}parseUpdateFile($,W){let Z={type:"update",chunks:[]},Q=$.split(`
411
+ `),J=0,j=[a.END,a.UPDATE,a.DELETE,a.ADD,a.END_FILE];while(!j.some((X)=>this.lines[this.index]?.startsWith(X.trim()))){let X=this.lines[this.index],Y=X?.startsWith("@@ ")?X.substring(3):void 0;if(Y!==void 0||(X==="@@"?X:void 0)!==void 0)this.index++;else if(J!==0)throw new G0(`Invalid Line:
412
+ ${this.lines[this.index]}`);if(Y?.trim()){let U=r0(Y.trim());for(let f=J;f<Q.length;f++){let _=Q[f];if(_&&(r0(_)===U||r0(_.trim())===U)){if(J=f+1,r0(_.trim())===U&&r0(_)!==U)this.fuzz++;break}}}let[B,H,G,K]=kq(this.lines,this.index),[F,A,D]=hq(Q,B,J,K);if(F===-1){let U=B.join(`
413
+ `);this.addWarning({path:this.currentPath||W,chunkIndex:Z.chunks.length,message:`Could not find matching context (similarity: ${D.toFixed(2)}). Chunk skipped.`,context:U.length>200?`${U.substring(0,200)}...`:U}),this.index=G}else{this.fuzz+=A;for(let U of H)U.origIndex+=F,Z.chunks.push(U);J=F+B.length,this.index=G}}return Z}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new G0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new G0(`Add File Error: File already exists: ${$}`);this.index++;let W=[],Z=[a.END,a.UPDATE,a.DELETE,a.ADD];while(this.hasMoreLines()&&!Z.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index++];if(Q===void 0)break;if(!Q.startsWith("+"))throw new G0(`Invalid Add File line (missing '+'): ${Q}`);W.push(Q.substring(1))}this.patch.actions[$]={type:"add",newFile:W.join(`
414
+ `),chunks:[]}}}function oH($,W){let Z=$.length>W.length?$:W,Q=$.length>W.length?W:$;if(Z.length===0)return 1;let J=yq(Q,Z);return(Z.length-J)/Z.length}function yq($,W){let Z=W.length+1,Q=$.length+1,J=Array(Z*Q).fill(0),j=(Y,V)=>J[Y*Q+V]??0,X=(Y,V,B)=>{J[Y*Q+V]=B};for(let Y=0;Y<=W.length;Y++)X(Y,0,Y);for(let Y=0;Y<=$.length;Y++)X(0,Y,Y);for(let Y=1;Y<=W.length;Y++)for(let V=1;V<=$.length;V++)if(W[Y-1]===$[V-1])X(Y,V,j(Y-1,V-1));else X(Y,V,1+Math.min(j(Y-1,V-1),j(Y,V-1),j(Y-1,V)));return j(W.length,$.length)}function hq($,W,Z,Q){if(W.length===0)return[Z,0,1];let J=0,j=(X)=>{let Y=r0(W.join(`
415
415
  `));for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).join(`
416
- `));if(H===Y)return[B,0,1];let G=aH(H,Y);if(G>J)J=G}for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).map((K)=>K.trimEnd()).join(`
416
+ `));if(H===Y)return[B,0,1];let G=oH(H,Y);if(G>J)J=G}for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).map((K)=>K.trimEnd()).join(`
417
417
  `)),G=r0(W.map((K)=>K.trimEnd()).join(`
418
418
  `));if(H===G)return[B,1,1]}for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).map((K)=>K.trim()).join(`
419
419
  `)),G=r0(W.map((K)=>K.trim()).join(`
420
420
  `));if(H===G)return[B,100,1]}let V=0.66;for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).join(`
421
- `)),G=aH(H,Y);if(G>=V)return[B,1000,G];if(G>J)J=G}return[-1,0,J]};if(Q){let[X,Y,V]=j($.length-W.length);if(X!==-1)return[X,Y,V];return[X,Y,V]=j(Z),[X,Y+1e4,V]}return j(Z)}function hq($,W){let Z=W,Q=[],J=[],j=[],X=[],Y="keep",V=["@@",n.END,n.UPDATE,n.DELETE,n.ADD,n.END_FILE];while(Z<$.length){let B=$[Z];if(!B||V.some((K)=>B.startsWith(K.trim())))break;if(B==="***")break;if(B.startsWith("***"))throw new G0(`Invalid line: ${B}`);Z++;let H=Y,G=B;if(G[0]==="+")Y="add";else if(G[0]==="-")Y="delete";else if(G[0]===" ")Y="keep";else Y="keep",G=` ${G}`;if(G=G.slice(1),Y==="keep"&&H!==Y){if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});J=[],j=[]}if(Y==="delete")J.push(G),Q.push(G);else if(Y==="add")j.push(G);else Q.push(G)}if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});if(Z<$.length&&$[Z]===n.END_FILE)return Z++,[Q,X,Z,!0];return[Q,X,Z,!1]}function a3($,W,Z){let Q=n0.isAbsolute(W),J=Q?n0.normalize(W):n0.resolve($,W);if(!Z||Q)return J;let j=n0.relative($,J);if(j.startsWith("..")||n0.isAbsolute(j))throw new G0(`Path must stay within cwd: ${W}`);return J}function kq($){return $.split(`
422
- `).map((W)=>W.replace(/\r$/,""))}function sH($){if($.trim()==="")return!1;return oH.some((W)=>$.startsWith(W))}function Iq($){let W=0,Z=$.length;while(W<Z&&sH($[W]??""))W++;while(Z>W&&sH($[Z-1]??""))Z--;return $.slice(W,Z)}function xq($){let W=kq($),Z=W.findIndex((X)=>X.startsWith(n.BEGIN)),Q=-1;for(let X=W.length-1;X>=0;X--)if(W[X]?.startsWith(n.END)){Q=X;break}if(Z!==-1||Q!==-1){if(Z===-1||Q===-1||Q<Z)throw new G0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:W.slice(Z,Q+1)}}let J=Iq(W);while(J.length>0&&J[0]==="")J.shift();while(J.length>0&&J[J.length-1]==="")J.pop();return{lines:[n.BEGIN,...J,n.END]}}function gq($,W){let Z=new Set;for(let Q of $)for(let J of W)if(Q.startsWith(J)){Z.add(Q.substring(J.length).trim());break}return[...Z]}function mq($,W,Z){if(W.length===0)return $;let Q=$.split(`
421
+ `)),G=oH(H,Y);if(G>=V)return[B,1000,G];if(G>J)J=G}return[-1,0,J]};if(Q){let[X,Y,V]=j($.length-W.length);if(X!==-1)return[X,Y,V];return[X,Y,V]=j(Z),[X,Y+1e4,V]}return j(Z)}function kq($,W){let Z=W,Q=[],J=[],j=[],X=[],Y="keep",V=["@@",a.END,a.UPDATE,a.DELETE,a.ADD,a.END_FILE];while(Z<$.length){let B=$[Z];if(!B||V.some((K)=>B.startsWith(K.trim())))break;if(B==="***")break;if(B.startsWith("***"))throw new G0(`Invalid line: ${B}`);Z++;let H=Y,G=B;if(G[0]==="+")Y="add";else if(G[0]==="-")Y="delete";else if(G[0]===" ")Y="keep";else Y="keep",G=` ${G}`;if(G=G.slice(1),Y==="keep"&&H!==Y){if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});J=[],j=[]}if(Y==="delete")J.push(G),Q.push(G);else if(Y==="add")j.push(G);else Q.push(G)}if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});if(Z<$.length&&$[Z]===a.END_FILE)return Z++,[Q,X,Z,!0];return[Q,X,Z,!1]}function o3($,W,Z){let Q=n0.isAbsolute(W),J=Q?n0.normalize(W):n0.resolve($,W);if(!Z||Q)return J;let j=n0.relative($,J);if(j.startsWith("..")||n0.isAbsolute(j))throw new G0(`Path must stay within cwd: ${W}`);return J}function Iq($){return $.split(`
422
+ `).map((W)=>W.replace(/\r$/,""))}function tH($){if($.trim()==="")return!1;return sH.some((W)=>$.startsWith(W))}function xq($){let W=0,Z=$.length;while(W<Z&&tH($[W]??""))W++;while(Z>W&&tH($[Z-1]??""))Z--;return $.slice(W,Z)}function gq($){let W=Iq($),Z=W.findIndex((X)=>X.startsWith(a.BEGIN)),Q=-1;for(let X=W.length-1;X>=0;X--)if(W[X]?.startsWith(a.END)){Q=X;break}if(Z!==-1||Q!==-1){if(Z===-1||Q===-1||Q<Z)throw new G0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:W.slice(Z,Q+1)}}let J=xq(W);while(J.length>0&&J[0]==="")J.shift();while(J.length>0&&J[J.length-1]==="")J.pop();return{lines:[a.BEGIN,...J,a.END]}}function mq($,W){let Z=new Set;for(let Q of $)for(let J of W)if(Q.startsWith(J)){Z.add(Q.substring(J.length).trim());break}return[...Z]}function vq($,W,Z){if(W.length===0)return $;let Q=$.split(`
423
423
  `),J=[],j=0;for(let X of W){if(X.origIndex>Q.length)throw new G0(`${Z}: chunk.origIndex ${X.origIndex} > lines.length ${Q.length}`);if(j>X.origIndex)throw new G0(`${Z}: currentIndex ${j} > chunk.origIndex ${X.origIndex}`);J.push(...Q.slice(j,X.origIndex)),J.push(...X.insLines),j=X.origIndex+X.delLines.length}return J.push(...Q.slice(j)),J.join(`
424
- `)}async function vq($,W,Z,Q){let J=gq($,[n.UPDATE,n.DELETE]),j={};for(let X of J){let Y=a3(W,X,Q),V;try{V=await i0.readFile(Y,Z)}catch{throw new G0(`File not found: ${X}`)}j[X]=V.replace(/\r\n/g,`
425
- `)}return j}function cq($,W){let Z={};for(let[Q,J]of Object.entries($.actions))switch(J.type){case"delete":Z[Q]={type:"delete",oldContent:W[Q]};break;case"add":if(J.newFile===void 0)throw new G0("ADD action without file content");Z[Q]={type:"add",newContent:J.newFile};break;case"update":Z[Q]={type:"update",oldContent:W[Q],newContent:mq(W[Q]??"",J.chunks,Q),movePath:J.movePath};break}return Z}function uq($){let W=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Z of $){let Q=Z.chunkIndex===void 0?"unknown":String(Z.chunkIndex+1);if(W.push(`${Z.path}: hunk ${Q}: ${Z.message}`),Z.context)W.push(`Context:
424
+ `)}async function cq($,W,Z,Q){let J=mq($,[a.UPDATE,a.DELETE]),j={};for(let X of J){let Y=o3(W,X,Q),V;try{V=await i0.readFile(Y,Z)}catch{throw new G0(`File not found: ${X}`)}j[X]=V.replace(/\r\n/g,`
425
+ `)}return j}function uq($,W){let Z={};for(let[Q,J]of Object.entries($.actions))switch(J.type){case"delete":Z[Q]={type:"delete",oldContent:W[Q]};break;case"add":if(J.newFile===void 0)throw new G0("ADD action without file content");Z[Q]={type:"add",newContent:J.newFile};break;case"update":Z[Q]={type:"update",oldContent:W[Q],newContent:vq(W[Q]??"",J.chunks,Q),movePath:J.movePath};break}return Z}function dq($){let W=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Z of $){let Q=Z.chunkIndex===void 0?"unknown":String(Z.chunkIndex+1);if(W.push(`${Z.path}: hunk ${Q}: ${Z.message}`),Z.context)W.push(`Context:
426
426
  ${Z.context}`)}return W.join(`
427
- `)}async function dq($,W,Z,Q){let J=[];for(let[j,X]of Object.entries($)){let Y=a3(W,j,Q);switch(X.type){case"delete":await i0.rm(Y,{force:!0}),J.push(`${j}: [deleted]`);break;case"add":if(X.newContent===void 0)throw new G0(`Cannot create ${j} with no content`);await i0.mkdir(n0.dirname(Y),{recursive:!0}),await i0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break;case"update":{if(X.newContent===void 0)throw new G0(`UPDATE change for ${j} has no new content`);if(X.movePath){let V=a3(W,X.movePath,Q);await i0.mkdir(n0.dirname(V),{recursive:!0}),await i0.writeFile(V,X.newContent,{encoding:Z}),await i0.rm(Y,{force:!0}),J.push(`${j} -> ${X.movePath}`)}else await i0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break}}}return J}async function c8($,W,Z={}){let{encoding:Q="utf-8",restrictToCwd:J=!0}=Z,j=xq($),X=await vq(j.lines,W,Q,J),Y=new n3(j.lines,X),{patch:V,fuzz:B}=Y.parse();if(V.warnings&&V.warnings.length>0)throw new G0(uq(V.warnings));return{changes:cq(V,X),fuzz:B}}function q2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0}=$;return async(Q,J,j)=>{let{changes:X,fuzz:Y}=await c8(Q.input,J,{encoding:W,restrictToCwd:Z}),V=await dq(X,J,W,Z),B=["Successfully applied patch to the following files:"];for(let H of V)B.push(H);if(Y>0)B.push(`Note: Patch applied with fuzz factor ${Y}`);return B.join(`
428
- `)}}import*as F1 from"node:fs/promises";import*as K1 from"node:path";function lq($,W,Z){let Q=K1.isAbsolute(W),J=Q?K1.normalize(W):K1.resolve($,W);if(!Z)return J;if(Q)return J;let j=K1.relative($,J);if(j.startsWith("..")||K1.isAbsolute(j))throw Error(`Path must stay within cwd: ${W}`);return J}function pq($,W){if(W.length===0)return 0;return $.split(W).length-1}function rq($,W,Z){let Q=$.split(`
427
+ `)}async function lq($,W,Z,Q){let J=[];for(let[j,X]of Object.entries($)){let Y=o3(W,j,Q);switch(X.type){case"delete":await i0.rm(Y,{force:!0}),J.push(`${j}: [deleted]`);break;case"add":if(X.newContent===void 0)throw new G0(`Cannot create ${j} with no content`);await i0.mkdir(n0.dirname(Y),{recursive:!0}),await i0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break;case"update":{if(X.newContent===void 0)throw new G0(`UPDATE change for ${j} has no new content`);if(X.movePath){let V=o3(W,X.movePath,Q);await i0.mkdir(n0.dirname(V),{recursive:!0}),await i0.writeFile(V,X.newContent,{encoding:Z}),await i0.rm(Y,{force:!0}),J.push(`${j} -> ${X.movePath}`)}else await i0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break}}}return J}async function c8($,W,Z={}){let{encoding:Q="utf-8",restrictToCwd:J=!0}=Z,j=gq($),X=await cq(j.lines,W,Q,J),Y=new a3(j.lines,X),{patch:V,fuzz:B}=Y.parse();if(V.warnings&&V.warnings.length>0)throw new G0(dq(V.warnings));return{changes:uq(V,X),fuzz:B}}function q2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0}=$;return async(Q,J,j)=>{let{changes:X,fuzz:Y}=await c8(Q.input,J,{encoding:W,restrictToCwd:Z}),V=await lq(X,J,W,Z),B=["Successfully applied patch to the following files:"];for(let H of V)B.push(H);if(Y>0)B.push(`Note: Patch applied with fuzz factor ${Y}`);return B.join(`
428
+ `)}}import*as F1 from"node:fs/promises";import*as K1 from"node:path";function pq($,W,Z){let Q=K1.isAbsolute(W),J=Q?K1.normalize(W):K1.resolve($,W);if(!Z)return J;if(Q)return J;let j=K1.relative($,J);if(j.startsWith("..")||K1.isAbsolute(j))throw Error(`Path must stay within cwd: ${W}`);return J}function rq($,W){if(W.length===0)return 0;return $.split(W).length-1}function iq($,W,Z){let Q=$.split(`
429
429
  `),J=W.split(`
430
430
  `),j=0;while(j<Q.length&&j<J.length&&Q[j]===J[j])j++;let X=Q.length,Y=J.length;while(X>j&&Y>j&&Q[X-1]===J[Y-1])X--,Y--;let V=X-j,B=Y-j,H=V,G=B;if(V+B>Z)H=Math.min(V,Math.max(Math.ceil(Z/2),Z-B)),G=Math.min(B,Z-H);let K=["```diff"];for(let D=j;D<j+H;D++)K.push(`-${D+1}: ${Q[D]}`);for(let D=j;D<j+G;D++)K.push(`+${D+1}: ${J[D]}`);let F=V-H,A=B-G;if(F>0||A>0)K.push(`... diff truncated (${F} more removed, ${A} more added lines) ...`);return K.push("```"),K.join(`
431
- `)}async function iq($,W,Z){return await F1.mkdir(K1.dirname($),{recursive:!0}),await F1.writeFile($,W,{encoding:Z}),`File created successfully at: ${$}`}async function nq($){try{return await F1.access($),!0}catch{return!1}}async function aq($,W,Z,Q,J){let j=await F1.readFile($,Q),X=pq(j,W);if(X===0)throw Error(`No replacement performed: text not found in ${$}.`);if(X>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let Y=j.replace(W,Z??"");await F1.writeFile($,Y,{encoding:Q});let V=rq(j,Y,J);return`Edited ${$}
432
- ${V}`}async function oq($,W,Z,Q){let j=(await F1.readFile($,Q)).split(`
431
+ `)}async function nq($,W,Z){return await F1.mkdir(K1.dirname($),{recursive:!0}),await F1.writeFile($,W,{encoding:Z}),`File created successfully at: ${$}`}async function aq($){try{return await F1.access($),!0}catch{return!1}}async function oq($,W,Z,Q,J){let j=await F1.readFile($,Q),X=rq(j,W);if(X===0)throw Error(`No replacement performed: text not found in ${$}.`);if(X>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let Y=j.replace(W,Z??"");await F1.writeFile($,Y,{encoding:Q});let V=iq(j,Y,J);return`Edited ${$}
432
+ ${V}`}async function sq($,W,Z,Q){let j=(await F1.readFile($,Q)).split(`
433
433
  `),X=j.length+1;if(W<1||W>X)throw Error(`Invalid insert_line: ${W}. insert_line must be a positive one-based boundary line in the range 1-${X}. Use ${X} to append at EOF.`);let Y=W-1;return j.splice(Y,0,...Z.split(`
434
434
  `)),await F1.writeFile($,j.join(`
435
- `),{encoding:Q}),`Inserted content at line ${W} in ${$}.`}function M2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0,maxDiffLines:Q=200}=$;return async(J,j,X)=>{let Y=lq(j,J.path,Z);if(J.insert_line!=null)return oq(Y,J.insert_line,J.new_text,W);if(!await nq(Y))return iq(Y,J.new_text,W);if(J.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return aq(Y,J.old_text,J.new_text,W,Q)}}import{createReadStream as sq}from"node:fs";import*as eW from"node:fs/promises";import*as w$ from"node:path";import{createInterface as tq}from"node:readline";import{resolveExistingFilePath as eq}from"@cline/shared/storage";var $M=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),WM={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},tH=1e8,ZM=50000;function eH($){let{reason:W}=$;if(W instanceof Error)return W;if(W!==void 0)return Error(String(W));return Error("File read was aborted")}async function QM($,W,Z,Q,J,j){if(j?.aborted)throw eH(j);let X=Math.max(Q??1,1),Y=J??Number.POSITIVE_INFINITY,V=Number.isFinite(Y),B=V?Y:X+ZM-1,H=[],G=0,K=0,F=!1,A=!1,D=Number.isFinite(Y)?Math.min(Y,X+m8-1):X+m8-1,U=Z?String(D).length+3:0,f=sq($,{encoding:W}),_=tq({input:f,crlfDelay:Number.POSITIVE_INFINITY}),R=j?()=>f.destroy(eH(j)):void 0;if(j&&R)j.addEventListener("abort",R,{once:!0});try{for await(let p of _){if(K+=1,K>Y){K=Y;break}if(!V&&F&&K>=B){A=!0;break}if(K<X||F)continue;if(H.length>=m8){F=!0;continue}let x=p;if(x.length>v3)x=`${x.slice(0,v3)} [line truncated]`;let P=G+x.length+U+1;if(P>tW&&H.length>0){F=!0;continue}H.push({lineNumber:K,text:x}),G=P}}finally{if(j&&R)j.removeEventListener("abort",R);_.close(),f.destroy()}let O=String(H[H.length-1]?.lineNumber??K).length,T=H.map(({lineNumber:p,text:x})=>Z?`${String(p).padStart(O," ")} | ${x}`:x).join(`
435
+ `),{encoding:Q}),`Inserted content at line ${W} in ${$}.`}function M2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0,maxDiffLines:Q=200}=$;return async(J,j,X)=>{let Y=pq(j,J.path,Z);if(J.insert_line!=null)return sq(Y,J.insert_line,J.new_text,W);if(!await aq(Y))return nq(Y,J.new_text,W);if(J.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return oq(Y,J.old_text,J.new_text,W,Q)}}import{createReadStream as tq}from"node:fs";import*as $Z from"node:fs/promises";import*as w$ from"node:path";import{createInterface as eq}from"node:readline";import{resolveExistingFilePath as $M}from"@cline/shared/storage";var WM=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),ZM={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},eH=1e8,QM=50000;function $G($){let{reason:W}=$;if(W instanceof Error)return W;if(W!==void 0)return Error(String(W));return Error("File read was aborted")}async function JM($,W,Z,Q,J,j){if(j?.aborted)throw $G(j);let X=Math.max(Q??1,1),Y=J??Number.POSITIVE_INFINITY,V=Number.isFinite(Y),B=V?Y:X+QM-1,H=[],G=0,K=0,F=!1,A=!1,D=Number.isFinite(Y)?Math.min(Y,X+m8-1):X+m8-1,U=Z?String(D).length+3:0,f=tq($,{encoding:W}),_=eq({input:f,crlfDelay:Number.POSITIVE_INFINITY}),R=j?()=>f.destroy($G(j)):void 0;if(j&&R)j.addEventListener("abort",R,{once:!0});try{for await(let p of _){if(K+=1,K>Y){K=Y;break}if(!V&&F&&K>=B){A=!0;break}if(K<X||F)continue;if(H.length>=m8){F=!0;continue}let x=p;if(x.length>c3)x=`${x.slice(0,c3)} [line truncated]`;let P=G+x.length+U+1;if(P>eW&&H.length>0){F=!0;continue}H.push({lineNumber:K,text:x}),G=P}}finally{if(j&&R)j.removeEventListener("abort",R);_.close(),f.destroy()}let O=String(H[H.length-1]?.lineNumber??K).length,T=H.map(({lineNumber:p,text:x})=>Z?`${String(p).padStart(O," ")} | ${x}`:x).join(`
436
436
  `),L=H[H.length-1]?.lineNumber;if(L===void 0)return T;let C=Math.min(Y,K);if(L>=C)return T;let E=A?`${K}+ lines`:C;return`${T}
437
437
 
438
- [Showing lines ${X}-${L} of ${E}. Use start_line/end_line to read other sections.]`}function s4($={}){let{maxFileSizeBytes:W,encoding:Z,includeLineNumbers:Q}={...WM,...$};return async(J,j)=>{let{path:X,start_line:Y,end_line:V}=J,B=w$.isAbsolute(X)?w$.normalize(X):w$.resolve(process.cwd(),X),H=eq(B)??B,G=w$.extname(H).toLowerCase(),K=$M.get(G),F=await eW.stat(H);if(!F.isFile())throw Error(`Path is not a file: ${H}`);if(K){if(F.size>W)throw Error(`Image file too large: ${F.size} bytes (max: ${W} bytes).`);if(j.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let A=await eW.readFile(H);return[{type:"text",text:"Successfully read image"},{type:"image",data:A.toString("base64"),mediaType:K}]}if(F.size>tH)throw Error(`Text file too large to stream safely: ${F.size} bytes (max: ${tH} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return QM(H,Z,Q,Y,V,j.signal)}}import{spawn as YG}from"node:child_process";import*as VG from"node:fs/promises";import*as ZZ from"node:path";var jG={};w(jG,{prewarmFileIndex:()=>WZ,getFileIndex:()=>t1,enrichPromptWithMentions:()=>d8});import{spawn as JM}from"node:child_process";import{readdir as jM}from"node:fs/promises";import s3 from"node:path";import{isMainThread as ZG,parentPort as $G,Worker as XM}from"node:worker_threads";var YM=15000,VM=600000,BM=1000,HM=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function WG($){let W=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return W==="EACCES"||W==="EPERM"||W==="ENOENT"}var u8=new Map;function GM(){if(!ZG)return!1;return!0}function KM($){if(u8.size<=1)return;for(let[W,Z]of u8.entries()){if(Z.pending)continue;if($-Z.lastAccessedAt>VM)u8.delete(W)}}function FM($,W){return s3.relative($,W).split(s3.sep).join("/")}async function AM($){let Z=(await new Promise((Q,J)=>{let j=JM("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),X="",Y="";j.stdout.on("data",(V)=>{X+=V.toString()}),j.stderr.on("data",(V)=>{Y+=V.toString()}),j.on("error",J),j.on("close",(V)=>{if(V===0){Q(X);return}J(Error(Y||`rg exited with code ${V}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(Z)}async function QG($,W,Z){let Q;try{Q=await jM(W,{withFileTypes:!0})}catch(J){if(WG(J))return;throw J}for(let J of Q){let j=s3.join(W,J.name);if(J.isDirectory()){if(HM.has(J.name))continue;try{await QG($,j,Z)}catch(X){if(WG(X))continue;throw X}continue}if(J.isFile())Z.add(FM($,j))}}async function UM($){let W=new Set;return await QG($,$,W),W}async function $Z($){try{return await AM($)}catch{return UM($)}}function DM(){if(ZG||!$G)return;let $=$G;$.on("message",(W)=>{if(W.type!=="index")return;$Z(W.cwd).then((Z)=>{let Q={type:"indexResult",requestId:W.requestId,files:Array.from(Z)};$.postMessage(Q)}).catch((Z)=>{let Q={type:"indexResult",requestId:W.requestId,error:Z instanceof Error?Z.message:"Failed to build file index"};$.postMessage(Q)})})}class JG{worker=new XM(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let W=this.pending.get($.requestId);if(!W)return;if(this.pending.delete($.requestId),$.error){W.reject(Error($.error));return}W.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let W=++this.nextRequestId,Z=new Promise((J,j)=>{let X=setTimeout(()=>{this.pending.delete(W),J(null)},BM);X.unref(),this.pending.set(W,{resolve:(Y)=>{clearTimeout(X),J(Y)},reject:(Y)=>{clearTimeout(X),j(Y)}})}),Q={type:"index",requestId:W,cwd:$};return this.worker.postMessage(Q),Z}flushPending($){for(let[W,Z]of this.pending.entries())Z.reject($),this.pending.delete(W)}}DM();var o3;function _M(){if(!GM())return null;if(o3===void 0)o3=new JG;return o3}async function fM($){let W=_M();if(!W)return $Z($);try{let Z=await W.requestIndex($);if(Z===null)return $Z($);return new Set(Z)}catch{return $Z($)}}async function t1($,W={}){let Z=W.ttlMs??YM,Q=Date.now();KM(Q);let J=u8.get($);if(J&&Z>0&&Q-J.lastBuiltAt<=Z&&J.files.size>0)return J.lastAccessedAt=Q,J.files;if(J?.pending)return J.lastAccessedAt=Q,J.pending;let j=fM($).then((X)=>{return u8.set($,{files:X,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),X});return u8.set($,{files:J?.files??new Set,lastBuiltAt:J?.lastBuiltAt??0,lastAccessedAt:Q,pending:j}),j}async function WZ($,W={}){await t1($,{...W,ttlMs:0})}import{stat as LM}from"node:fs/promises";import R2 from"node:path";var TM=/[),.:;!?`'"]+$/,OM=/^[(`'"]+/;function zM($){let W=$.matchAll(/(^|[\s])@([^\s]+)/g),Z=[];for(let Q of W){let J=(Q[2]??"").trim();if(J.length===0)continue;let j=J.replace(OM,"").replace(TM,"");if(j.length===0||j.includes("@"))continue;Z.push(j)}return Array.from(new Set(Z))}function qM($,W){let Z=$.replace(/\\/g,"/"),Q=R2.isAbsolute(Z)?R2.resolve(Z):R2.resolve(W,Z),J=R2.relative(W,Q);if(J.startsWith("..")||R2.isAbsolute(J))return;return J.split(R2.sep).join("/")}async function d8($,W,Z={}){let Q=zM($);if(Q.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:J,maxFileBytes:j,maxTotalBytes:X}=Z,Y=await t1(W,{ttlMs:Z.ttlMs}),V=[],B=[],H=[],G=0;for(let K of Q){if(J&&H.length>=J){B.push(K);continue}let F=qM(K,W);if(!F||!Y.has(F)){B.push(K);continue}if(!j||!X){V.push(F);continue}let A=R2.join(W,F);try{if(!(await LM(A)).isFile()){B.push(K);continue}let U=G+j;if(U>X){B.push(K);continue}G=U,V.push(F)}catch{B.push(K)}}return{prompt:$,mentions:Q,matchedFiles:V,ignoredMentions:B}}var MM=["ts","tsx","js","jsx","mjs","cjs","json","md","mdx","txt","yaml","yml","toml","py","rb","go","rs","java","kt","swift","c","cpp","h","hpp","css","scss","less","html","vue","svelte","sql","sh","bash","zsh","fish","ps1","env","gitignore","dockerignore","editorconfig"],RM=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],E2=null;function EM(){if(E2!==null)return Promise.resolve(E2);return new Promise(($)=>{let W=YG("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});W.on("close",(Z)=>{E2=Z===0,$(E2)}),W.on("error",()=>{E2=!1,$(!1)}),setTimeout(()=>{if(!W.killed)W.kill("SIGTERM");if(E2===null)E2=!1,$(!1)},1000)})}function NM($,W,Z,Q,J=5000,j){return new Promise((X)=>{let Y=YG("rg",["--json",`--context=${Q}`,"--max-count=1","-i",$],{cwd:W,stdio:["ignore","pipe","pipe"],windowsHide:!0}),V="",B=!1,H=()=>{if(!Y.killed)Y.kill("SIGTERM")},G=setTimeout(()=>{if(!B)B=!0,H(),X(null)},J),K=(F)=>{if(!B)B=!0,clearTimeout(G),H(),X(F)};if(j?.aborted){H(),X(null);return}j?.addEventListener("abort",()=>{K(null)}),Y.stdout.on("data",(F)=>{V+=F.toString()}),Y.stderr.on("data",()=>{}),Y.on("close",(F)=>{if(F===0||F===1){try{let A=[],D=V.split(`
439
- `).filter((U)=>U.trim());for(let U of D){if(A.length>=Z)break;let f=JSON.parse(U);if(f.type==="match"){let _=f.data,R=[];if(f.data.submatches&&f.data.submatches.length>0){let O=f.data.submatches[0];A.push({file:_.path.text,line:_.line_number,column:(O?.start??0)+1,match:O?.match?.text??"",context:R})}}else if(f.type==="context"&&A.length>0){let _=A[A.length-1],R=f.data.line_number===_.line?">":" ";_.context.push(`${R} ${f.data.line_number}: ${f.data.lines?.text??f.data.line?.text??""}`)}}K(A.length>0?A:null)}catch{K(null)}return}K(null)}),Y.on("error",()=>{K(null)})})}function wM($,W,Z,Q){let J=$.split("/"),j=J[J.length-1]??"";if(J.length-1>Q)return!1;for(let V=0;V<J.length-1;V++)if(W.has(J[V]??""))return!1;let Y=ZZ.posix.extname(j).slice(1).toLowerCase();return Z.has(Y)||!Y&&!j.startsWith(".")}function t4($={}){let{includeExtensions:W=MM,excludeDirs:Z=RM,maxResults:Q=100,contextLines:J=2,maxDepth:j=20}=$,X=new Set(Z),Y=new Set(W.map((V)=>V.toLowerCase()));return async(V,B,H)=>{if(H.signal?.aborted)throw Error("Search operation aborted");let G=await EM(),K=null;if(G)K=await NM(V,B,Q,J,5000,H.signal);if(K){let _=[`Found ${K.length} result${K.length===1?"":"s"} for pattern: ${V}`,""];for(let R of K)_.push(`${R.file}:${R.line}:${R.column}`),_.push(...R.context),_.push("");if(K.length>=Q)_.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return XG(_.join(`
440
- `))}let F;try{F=new RegExp(V,"gim")}catch(_){throw Error(`Invalid regex pattern: ${V}. ${_ instanceof Error?_.message:""}`)}let A=[],D=0,U=await t1(B);for(let _ of U){if(H.signal?.aborted)throw Error("Search operation aborted");if(!wM(_,X,Y,j))continue;if(A.length>=Q)break;D++;let R=ZZ.join(B,_);try{let T=(await VG.readFile(R,"utf-8")).split(`
438
+ [Showing lines ${X}-${L} of ${E}. Use start_line/end_line to read other sections.]`}function s4($={}){let{maxFileSizeBytes:W,encoding:Z,includeLineNumbers:Q}={...ZM,...$};return async(J,j)=>{let{path:X,start_line:Y,end_line:V}=J,B=w$.isAbsolute(X)?w$.normalize(X):w$.resolve(process.cwd(),X),H=$M(B)??B,G=w$.extname(H).toLowerCase(),K=WM.get(G),F=await $Z.stat(H);if(!F.isFile())throw Error(`Path is not a file: ${H}`);if(K){if(F.size>W)throw Error(`Image file too large: ${F.size} bytes (max: ${W} bytes).`);if(j.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let A=await $Z.readFile(H);return[{type:"text",text:"Successfully read image"},{type:"image",data:A.toString("base64"),mediaType:K}]}if(F.size>eH)throw Error(`Text file too large to stream safely: ${F.size} bytes (max: ${eH} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return JM(H,Z,Q,Y,V,j.signal)}}import{spawn as VG}from"node:child_process";import*as BG from"node:fs/promises";import*as QZ from"node:path";var XG={};w(XG,{prewarmFileIndex:()=>ZZ,getFileIndex:()=>t1,enrichPromptWithMentions:()=>d8});import{spawn as jM}from"node:child_process";import{readdir as XM}from"node:fs/promises";import t3 from"node:path";import{isMainThread as QG,parentPort as WG,Worker as YM}from"node:worker_threads";var VM=15000,BM=600000,HM=1000,GM=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function ZG($){let W=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return W==="EACCES"||W==="EPERM"||W==="ENOENT"}var u8=new Map;function KM(){if(!QG)return!1;return!0}function FM($){if(u8.size<=1)return;for(let[W,Z]of u8.entries()){if(Z.pending)continue;if($-Z.lastAccessedAt>BM)u8.delete(W)}}function AM($,W){return t3.relative($,W).split(t3.sep).join("/")}async function UM($){let Z=(await new Promise((Q,J)=>{let j=jM("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),X="",Y="";j.stdout.on("data",(V)=>{X+=V.toString()}),j.stderr.on("data",(V)=>{Y+=V.toString()}),j.on("error",J),j.on("close",(V)=>{if(V===0){Q(X);return}J(Error(Y||`rg exited with code ${V}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(Z)}async function JG($,W,Z){let Q;try{Q=await XM(W,{withFileTypes:!0})}catch(J){if(ZG(J))return;throw J}for(let J of Q){let j=t3.join(W,J.name);if(J.isDirectory()){if(GM.has(J.name))continue;try{await JG($,j,Z)}catch(X){if(ZG(X))continue;throw X}continue}if(J.isFile())Z.add(AM($,j))}}async function DM($){let W=new Set;return await JG($,$,W),W}async function WZ($){try{return await UM($)}catch{return DM($)}}function _M(){if(QG||!WG)return;let $=WG;$.on("message",(W)=>{if(W.type!=="index")return;WZ(W.cwd).then((Z)=>{let Q={type:"indexResult",requestId:W.requestId,files:Array.from(Z)};$.postMessage(Q)}).catch((Z)=>{let Q={type:"indexResult",requestId:W.requestId,error:Z instanceof Error?Z.message:"Failed to build file index"};$.postMessage(Q)})})}class jG{worker=new YM(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let W=this.pending.get($.requestId);if(!W)return;if(this.pending.delete($.requestId),$.error){W.reject(Error($.error));return}W.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let W=++this.nextRequestId,Z=new Promise((J,j)=>{let X=setTimeout(()=>{this.pending.delete(W),J(null)},HM);X.unref(),this.pending.set(W,{resolve:(Y)=>{clearTimeout(X),J(Y)},reject:(Y)=>{clearTimeout(X),j(Y)}})}),Q={type:"index",requestId:W,cwd:$};return this.worker.postMessage(Q),Z}flushPending($){for(let[W,Z]of this.pending.entries())Z.reject($),this.pending.delete(W)}}_M();var s3;function fM(){if(!KM())return null;if(s3===void 0)s3=new jG;return s3}async function LM($){let W=fM();if(!W)return WZ($);try{let Z=await W.requestIndex($);if(Z===null)return WZ($);return new Set(Z)}catch{return WZ($)}}async function t1($,W={}){let Z=W.ttlMs??VM,Q=Date.now();FM(Q);let J=u8.get($);if(J&&Z>0&&Q-J.lastBuiltAt<=Z&&J.files.size>0)return J.lastAccessedAt=Q,J.files;if(J?.pending)return J.lastAccessedAt=Q,J.pending;let j=LM($).then((X)=>{return u8.set($,{files:X,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),X});return u8.set($,{files:J?.files??new Set,lastBuiltAt:J?.lastBuiltAt??0,lastAccessedAt:Q,pending:j}),j}async function ZZ($,W={}){await t1($,{...W,ttlMs:0})}import{stat as TM}from"node:fs/promises";import R2 from"node:path";var OM=/[),.:;!?`'"]+$/,zM=/^[(`'"]+/;function qM($){let W=$.matchAll(/(^|[\s])@([^\s]+)/g),Z=[];for(let Q of W){let J=(Q[2]??"").trim();if(J.length===0)continue;let j=J.replace(zM,"").replace(OM,"");if(j.length===0||j.includes("@"))continue;Z.push(j)}return Array.from(new Set(Z))}function MM($,W){let Z=$.replace(/\\/g,"/"),Q=R2.isAbsolute(Z)?R2.resolve(Z):R2.resolve(W,Z),J=R2.relative(W,Q);if(J.startsWith("..")||R2.isAbsolute(J))return;return J.split(R2.sep).join("/")}async function d8($,W,Z={}){let Q=qM($);if(Q.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:J,maxFileBytes:j,maxTotalBytes:X}=Z,Y=await t1(W,{ttlMs:Z.ttlMs}),V=[],B=[],H=[],G=0;for(let K of Q){if(J&&H.length>=J){B.push(K);continue}let F=MM(K,W);if(!F||!Y.has(F)){B.push(K);continue}if(!j||!X){V.push(F);continue}let A=R2.join(W,F);try{if(!(await TM(A)).isFile()){B.push(K);continue}let U=G+j;if(U>X){B.push(K);continue}G=U,V.push(F)}catch{B.push(K)}}return{prompt:$,mentions:Q,matchedFiles:V,ignoredMentions:B}}var RM=["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"],EM=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],E2=null;function NM(){if(E2!==null)return Promise.resolve(E2);return new Promise(($)=>{let W=VG("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});W.on("close",(Z)=>{E2=Z===0,$(E2)}),W.on("error",()=>{E2=!1,$(!1)}),setTimeout(()=>{if(!W.killed)W.kill("SIGTERM");if(E2===null)E2=!1,$(!1)},1000)})}function wM($,W,Z,Q,J=5000,j){return new Promise((X)=>{let Y=VG("rg",["--json",`--context=${Q}`,"--max-count=1","-i",$],{cwd:W,stdio:["ignore","pipe","pipe"],windowsHide:!0}),V="",B=!1,H=()=>{if(!Y.killed)Y.kill("SIGTERM")},G=setTimeout(()=>{if(!B)B=!0,H(),X(null)},J),K=(F)=>{if(!B)B=!0,clearTimeout(G),H(),X(F)};if(j?.aborted){H(),X(null);return}j?.addEventListener("abort",()=>{K(null)}),Y.stdout.on("data",(F)=>{V+=F.toString()}),Y.stderr.on("data",()=>{}),Y.on("close",(F)=>{if(F===0||F===1){try{let A=[],D=V.split(`
439
+ `).filter((U)=>U.trim());for(let U of D){if(A.length>=Z)break;let f=JSON.parse(U);if(f.type==="match"){let _=f.data,R=[];if(f.data.submatches&&f.data.submatches.length>0){let O=f.data.submatches[0];A.push({file:_.path.text,line:_.line_number,column:(O?.start??0)+1,match:O?.match?.text??"",context:R})}}else if(f.type==="context"&&A.length>0){let _=A[A.length-1],R=f.data.line_number===_.line?">":" ";_.context.push(`${R} ${f.data.line_number}: ${f.data.lines?.text??f.data.line?.text??""}`)}}K(A.length>0?A:null)}catch{K(null)}return}K(null)}),Y.on("error",()=>{K(null)})})}function CM($,W,Z,Q){let J=$.split("/"),j=J[J.length-1]??"";if(J.length-1>Q)return!1;for(let V=0;V<J.length-1;V++)if(W.has(J[V]??""))return!1;let Y=QZ.posix.extname(j).slice(1).toLowerCase();return Z.has(Y)||!Y&&!j.startsWith(".")}function t4($={}){let{includeExtensions:W=RM,excludeDirs:Z=EM,maxResults:Q=100,contextLines:J=2,maxDepth:j=20}=$,X=new Set(Z),Y=new Set(W.map((V)=>V.toLowerCase()));return async(V,B,H)=>{if(H.signal?.aborted)throw Error("Search operation aborted");let G=await NM(),K=null;if(G)K=await wM(V,B,Q,J,5000,H.signal);if(K){let _=[`Found ${K.length} result${K.length===1?"":"s"} for pattern: ${V}`,""];for(let R of K)_.push(`${R.file}:${R.line}:${R.column}`),_.push(...R.context),_.push("");if(K.length>=Q)_.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return YG(_.join(`
440
+ `))}let F;try{F=new RegExp(V,"gim")}catch(_){throw Error(`Invalid regex pattern: ${V}. ${_ instanceof Error?_.message:""}`)}let A=[],D=0,U=await t1(B);for(let _ of U){if(H.signal?.aborted)throw Error("Search operation aborted");if(!CM(_,X,Y,j))continue;if(A.length>=Q)break;D++;let R=QZ.join(B,_);try{let T=(await BG.readFile(R,"utf-8")).split(`
441
441
  `);for(let L=0;L<T.length;L++){let C=T[L];F.lastIndex=0;let E=F.exec(C);while(E!==null){if(A.length>=Q)break;let p=Math.max(0,L-J),x=Math.min(T.length-1,L+J),P=[];for(let r=p;r<=x;r++){let d=r===L?">":" ";P.push(`${d} ${r+1}: ${T[r]}`)}if(A.push({file:_,line:L+1,column:E.index+1,match:E[0],context:P}),E.index===F.lastIndex)F.lastIndex++;E=F.exec(C)}}}catch{}}if(A.length===0)return`No results found for pattern: ${V}
442
- Searched ${D} files.`;let f=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${V}`,`Searched ${D} files.`,""];for(let _ of A)f.push(`${_.file}:${_.line}:${_.column}`),f.push(..._.context),f.push("");if(A.length>=Q)f.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return XG(f.join(`
443
- `))}}function XG($){if($.length<=v8)return $;let W=Math.ceil(v8/2),Z=Math.max(1,v8-W);return`${$.slice(0,W)}
442
+ Searched ${D} files.`;let f=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${V}`,`Searched ${D} files.`,""];for(let _ of A)f.push(`${_.file}:${_.line}:${_.column}`),f.push(..._.context),f.push("");if(A.length>=Q)f.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return YG(f.join(`
443
+ `))}}function YG($){if($.length<=v8)return $;let W=Math.ceil(v8/2),Z=Math.max(1,v8-W);return`${$.slice(0,W)}
444
444
  [... search output truncated: ${$.length} chars total. Narrow the pattern or scope to view the elided matches ...]
445
- `+$.slice(-Z)}function CM($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
445
+ `+$.slice(-Z)}function PM($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
446
446
  `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(W,Z)=>String.fromCharCode(parseInt(Z,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
447
447
  `).replace(/\n{3,}/g,`
448
448
 
449
- `).trim()}function e4($={}){let{timeoutMs:W=30000,maxResponseBytes:Z=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:J={},followRedirects:j=!0}=$;return async(X,Y,V)=>{let B;try{B=new URL(X)}catch{throw Error(`Invalid URL: ${X}`)}if(!["http:","https:"].includes(B.protocol))throw Error(`Invalid protocol: ${B.protocol}. Only http and https are supported.`);let H=new AbortController,G=setTimeout(()=>H.abort(),W),K;if(V.signal)K=()=>H.abort(),V.signal.addEventListener("abort",K);try{let F=await fetch(X,{method:"GET",headers:{"User-Agent":Q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...J},redirect:j?"follow":"manual",signal:H.signal});if(clearTimeout(G),!j&&F.status>=300&&F.status<400)return`Redirect to: ${F.headers.get("location")}`;if(!F.ok)throw Error(`HTTP ${F.status}: ${F.statusText}`);let A=F.headers.get("content-type")||"",D=F.body?.getReader();if(!D)throw Error("Failed to read response body");let U=[],f=0;while(!0){let{done:C,value:E}=await D.read();if(C)break;if(f+=E.length,f>Z)throw D.cancel(),Error(`Response too large: exceeded ${Z} bytes`);U.push(E)}let _=new Uint8Array(f),R=0;for(let C of U)_.set(C,R),R+=C.length;let O=new TextDecoder("utf-8").decode(_),T;if(A.includes("text/html")||A.includes("application/xhtml"))T=CM(O);else if(A.includes("application/json"))try{let C=JSON.parse(O);T=JSON.stringify(C,null,2)}catch{T=O}else T=O;let L=[`URL: ${X}`,`Content-Type: ${A}`,`Size: ${f} bytes`,"","--- Content ---",T.slice(0,50000)];if(T.length>50000)L.push(`
449
+ `).trim()}function e4($={}){let{timeoutMs:W=30000,maxResponseBytes:Z=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:J={},followRedirects:j=!0}=$;return async(X,Y,V)=>{let B;try{B=new URL(X)}catch{throw Error(`Invalid URL: ${X}`)}if(!["http:","https:"].includes(B.protocol))throw Error(`Invalid protocol: ${B.protocol}. Only http and https are supported.`);let H=new AbortController,G=setTimeout(()=>H.abort(),W),K;if(V.signal)K=()=>H.abort(),V.signal.addEventListener("abort",K);try{let F=await fetch(X,{method:"GET",headers:{"User-Agent":Q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...J},redirect:j?"follow":"manual",signal:H.signal});if(clearTimeout(G),!j&&F.status>=300&&F.status<400)return`Redirect to: ${F.headers.get("location")}`;if(!F.ok)throw Error(`HTTP ${F.status}: ${F.statusText}`);let A=F.headers.get("content-type")||"",D=F.body?.getReader();if(!D)throw Error("Failed to read response body");let U=[],f=0;while(!0){let{done:C,value:E}=await D.read();if(C)break;if(f+=E.length,f>Z)throw D.cancel(),Error(`Response too large: exceeded ${Z} bytes`);U.push(E)}let _=new Uint8Array(f),R=0;for(let C of U)_.set(C,R),R+=C.length;let O=new TextDecoder("utf-8").decode(_),T;if(A.includes("text/html")||A.includes("application/xhtml"))T=PM(O);else if(A.includes("application/json"))try{let C=JSON.parse(O);T=JSON.stringify(C,null,2)}catch{T=O}else T=O;let L=[`URL: ${X}`,`Content-Type: ${A}`,`Size: ${f} bytes`,"","--- Content ---",T.slice(0,50000)];if(T.length>50000)L.push(`
450
450
  [Content truncated: showing first 50000 of ${T.length} characters]`);return L.push("","--- Analysis Request ---",`Prompt: ${Y}`),L.join(`
451
- `)}catch(F){if(clearTimeout(G),F instanceof Error){if(F.name==="AbortError")throw Error(`Request timed out after ${W}ms`);throw F}throw Error(`Fetch failed: ${String(F)}`)}finally{if(V.signal&&K)V.signal.removeEventListener("abort",K)}}}function $5($={}){return T2($)}function l8($={}){return{readFile:s4($.fileRead),search:t4($.search),bash:$5($.bash),webFetch:e4($.webFetch),applyPatch:q2($.applyPatch),editor:M2($.editor)}}var PM={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion",submit_and_exit:"enableSubmitAndExit"},p8=[{name:"openai-native-use-apply-patch",mode:"act",providerIdIncludes:["openai-native"],enableTools:["apply_patch"],disableTools:["editor"]},{name:"codex-and-gpt-use-apply-patch",mode:"act",modelIdIncludes:["codex","gpt"],enableTools:["apply_patch"],disableTools:["editor"]}];function BG($,W){if(!W||W.length===0)return!0;let Z=$.toLowerCase();return W.some((Q)=>Z.includes(Q.toLowerCase()))}function SM($,W,Z,Q){if($.mode&&$.mode!=="any"&&$.mode!==Q)return!1;return BG(W,$.providerIdIncludes)&&BG(Z,$.modelIdIncludes)}function r8($,W,Z,Q){if(!Q||Q.length===0)return{};let J=new Map;for(let X of Q){if(!SM(X,$,W,Z))continue;for(let Y of X.disableTools??[])J.set(Y,!1);for(let Y of X.enableTools??[])J.set(Y,!0)}let j={};for(let[X,Y]of J.entries())j[PM[X]]=Y;return j}var a0={act:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},plan:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!1},yolo:{enableReadFiles:!0,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!0,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!0,enableSpawnAgent:!1,enableAgentTeams:!1}};function e1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function QZ($){if($!=="yolo")return{};let W={enabled:!0,autoApprove:!0},Z={"*":W};for(let Q of D$)Z[Q]=W;return Z}function JZ($,W){let Z=a0[$],{enableSpawnAgent:Q,enableAgentTeams:J,...j}=Z;return N$({...j,...W})}import{createTool as nR,zodToJsonSchema as aR}from"@cline/shared";import{z as HJ}from"zod";X1();import{createAgentRuntime as IR}from"@cline/agents";import{createContributionRegistry as xR,mergeModelOptions as PG}from"@cline/shared";import{createGateway as cM,createHandlerAsync as uM,hasRegisteredHandler as dM,MODEL_COLLECTIONS_BY_PROVIDER_ID as lM,normalizeProviderId as pM}from"@cline/llms";import{EMPTY_CONTENT_TEXT as bM}from"@cline/shared";function yM($){let W=kM($.content),Z=[],Q=$.id??gM(),J=0,j=[],X=()=>{if(j.length===0)return;let Y=J===0?Q:`${Q}_part_${J}`;J+=1,Z.push({id:Y,role:$.role,content:j.map(IM),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:HG($.metrics)}),j=[]};if(W.length===0)return Z.push({id:Q,role:$.role,content:[{type:"text",text:bM}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:HG($.metrics)}),Z;for(let Y of W){if(Y.type!=="tool_result"){j.push(Y);continue}X(),Z.push({id:`${Q}_tool_${Y.tool_use_id}`,role:"tool",content:[KG(Y)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return X(),Z}function jZ($){return $.flatMap(yM)}function hM($){let W=$.content.map(FG).filter((Z)=>Z!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:W,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:xM($.metrics)}}function i8($){return $.map(hM)}function XZ($){let W=[];for(let Z of $){let Q=Z.content.map(FG).filter((X)=>X!==void 0),J=Z.role==="tool"?"user":Z.role,j=W[W.length-1];if(J==="user"&&Q.length>0&&Q.every((X)=>X.type==="tool_result")&&j?.role==="user"&&Array.isArray(j.content)&&j.content.every((X)=>X.type==="tool_result")){j.content.push(...Q);continue}W.push({role:J,content:Q})}return W}function kM($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function IM($){switch($.type){case"text":return{type:"text",text:$.text};case"thinking":return{type:"reasoning",text:$.thinking,metadata:$.signature?{signature:$.signature,details:$.details}:$.details?{details:$.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:$.data}};case"image":return{type:"image",image:$.data,mediaType:$.mediaType};case"file":return{type:"file",path:$.path,content:$.content};case"tool_use":return{type:"tool-call",toolCallId:$.id,toolName:$.name,input:$.input,metadata:$.signature?{signature:$.signature}:void 0};case"tool_result":return KG($)}}function KG($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function FG($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let W=$.metadata;return{type:"thinking",thinking:$.text,signature:W?.signature,details:W?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":{let W=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:W?.thoughtSignature??W?.signature}}case"tool-result":{let W=$.output,Z=typeof W==="string"?W:Array.isArray(W)?W:JSON.stringify(W);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Z,is_error:$.isError}}}}function HG($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function xM($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var GG=0;function gM(){return GG+=1,`msg_${Date.now().toString(36)}_${GG.toString(36)}`}function mM($){switch($.type){case"text":return[{type:"text-delta",text:$.text}];case"reasoning":return[{type:"reasoning-delta",text:$.reasoning,metadata:$.signature?{thoughtSignature:$.signature,details:$.details}:{details:$.details}}];case"tool_calls":{let W=$.tool_call.function,Z=W.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??W.id,toolName:W.name,inputText:typeof Z==="string"?Z:void 0,input:typeof Z==="string"?void 0:Z,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,reasoningTokenCount:$.thoughtsTokenCount,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:vM($),error:$.error}];default:return[]}}function vM($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function AG($){return{async*stream(W){let Z=!1,Q=!1;try{let J=typeof $==="function"?await $():$;J.setAbortSignal?.(W.signal);let j=XZ(W.messages),X=W.tools.map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}));for await(let Y of J.createMessage(W.systemPrompt??"",j,X))for(let V of mM(Y)){if(V.type==="finish")Z=!0;else if(V.type==="tool-call-delta")Q=!0;yield V}if(!Z)yield{type:"finish",reason:Q?"tool-calls":"stop"}}catch(J){if(!Z)yield{type:"finish",reason:W.signal?.aborted?"aborted":"error",error:J instanceof Error?J.message:String(J)}}}}}function rM($){let W=Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0));return Object.keys(W).length>0?W:void 0}function iM($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function nM($){let W={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(iM($))Object.assign(W,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(W,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let Z=$.gcp?.region??$.region;Object.assign(W,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Z,region:Z})}if($.providerId==="sapaicore")Object.assign(W,$.sap);return rM(W)}function aM($){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):void 0}function t3($){let W=$.providerConfig,Z=W?.knownModels?W.knownModels:$.knownModels??lM[$.providerId]?.models??void 0,Q=aM(W?.maxInputTokens),J=W?.modelInfo&&W.modelInfo.id===$.modelId?W.modelInfo:void 0;if(Q===void 0&&!J)return Z;return{...Z??{},[$.modelId]:{...Z?.[$.modelId],...Q!==void 0?{contextWindow:Q,maxInputTokens:Q}:{},...J,id:$.modelId}}}function oM($){if(!$?.length)return;let W=new Set;for(let Z of $)switch(Z){case"tools":case"reasoning":case"prompt-cache":case"images":W.add(Z);break;case"structured_output":W.add("structured-output");break;default:W.add("text")}return W.add("text"),[...W]}function sM($,W){return{id:$,name:W.name??$,description:W.description,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxOutputTokens:W.maxTokens,capabilities:oM(W.capabilities),metadata:{family:W.family,pricing:W.pricing,status:W.status,releaseDate:W.releaseDate}}}function UG($,W,Z){let Q=$.providerConfig,J=Q?.providerId===$.providerId?Q:void 0,j={...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:t3($),maxOutputTokens:$.maxTokensPerTurn,temperature:$.temperature,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:W,extensionContext:$.extensionContext};if(dM(pM(j.providerId)))return AG(()=>uM(j));return cM({fetch:j.fetch,providerConfigs:[{providerId:j.providerId,apiKey:j.apiKey,baseUrl:j.baseUrl,headers:j.headers,timeoutMs:j.timeoutMs,fetch:j.fetch,options:nM(j),models:j.knownModels?Object.entries(j.knownModels).map(([X,Y])=>sM(X,Y)):void 0}],logger:W,telemetry:Z??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:j.providerId,modelId:j.modelId},{maxTokens:j.maxOutputTokens,temperature:j.temperature})}import{createMediaBudgetState as tM,IMAGE_OMITTED_PLACEHOLDER as DG,normalizeUserInput as _G,resolveMediaBudget as eM,validateAndReserveImageMedia as $R}from"@cline/shared";var WR=8000,ZR=50000,QR=6000000,JR=200000,jR=12000,XR=65536,Z5=2000,fG=40000,YR=8,e3={maxToolResultChars:"CLINE_MESSAGE_BUILDER_MAX_TOOL_RESULT_CHARS",maxTotalTextBytes:"CLINE_MESSAGE_BUILDER_MAX_TOTAL_TEXT_BYTES",minOutdatedRewriteBytes:"CLINE_MESSAGE_BUILDER_MIN_OUTDATED_REWRITE_BYTES"},VR=new Set(["read","read_files"]),N2="[outdated - see the latest file content]",LG="Tool execution was interrupted before a result was produced.",TG=($)=>`
451
+ `)}catch(F){if(clearTimeout(G),F instanceof Error){if(F.name==="AbortError")throw Error(`Request timed out after ${W}ms`);throw F}throw Error(`Fetch failed: ${String(F)}`)}finally{if(V.signal&&K)V.signal.removeEventListener("abort",K)}}}function $5($={}){return T2($)}function l8($={}){return{readFile:s4($.fileRead),search:t4($.search),bash:$5($.bash),webFetch:e4($.webFetch),applyPatch:q2($.applyPatch),editor:M2($.editor)}}var SM={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion",submit_and_exit:"enableSubmitAndExit"},p8=[{name:"openai-native-use-apply-patch",mode:"act",providerIdIncludes:["openai-native"],enableTools:["apply_patch"],disableTools:["editor"]},{name:"codex-and-gpt-use-apply-patch",mode:"act",modelIdIncludes:["codex","gpt"],enableTools:["apply_patch"],disableTools:["editor"]}];function HG($,W){if(!W||W.length===0)return!0;let Z=$.toLowerCase();return W.some((Q)=>Z.includes(Q.toLowerCase()))}function bM($,W,Z,Q){if($.mode&&$.mode!=="any"&&$.mode!==Q)return!1;return HG(W,$.providerIdIncludes)&&HG(Z,$.modelIdIncludes)}function r8($,W,Z,Q){if(!Q||Q.length===0)return{};let J=new Map;for(let X of Q){if(!bM(X,$,W,Z))continue;for(let Y of X.disableTools??[])J.set(Y,!1);for(let Y of X.enableTools??[])J.set(Y,!0)}let j={};for(let[X,Y]of J.entries())j[SM[X]]=Y;return j}var a0={act:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},plan:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!1},yolo:{enableReadFiles:!0,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!0,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!0,enableSpawnAgent:!1,enableAgentTeams:!1}};function e1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function JZ($){if($!=="yolo")return{};let W={enabled:!0,autoApprove:!0},Z={"*":W};for(let Q of D$)Z[Q]=W;return Z}function jZ($,W){let Z=a0[$],{enableSpawnAgent:Q,enableAgentTeams:J,...j}=Z;return N$({...j,...W})}import{createTool as aR,zodToJsonSchema as oR}from"@cline/shared";import{z as GJ}from"zod";X1();import{createAgentRuntime as xR}from"@cline/agents";import{createContributionRegistry as gR,mergeModelOptions as SG}from"@cline/shared";import{createGateway as uM,createHandlerAsync as dM,hasRegisteredHandler as lM,MODEL_COLLECTIONS_BY_PROVIDER_ID as pM,normalizeProviderId as rM}from"@cline/llms";import{EMPTY_CONTENT_TEXT as yM}from"@cline/shared";function hM($){let W=IM($.content),Z=[],Q=$.id??mM(),J=0,j=[],X=()=>{if(j.length===0)return;let Y=J===0?Q:`${Q}_part_${J}`;J+=1,Z.push({id:Y,role:$.role,content:j.map(xM),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:GG($.metrics)}),j=[]};if(W.length===0)return Z.push({id:Q,role:$.role,content:[{type:"text",text:yM}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:GG($.metrics)}),Z;for(let Y of W){if(Y.type!=="tool_result"){j.push(Y);continue}X(),Z.push({id:`${Q}_tool_${Y.tool_use_id}`,role:"tool",content:[FG(Y)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return X(),Z}function XZ($){return $.flatMap(hM)}function kM($){let W=$.content.map(AG).filter((Z)=>Z!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:W,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:gM($.metrics)}}function i8($){return $.map(kM)}function YZ($){let W=[];for(let Z of $){let Q=Z.content.map(AG).filter((X)=>X!==void 0),J=Z.role==="tool"?"user":Z.role,j=W[W.length-1];if(J==="user"&&Q.length>0&&Q.every((X)=>X.type==="tool_result")&&j?.role==="user"&&Array.isArray(j.content)&&j.content.every((X)=>X.type==="tool_result")){j.content.push(...Q);continue}W.push({role:J,content:Q})}return W}function IM($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function xM($){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 FG($)}}function FG($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function AG($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let W=$.metadata;return{type:"thinking",thinking:$.text,signature:W?.signature,details:W?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":{let W=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:W?.thoughtSignature??W?.signature}}case"tool-result":{let W=$.output,Z=typeof W==="string"?W:Array.isArray(W)?W:JSON.stringify(W);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Z,is_error:$.isError}}}}function GG($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function gM($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var KG=0;function mM(){return KG+=1,`msg_${Date.now().toString(36)}_${KG.toString(36)}`}function vM($){switch($.type){case"text":return[{type:"text-delta",text:$.text}];case"reasoning":return[{type:"reasoning-delta",text:$.reasoning,metadata:$.signature?{thoughtSignature:$.signature,details:$.details}:{details:$.details}}];case"tool_calls":{let W=$.tool_call.function,Z=W.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??W.id,toolName:W.name,inputText:typeof Z==="string"?Z:void 0,input:typeof Z==="string"?void 0:Z,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,reasoningTokenCount:$.thoughtsTokenCount,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:cM($),error:$.error}];default:return[]}}function cM($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function UG($){return{async*stream(W){let Z=!1,Q=!1;try{let J=typeof $==="function"?await $():$;J.setAbortSignal?.(W.signal);let j=YZ(W.messages),X=W.tools.map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}));for await(let Y of J.createMessage(W.systemPrompt??"",j,X))for(let V of vM(Y)){if(V.type==="finish")Z=!0;else if(V.type==="tool-call-delta")Q=!0;yield V}if(!Z)yield{type:"finish",reason:Q?"tool-calls":"stop"}}catch(J){if(!Z)yield{type:"finish",reason:W.signal?.aborted?"aborted":"error",error:J instanceof Error?J.message:String(J)}}}}}function iM($){let W=Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0));return Object.keys(W).length>0?W:void 0}function nM($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function aM($){let W={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(nM($))Object.assign(W,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(W,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let Z=$.gcp?.region??$.region;Object.assign(W,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Z,region:Z})}if($.providerId==="sapaicore")Object.assign(W,$.sap);return iM(W)}function oM($){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):void 0}function e3($){let W=$.providerConfig,Z=W?.knownModels?W.knownModels:$.knownModels??pM[$.providerId]?.models??void 0,Q=oM(W?.maxInputTokens),J=W?.modelInfo&&W.modelInfo.id===$.modelId?W.modelInfo:void 0;if(Q===void 0&&!J)return Z;return{...Z??{},[$.modelId]:{...Z?.[$.modelId],...Q!==void 0?{contextWindow:Q,maxInputTokens:Q}:{},...J,id:$.modelId}}}function sM($){if(!$?.length)return;let W=new Set;for(let Z of $)switch(Z){case"tools":case"reasoning":case"prompt-cache":case"images":W.add(Z);break;case"structured_output":W.add("structured-output");break;default:W.add("text")}return W.add("text"),[...W]}function tM($,W){return{id:$,name:W.name??$,description:W.description,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxOutputTokens:W.maxTokens,capabilities:sM(W.capabilities),metadata:{family:W.family,pricing:W.pricing,status:W.status,releaseDate:W.releaseDate}}}function DG($,W,Z){let Q=$.providerConfig,J=Q?.providerId===$.providerId?Q:void 0,j={...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:e3($),maxOutputTokens:$.maxTokensPerTurn,temperature:$.temperature,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:W,extensionContext:$.extensionContext};if(lM(rM(j.providerId)))return UG(()=>dM(j));return uM({fetch:j.fetch,providerConfigs:[{providerId:j.providerId,apiKey:j.apiKey,baseUrl:j.baseUrl,headers:j.headers,timeoutMs:j.timeoutMs,fetch:j.fetch,options:aM(j),models:j.knownModels?Object.entries(j.knownModels).map(([X,Y])=>tM(X,Y)):void 0}],logger:W,telemetry:Z??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:j.providerId,modelId:j.modelId},{maxTokens:j.maxOutputTokens,temperature:j.temperature})}z0();import{createMediaBudgetState as eM,IMAGE_OMITTED_PLACEHOLDER as _G,normalizeUserInput as fG,resolveMediaBudget as $R,validateAndReserveImageMedia as WR}from"@cline/shared";var ZR=8000,QR=50000,JR=6000000,jR=200000,XR=12000,YR=65536,Z5=2000,LG=40000,VR=8,$J={maxToolResultChars:"CLINE_MESSAGE_BUILDER_MAX_TOOL_RESULT_CHARS",maxTotalTextBytes:"CLINE_MESSAGE_BUILDER_MAX_TOTAL_TEXT_BYTES",minOutdatedRewriteBytes:"CLINE_MESSAGE_BUILDER_MIN_OUTDATED_REWRITE_BYTES"},BR=new Set(["read","read_files"]),N2="[outdated - see the latest file content]",TG="Tool execution was interrupted before a result was produced.",OG=($)=>`
452
452
 
453
453
  ...[truncated ${$} chars]...
454
454
 
@@ -456,85 +456,85 @@ Searched ${D} files.`;let f=[`Found ${A.length} result${A.length===1?"":"s"} for
456
456
 
457
457
  ...[truncated ${$} chars to fit provider request budget]...
458
458
 
459
- `,BR=($)=>`
459
+ `,HR=($)=>`
460
460
 
461
461
  ...[assistant text truncated: omitted ${$} chars]...
462
462
 
463
- `,OG=($)=>`
463
+ `,zG=($)=>`
464
464
 
465
465
  ...[assistant text truncated: omitted ${$} chars to fit provider request budget]...
466
466
 
467
- `,HR=($)=>`
467
+ `,GR=($)=>`
468
468
 
469
469
  ...[assistant text truncated: omitted ${$} chars due to repeated tool-call markup]...
470
470
 
471
- `;function MG($=process.env){return{maxToolResultChars:qG($[e3.maxToolResultChars]),maxTotalTextBytes:qG($[e3.maxTotalTextBytes]),minOutdatedRewriteBytes:KR($[e3.minOutdatedRewriteBytes])}}class WJ{indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;maxToolResultChars;maxFileContentChars;maxTotalTextBytes;mediaBudget;maxAssistantTextChars;maxAssistantToolMarkupChars;minOutdatedRewriteBytes;committedOutdatedRewrites=new Map;constructor($={}){this.maxToolResultChars=W5($.maxToolResultChars,WR),this.maxFileContentChars=W5($.maxFileContentChars,ZR),this.maxTotalTextBytes=W5($.maxTotalTextBytes,QR),this.mediaBudget=$.mediaBudget??{},this.maxAssistantTextChars=W5($.maxAssistantTextChars,JR),this.maxAssistantToolMarkupChars=W5($.maxAssistantToolMarkupChars,jR),this.minOutdatedRewriteBytes=FR($.minOutdatedRewriteBytes,XR)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi($){this.reindex($),this.commitOutdatedRewrites($);let Z=this.addMissingToolResults($).map((J)=>{if(!Array.isArray(J.content)){if(J.role==="user"&&typeof J.content==="string"){let Y=_G(J.content);if(Y!==J.content)return{...J,content:Y}}if(J.role==="assistant"&&typeof J.content==="string"){let Y=this.truncateAssistantText(J.content);if(Y!==J.content)return{...J,content:Y}}return J}let j=!1,X=J.content.map((Y)=>{let V=this.transformBlock(Y,J.role);if(V!==Y)j=!0;return V});return j?{...J,content:X}:J}),Q=this.applyMediaBudget(Z);return this.truncateToTotalTextBudget(Q)}transformBlock($,W){if(W==="user"&&$.type==="text"&&typeof $.text==="string"){let J=_G($.text);if(J!==$.text)return{...$,text:J};return $}if(W==="assistant"&&$.type==="text"&&typeof $.text==="string"){let J=this.truncateAssistantText($.text);return J===$.text?$:{...$,text:J}}if($.type==="file"){let J=n8($.content,this.maxFileContentChars,TG);return J===$.content?$:{...$,content:J}}if($.type!=="tool_result")return $;let Z=this.resolveToolName($),Q=$.content;if(this.isReadTool(Z)&&$.is_error!==!0){let J=this.committedOutdatedRewrites.get($.tool_use_id);if(J&&J.size>0){let X=this.getReadLocators($).filter((Y)=>J.has(this.toReadLocatorKey(Y))&&this.isOutdatedReadLocator(Y,$.tool_use_id));if(X.length>0)Q=this.replaceOutdatedReadContent(Q,X)}}return Q=this.truncateToolResultContent(Q),Q===$.content?$:{...$,content:Q}}reindex($){let W=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!W)this.resetIndexes();for(let Z=this.indexedMessageCount;Z<$.length;Z++){let Q=$[Z];if(!Array.isArray(Q.content))continue;for(let J=0;J<Q.content.length;J++){let j=Q.content[J];if(j.type==="file")this.latestFullContentOwnerByPathCache.set(j.path,`file:${Z}:${J}`);else if(j.type==="tool_use"){let X=j.name.toLowerCase();if(this.toolNameByIdCache.set(j.id,X),this.isReadTool(X)){let Y=this.extractLocatorsFromReadToolInput(j.input);if(Y.length>0)this.readLocatorsByToolUseIdCache.set(j.id,Y)}}else if(j.type==="tool_result"){let X=this.resolveToolName(j);if(!this.isReadTool(X)||j.is_error===!0)continue;let Y=this.getReadLocators(j);for(let V of Y)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(V),j.tool_use_id),this.isFullFileRead(V))this.latestFullContentOwnerByPathCache.set(V.path,j.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}commitOutdatedRewrites($){let W=new Map,Z=new Set,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result"||j.is_error===!0)continue;let X=this.resolveToolName(j);if(!this.isReadTool(X))continue;Z.add(j.tool_use_id);let Y=this.committedOutdatedRewrites.get(j.tool_use_id),V=new Set,B=new Set;for(let G of this.getReadLocators(j)){let K=this.toReadLocatorKey(G);if(!this.isOutdatedReadLocator(G,j.tool_use_id))continue;if(B.add(K),!Y?.has(K))V.add(K)}if(Y){for(let G of Y)if(!B.has(G))Y.delete(G);if(Y.size===0)this.committedOutdatedRewrites.delete(j.tool_use_id)}if(V.size===0)continue;let H=W.get(j.tool_use_id);if(!H)H=new Set,W.set(j.tool_use_id,H);for(let G of V)H.add(G);Q+=this.estimateOutdatedReclaimBytes(j.content,V)}}for(let J of this.committedOutdatedRewrites.keys())if(!Z.has(J))this.committedOutdatedRewrites.delete(J);if(W.size===0||Q<this.minOutdatedRewriteBytes)return;for(let[J,j]of W){let X=this.committedOutdatedRewrites.get(J);if(!X)X=new Set,this.committedOutdatedRewrites.set(J,X);for(let Y of j)X.add(Y)}}estimateOutdatedReclaimBytes($,W){let Z=this.extractReadLocatorsFromToolResultContent($),Q=Z.length>0&&Z.every((V)=>W.has(this.toReadLocatorKey(V))),J=(V)=>{let B;try{B=JSON.parse(V)}catch{return Q||Z.length===0?j0(this.truncateMiddle(V)):0}let H=Array.isArray(B)?B:[B],G=0;for(let K of H){let F=this.extractLocatorFromResultEntry(K);if(F&&W.has(this.toReadLocatorKey(F)))G+=this.providerBoundEntryBytes(K)}return G};if(typeof $==="string")return J($);let j=new Set(W),X=0;for(let V of $)if(V.type==="text")X+=this.countOutdatedImageEntries(V.text,j);let Y=0;for(let V of $)if(V.type==="text")Y+=J(V.text);else if(V.type==="image"){if(X>0)X-=1,Y+=j0(V.data)}else if(C$(V)){let B=this.extractLocatorFromResultEntry(V);if(B&&W.has(this.toReadLocatorKey(B)))Y+=this.providerBoundEntryBytes(V)}else if(V.type==="file"){if(W.has(this.toReadLocatorKey({path:V.path,startLine:null,endLine:null})))Y+=j0(this.truncateMiddle(V.content))}return Y}providerBoundEntryBytes($){let W=this.truncateNestedStrings($);return j0(JSON.stringify(W))}addMissingToolResults($){let W=this.collectToolResultIds($),Z=[],Q=new Map,J=!1,j=()=>{if(Q.size===0)return;X(this.createMissingToolResultMessage(Q)),Q.clear(),J=!0},X=(Y)=>{let V=Z.at(-1);if(this.shouldMergeUserAfterToolResults(V,Y)){Z[Z.length-1]={...V,content:[...V.content,...this.contentBlocksForUserMerge(Y.content)]},J=!0;return}Z.push(Y)};for(let Y of $){if(this.isToolResultOnlyMessage(Y)){if(X(this.appendMissingToolResults(Y,Q)),Q.size>0)Q.clear(),J=!0;continue}if(Array.isArray(Y.content)){let V=Y.content.filter((H)=>H.type==="tool_result"),B=Y.content.filter((H)=>H.type!=="tool_result");if(V.length>0){let H=this.appendMissingToolResults({...Y,role:"user",content:V},Q);if(X(H),Q.size>0)Q.clear();J=!0}if(B.length>0||V.length===0){if(V.length===0)j();let H=V.length>0?{...Y,content:B}:Y;if(X(H),H.role==="assistant")this.trackMissingToolCalls(H,W,Q)}continue}j(),X(Y)}return j(),J?Z:$}appendMissingToolResults($,W){if(W.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(W)]}}shouldMergeUserAfterToolResults($,W){return $?.role==="user"&&W.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(W.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}return W}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}trackMissingToolCalls($,W,Z){if(!Array.isArray($.content))return;for(let Q of $.content){if(Q.type!=="tool_use"||W.has(Q.id))continue;Z.set(Q.id,Q.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([W,Z])=>({type:"tool_result",tool_use_id:W,name:Z,content:[{type:"text",text:this.formatMissingToolResultText(Z)}],is_error:!0}))}formatMissingToolResultText($){return $?`${LG} Tool: ${$}.`:LG}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let W=$,Z=this.readResultLocatorCache.get(W);if(Z===void 0)Z=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(W,Z);if(Z.length>0)return Z;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let W=$,Z=[],Q=this.extractLocatorFromReadRequest(W);if(Q)Z.push(Q);if(Array.isArray(W.files))for(let J of W.files){let j=this.extractLocatorFromReadRequest(J);if(j)Z.push(j)}if(Array.isArray(W.file_paths)){for(let J of W.file_paths)if(typeof J==="string"&&J.length>0)Z.push({path:J,startLine:null,endLine:null})}return this.dedupeReadLocators(Z)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);let W=[];for(let Z of $){if(Z.type==="text"){W.push(...this.tryParseReadLocators(Z.text));continue}if(C$(Z)){let Q=this.extractLocatorFromResultEntry(Z);if(Q)W.push(Q)}}return this.dedupeReadLocators(W)}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Z=[];for(let Q of $){let J=this.extractLocatorFromResultEntry(Q);if(J)Z.push(J)}return this.dedupeReadLocators(Z)}let W=this.extractLocatorFromResultEntry($);return W?[W]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(!Z)return;return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(Z)return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)};if(typeof W.query==="string"&&W.query.length>0)return this.parseReadQuery(W.query);return}extractPath($){let W=[$.path,$.file_path,$.filePath];for(let Z of W)if(typeof Z==="string"&&Z.length>0)return Z;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let W=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!W)return{path:$,startLine:null,endLine:null};return{path:W[1],startLine:Number(W[2]),endLine:W[3]==="EOF"?null:Number(W[3])}}dedupeReadLocators($){let W=new Map;for(let Z of $)W.set(this.toReadLocatorKey(Z),Z);return Array.from(W.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,W){let Z=this.latestFullContentOwnerByPathCache.get($.path);if(Z&&Z!==W)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==W}replaceOutdatedReadContent($,W){let Z=new Set(W.map((j)=>this.toReadLocatorKey(j))),Q=new Set(W.map((j)=>j.path));if(typeof $==="string")return this.replaceOutdatedInString($,Z)??N2;let J=0;for(let j of $)if(j.type==="text")J+=this.countOutdatedImageEntries(j.text,Z);return $.map((j)=>{if(j.type==="file"){if(!Q.has(j.path))return j;return{...j,content:N2}}if(j.type==="image"){if(J===0)return j;return J-=1,{type:"text",text:N2}}if(C$(j))return this.replaceOutdatedReadEntry(j,Z);if(j.type!=="text")return j;let X=this.replaceOutdatedInString(j.text,Z);if(X===null)return{...j,text:N2};return X===j.text?j:{...j,text:X}})}countOutdatedImageEntries($,W){let Z;try{Z=JSON.parse($)}catch{return 0}let Q=Array.isArray(Z)?Z:[Z],J=0;for(let j of Q){if(!j||typeof j!=="object")continue;let X=j,Y=this.extractLocatorFromResultEntry(X);if(!Y)continue;if(!W.has(this.toReadLocatorKey(Y)))continue;if(X.result==="Successfully read image"||X.content==="Successfully read image")J+=1}return J}replaceOutdatedInString($,W){let Z;try{Z=JSON.parse($)}catch{return null}let Q=Array.isArray(Z)?Z.map((J)=>this.replaceOutdatedReadEntry(J,W)):this.replaceOutdatedReadEntry(Z,W);return JSON.stringify(Q)}replaceOutdatedReadEntry($,W){if(!$||typeof $!=="object")return $;let Z=this.extractLocatorFromResultEntry($);if(!Z||!W.has(this.toReadLocatorKey(Z)))return $;let Q={...$};if(typeof Q.result==="string")Q.result=N2;else if(typeof Q.content==="string")Q.content=N2;else Q.result=N2;return Q}isReadTool($){return!!$&&VR.has($)}resolveToolName($){let W=this.toolNameByIdCache.get($.tool_use_id);if(W!==void 0)return W;return typeof $.name==="string"&&$.name.length>0?$.name.toLowerCase():void 0}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((W)=>{if(W.type==="file"){let Z=this.truncateMiddle(W.content);return Z===W.content?W:{...W,content:Z}}if(W.type==="text"){let Z=this.truncateMiddle(W.text);return Z===W.text?W:{...W,text:Z}}if(C$(W))return this.truncateNestedStrings(W);return W})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let W=!1,Z=$.map((Q)=>{let J=this.truncateNestedStrings(Q);if(J!==Q)W=!0;return J});return W?Z:$}if($!==null&&typeof $==="object"){if(ZJ($))return $;let W=!1,Z={};for(let[Q,J]of Object.entries($)){let j=this.truncateNestedStrings(J);if(j!==J)W=!0;Z[Q]=j}return W?Z:$}return $}truncateMiddle($){return n8($,this.maxToolResultChars,TG)}truncateAssistantText($){if(this.hasRepeatedToolCallMarkup($))return n8($,this.maxAssistantToolMarkupChars,HR);return n8($,this.maxAssistantTextChars,BR)}hasRepeatedToolCallMarkup($){if($.length<=this.maxAssistantToolMarkupChars)return!1;let W=0;for(let Z of $.matchAll(GR))if(W+=1,W>=YR)return!0;return!1}truncateToTotalTextBudget($){let W=this.countMessageTextBytes($);if(W<=this.maxTotalTextBytes)return $;let Z=$.map((J)=>{if(!Array.isArray(J.content))return{...J};return{...J,content:J.content.map((j)=>UR(j))}}),Q=this.collectTruncationCandidates(Z);for(let J of Q){if(W<=this.maxTotalTextBytes)break;let j=J.byteLength;if(j<=J.minBytes)continue;let X=W-this.maxTotalTextBytes,Y=Math.max(J.minBytes,j-X),V=AR(J.get(),Y,J.makeMarker);J.set(V),W-=j-j0(V)}return Z}countMessageTextBytes($){let W=0;for(let Z of $){if(typeof Z.content==="string"){W+=j0(Z.content);continue}for(let Q of Z.content)if(Q.type==="text")W+=j0(Q.text);else if(Q.type==="thinking")W+=j0(Q.thinking);else if(Q.type==="file")W+=j0(Q.content);else if(Q.type==="tool_use")W+=YZ(Q.input);else if(Q.type==="tool_result"){if(typeof Q.content==="string")W+=j0(Q.content);else for(let J of Q.content)if(J.type==="text")W+=j0(J.text);else if(J.type==="file")W+=j0(J.content);else if(C$(J))W+=YZ(J)}}return W}collectTruncationCandidates($){let W=[],Z=[];for(let Q of $){if(Q.role==="assistant"&&typeof Q.content==="string"){W.push({byteLength:j0(Q.content),minBytes:fG,makeMarker:OG,get:()=>Q.content,set:(J)=>{Q.content=J}});continue}if(!Array.isArray(Q.content))continue;for(let J of Q.content){if(J.type==="tool_use"){VZ(J.input,Z);continue}if(Q.role==="assistant"&&J.type==="text"){W.push({byteLength:j0(J.text),minBytes:fG,makeMarker:OG,get:()=>J.text,set:(j)=>{J.text=j}});continue}if(J.type!=="tool_result")continue;if(typeof J.content==="string"){W.push({byteLength:j0(J.content),minBytes:Z5,makeMarker:Q5,get:()=>J.content,set:(j)=>{J.content=j}});continue}for(let j of J.content)if(j.type==="text")W.push({byteLength:j0(j.text),minBytes:Z5,makeMarker:Q5,get:()=>j.text,set:(X)=>{j.text=X}});else if(j.type==="file")W.push({byteLength:j0(j.content),minBytes:Z5,makeMarker:Q5,get:()=>j.content,set:(X)=>{j.content=X}});else if(C$(j))VZ(j,W)}}return W.sort((Q,J)=>J.byteLength-Q.byteLength),Z.sort((Q,J)=>J.byteLength-Q.byteLength),[...W,...Z]}applyMediaBudget($){let W=this.resolveMediaBudget();if(W.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&W.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&W.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Z=tM(),Q=!1,J=$.map((j)=>{if(!Array.isArray(j.content))return j;let X=!1,Y=j.content.map((V)=>{let B=this.applyMediaBudgetToBlock(V,W,Z);if(B!==V)X=!0;return B});if(!X)return j;return Q=!0,{...j,content:Y}});return Q?J:$}resolveMediaBudget(){return eM(this.mediaBudget)}applyMediaBudgetToBlock($,W,Z){if($J($))return this.limitImageContent($,W,Z);if($.type!=="tool_result"||typeof $.content==="string")return $;let Q=!1,J=$.content.map((j)=>{let X=this.applyMediaBudgetToToolResultEntry(j,W,Z);if(X!==j)Q=!0;return X});return Q?{...$,content:J}:$}applyMediaBudgetToToolResultEntry($,W,Z){if($J($))return this.limitImageContent($,W,Z);if(C$($))return this.limitNestedMedia($,W,Z);return $}limitNestedMedia($,W,Z){if($J($)){let Q=this.limitImageContent($,W,Z);return Q.type==="text"?Q.text:Q}if(Array.isArray($)){let Q=!1,J=$.map((j)=>{let X=this.limitNestedMedia(j,W,Z);if(X!==j)Q=!0;return X});return Q?J:$}if($!==null&&typeof $==="object"){let Q=!1,J={};for(let[j,X]of Object.entries($)){let Y=this.limitNestedMedia(X,W,Z);if(Y!==X)Q=!0;J[j]=Y}return Q?J:$}return $}limitImageContent($,W,Z){if(!RG($))return{type:"text",text:DG};let Q=$R($.mediaType,$.data,{maxImageEncodedBytes:W.maxImageEncodedBytes,maxImageDecodedBytes:W.maxImageDecodedBytes,maxTotalMediaBytes:W.maxTotalMediaBytes},Z);if(!Q.ok)return{type:"text",text:DG};return{...$,data:Q.base64,mediaType:Q.mediaType}}}var zG=String.raw`[\|\uFF5C]`,GR=new RegExp(String.raw`<\s*(?:${zG}\s*)?DSML\s*(?:${zG}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function j0($){return Buffer.byteLength($,"utf8")}function qG($){if($===void 0)return;let W=Number.parseInt($,10);return Number.isFinite(W)&&W>0?W:void 0}function KR($){if($===void 0)return;let W=$.trim().toLowerCase();if(W==="infinity"||W==="disable")return Number.POSITIVE_INFINITY;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>=0?Z:void 0}function W5($,W){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):W}function FR($,W){if(typeof $!=="number"||Number.isNaN($)||$<0)return W;return Number.isFinite($)?Math.floor($):$}function n8($,W,Z){if($.length<=W)return $;let Q=Z($.length-W),J=Math.max(0,Math.floor((W-Q.length)/2)),j=Math.max(0,$.length-J*2),X=Z(j),Y=Math.max(0,Math.floor((W-X.length)/2)),V=$.slice(0,Y),B=Y>0?$.slice(-Y):"";return`${V}${X}${B}`}function AR($,W,Z){if(j0($)<=W)return $;let Q=0,J=$.length,j=n8($,0,Z);while(Q<=J){let X=Q+J>>>1,Y=n8($,X,Z);if(j0(Y)<=W)j=Y,Q=X+1;else J=X-1}return j}function UR($){if($.type==="tool_use")return{...$,input:BZ($.input)};if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((W)=>C$(W)?BZ(W):{...W})}}function C$($){if($===null||typeof $!=="object")return!1;let W=$.type;return W!=="text"&&W!=="image"&&W!=="file"}function $J($){return $!==null&&typeof $==="object"&&$.type==="image"}function RG($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function ZJ($){return RG($)}function YZ($){if(typeof $==="string")return j0($);if(Array.isArray($)){let W=0;for(let Z of $)W+=YZ(Z);return W}if($!==null&&typeof $==="object"){if(ZJ($))return 0;let W=0;for(let Z of Object.values($))W+=YZ(Z);return W}return 0}function VZ($,W){if(Array.isArray($)){$.forEach((Z,Q)=>{if(typeof Z==="string")W.push({byteLength:j0(Z),minBytes:Z5,makeMarker:Q5,get:()=>$[Q],set:(J)=>{$[Q]=J}});else VZ(Z,W)});return}if($!==null&&typeof $==="object"){if(ZJ($))return;let Z=$;for(let Q of Object.keys(Z)){let J=Z[Q];if(typeof J==="string")W.push({byteLength:j0(J),minBytes:Z5,makeMarker:Q5,get:()=>Z[Q],set:(j)=>{Z[Q]=j}});else VZ(J,W)}}}function BZ($){if(Array.isArray($))return $.map(BZ);if($!==null&&typeof $==="object"){let W={};for(let[Z,Q]of Object.entries($))W[Z]=BZ(Q);return W}return $}function QJ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class JJ{messages=[];conversationId=QJ();sessionStarted=!1;constructor($){if(($?.length??0)>0)this.restore($??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage($){this.messages.push($)}appendMessages($){if($.length===0)return;this.messages.push(...$)}replaceMessages($){this.messages=[...$]}resetForRun(){this.messages=[],this.conversationId=QJ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=QJ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function EG($){let{agentConfig:W}=$,Z=DR(W),Q=_R(W),J=$.hooks,j=fR(W.maxParallelToolCalls);return{sessionId:$.sessionId??W.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??W.systemPrompt,messageModelInfo:Q,model:$.model,modelOptions:Z,tools:$.tools,hooks:J,prepareTurn:$.prepareTurn,consumePendingUserMessage:W.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??W.logger,telemetry:$.telemetry??W.telemetry,initialMessages:$.initialMessages,completionPolicy:W.completionPolicy,maxIterations:W.maxIterations,toolExecution:j,toolPolicies:W.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:W.requestToolApproval}}function DR($){let W={};if($.thinking!==void 0)W.thinking=$.thinking;if($.reasoningEffort!==void 0)W.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)W.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)W.maxTokensPerTurn=$.maxTokensPerTurn;if($.temperature!==void 0)W.temperature=$.temperature;if($.apiTimeoutMs!==void 0)W.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(W).length>0?W:void 0}function _R($){let W=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:W}}function fR($){if($===void 0)return;return $>=2?"parallel":"sequential"}var NG={};w(NG,{normalizeConnectionUpdate:()=>w2,buildConnectionUpdate:()=>jJ});function jJ($){let W={};if($.providerId!==void 0)W.providerId=$.providerId;if($.modelId!==void 0)W.modelId=$.modelId;if($.apiKey!==void 0)W.apiKey=$.apiKey;if($.baseUrl!==void 0)W.baseUrl=$.baseUrl;if($.headers!==void 0)W.headers=$.headers;if($.providerConfig!==void 0)W.providerConfig=$.providerConfig;if($.thinking===!1)return W.thinking=!1,W.reasoningEffort=null,W.thinkingBudgetTokens=null,W;if($.thinking===!0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort??null,W.thinkingBudgetTokens=null;else if($.reasoningEffort!==void 0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort;if(typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0,W.thinkingBudgetTokens=Math.trunc($.thinkingBudgetTokens);return W}function w2($){let W={...$},Z=Object.hasOwn($,"thinking"),Q=Object.hasOwn($,"thinkingBudgetTokens");if($.thinking===!1||$.thinking===null)return W.reasoningEffort=void 0,W.thinkingBudgetTokens=void 0,W;if(!Z&&Q&&typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0;return W}function LR(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function TR($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function XJ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(XJ);let W={};for(let Z of Object.keys($).sort())W[Z]=XJ($[Z]);return W}function OR($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(XJ($))}catch{return String($)}}function zR($,W,Z,Q){if(W===$.lastToolName&&Z===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=W,$.lastToolSignature=Z,{softWarning:$.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Q.hardThreshold}}var wG={softThreshold:3,hardThreshold:5};class YJ{config;state=LR();constructor($){this.config={softThreshold:$?.softThreshold??wG.softThreshold,hardThreshold:$?.hardThreshold??wG.hardThreshold}}inspect($){let W=OR($.input),Z=zR(this.state,$.name,W,this.config);if(Z.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Z.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){TR(this.state)}}class VJ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let W=this.options.maxConsecutiveMistakes,Z=$.forceAtLimit&&W?W:this.consecutiveMistakes+1;this.consecutiveMistakes=Z;let Q=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:Z,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!W||Z<W)return{action:"continue"};let J=await MR({iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details},this.options.onLimitReached);if(J.action==="continue"){let j=J.guidance?.trim();if(j)this.options.appendRecoveryNotice(j,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:j}}return{action:"stop",reason:J.reason?.trim()||void 0,message:qR({iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details,stopReason:J.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function qR($){let W=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Z=$.details?.trim();if(Z)W.push(`Error: ${Z}`);let Q=$.stopReason?.trim();if(Q)W.push(`Decision: ${Q}`);return W.push("Session state was preserved. Send a new prompt to resume from the latest state."),W.join(" ")}async function MR($,W){if(!W)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await W($)}catch(Z){return{action:"stop",reason:Z instanceof Error?Z.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function RR($){switch($){case"auto_compaction":case"manual_compaction":case"compaction_budget_emergency":return $;default:return}}function ER($){let W=$.content.filter((Z)=>Z.type==="text");if(W.length===0)return;return W.map((Z)=>Z.text).join("")}function NR($){let W=$.content.filter((Z)=>Z.type==="reasoning");if(W.length===0)return;return{reasoning:W.map((Z)=>Z.text).join(""),redacted:W.some((Z)=>Z.redacted===!0)}}function wR($){return $.content.find((W)=>W.type==="tool-result")}function CR($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function PR($){if(!$||$.isError!==!0)return;if(typeof $.output==="string")return $.output;if($.output instanceof Error)return $.output.message;try{return JSON.stringify($.output)}catch{return String($.output)}}class BJ{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:RR($.metadata?.reason),metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let W=[],Z=ER($);if(Z!==void 0)W.push({type:"content_end",contentType:"text",text:Z});let Q=NR($);if(Q!==void 0)W.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return W}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let W=this.toolStartedAt.get($.toolCall.toolCallId),Z=W===void 0?void 0:Date.now()-W;this.toolStartedAt.delete($.toolCall.toolCallId);let Q=wR($.message),J=Q?.output,j=PR(Q);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:J,error:j,durationMs:Z}]}translateUsage($){let W=$.inputTokens-this.lastUsage.inputTokens,Z=$.outputTokens-this.lastUsage.outputTokens,Q=$.cacheReadTokens-this.lastUsage.cacheReadTokens,J=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,j=this.lastUsage.totalCost??0,Y=($.totalCost??0)-j;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,W),outputTokens:Math.max(0,Z),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:J===0?void 0:Math.max(0,J),cost:Y===0?void 0:Y,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let W={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:CR($.status),text:$.outputText,iterations:$.iterations,usage:W}]}}function gR($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function mR($){let Z=(typeof $.content==="function"?await $.content():$.content).trim();return Z.length>0?Z:void 0}function vR($,W){let Z=$.trim(),Q=W.map((J)=>J.trim()).filter(Boolean).join(`
471
+ `;function RG($=process.env){return{maxToolResultChars:MG($[$J.maxToolResultChars]),maxTotalTextBytes:MG($[$J.maxTotalTextBytes]),minOutdatedRewriteBytes:FR($[$J.minOutdatedRewriteBytes])}}class ZJ{indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;maxToolResultChars;maxFileContentChars;maxTotalTextBytes;mediaBudget;maxAssistantTextChars;maxAssistantToolMarkupChars;minOutdatedRewriteBytes;committedOutdatedRewrites=new Map;constructor($={}){this.maxToolResultChars=W5($.maxToolResultChars,ZR),this.maxFileContentChars=W5($.maxFileContentChars,QR),this.maxTotalTextBytes=W5($.maxTotalTextBytes,JR),this.mediaBudget=$.mediaBudget??{},this.maxAssistantTextChars=W5($.maxAssistantTextChars,jR),this.maxAssistantToolMarkupChars=W5($.maxAssistantToolMarkupChars,XR),this.minOutdatedRewriteBytes=AR($.minOutdatedRewriteBytes,YR)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi($){this.reindex($),this.commitOutdatedRewrites($);let Z=this.addMissingToolResults($).map((J)=>{if(!Array.isArray(J.content)){if(J.role==="user"&&typeof J.content==="string"){let Y=fG(J.content);if(Y!==J.content)return{...J,content:Y}}if(J.role==="assistant"&&typeof J.content==="string"){let Y=this.truncateAssistantText(J.content);if(Y!==J.content)return{...J,content:Y}}return J}let j=!1,X=J.content.map((Y)=>{let V=this.transformBlock(Y,J.role);if(V!==Y)j=!0;return V});return j?{...J,content:X}:J}),Q=this.applyMediaBudget(Z);return this.truncateToTotalTextBudget(Q)}transformBlock($,W){if(W==="user"&&$.type==="text"&&typeof $.text==="string"){let J=fG($.text);if(J!==$.text)return{...$,text:J};return $}if(W==="assistant"&&$.type==="text"&&typeof $.text==="string"){let J=this.truncateAssistantText($.text);return J===$.text?$:{...$,text:J}}if($.type==="file"){let J=n8($.content,this.maxFileContentChars,OG);return J===$.content?$:{...$,content:J}}if($.type!=="tool_result")return $;let Z=this.resolveToolName($),Q=$.content;if(this.isReadTool(Z)&&$.is_error!==!0){let J=this.committedOutdatedRewrites.get($.tool_use_id);if(J&&J.size>0){let X=this.getReadLocators($).filter((Y)=>J.has(this.toReadLocatorKey(Y))&&this.isOutdatedReadLocator(Y,$.tool_use_id));if(X.length>0)Q=this.replaceOutdatedReadContent(Q,X)}}return Q=this.truncateToolResultContent(Q),Q===$.content?$:{...$,content:Q}}reindex($){let W=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!W)this.resetIndexes();for(let Z=this.indexedMessageCount;Z<$.length;Z++){let Q=$[Z];if(!Array.isArray(Q.content))continue;for(let J=0;J<Q.content.length;J++){let j=Q.content[J];if(j.type==="file")this.latestFullContentOwnerByPathCache.set(j.path,`file:${Z}:${J}`);else if(j.type==="tool_use"){let X=j.name.toLowerCase();if(this.toolNameByIdCache.set(j.id,X),this.isReadTool(X)){let Y=this.extractLocatorsFromReadToolInput(j.input);if(Y.length>0)this.readLocatorsByToolUseIdCache.set(j.id,Y)}}else if(j.type==="tool_result"){let X=this.resolveToolName(j);if(!this.isReadTool(X)||j.is_error===!0)continue;let Y=this.getReadLocators(j);for(let V of Y)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(V),j.tool_use_id),this.isFullFileRead(V))this.latestFullContentOwnerByPathCache.set(V.path,j.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}commitOutdatedRewrites($){let W=new Map,Z=new Set,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result"||j.is_error===!0)continue;let X=this.resolveToolName(j);if(!this.isReadTool(X))continue;Z.add(j.tool_use_id);let Y=this.committedOutdatedRewrites.get(j.tool_use_id),V=new Set,B=new Set;for(let G of this.getReadLocators(j)){let K=this.toReadLocatorKey(G);if(!this.isOutdatedReadLocator(G,j.tool_use_id))continue;if(B.add(K),!Y?.has(K))V.add(K)}if(Y){for(let G of Y)if(!B.has(G))Y.delete(G);if(Y.size===0)this.committedOutdatedRewrites.delete(j.tool_use_id)}if(V.size===0)continue;let H=W.get(j.tool_use_id);if(!H)H=new Set,W.set(j.tool_use_id,H);for(let G of V)H.add(G);Q+=this.estimateOutdatedReclaimBytes(j.content,V)}}for(let J of this.committedOutdatedRewrites.keys())if(!Z.has(J))this.committedOutdatedRewrites.delete(J);if(W.size===0||Q<this.minOutdatedRewriteBytes)return;for(let[J,j]of W){let X=this.committedOutdatedRewrites.get(J);if(!X)X=new Set,this.committedOutdatedRewrites.set(J,X);for(let Y of j)X.add(Y)}}estimateOutdatedReclaimBytes($,W){let Z=this.extractReadLocatorsFromToolResultContent($),Q=Z.length>0&&Z.every((V)=>W.has(this.toReadLocatorKey(V))),J=(V)=>{let B;try{B=JSON.parse(V)}catch{return Q||Z.length===0?j0(this.truncateMiddle(V)):0}let H=Array.isArray(B)?B:[B],G=0;for(let K of H){let F=this.extractLocatorFromResultEntry(K);if(F&&W.has(this.toReadLocatorKey(F)))G+=this.providerBoundEntryBytes(K)}return G};if(typeof $==="string")return J($);let j=new Set(W),X=0;for(let V of $)if(V.type==="text")X+=this.countOutdatedImageEntries(V.text,j);let Y=0;for(let V of $)if(V.type==="text")Y+=J(V.text);else if(V.type==="image"){if(X>0)X-=1,Y+=j0(V.data)}else if(C$(V)){let B=this.extractLocatorFromResultEntry(V);if(B&&W.has(this.toReadLocatorKey(B)))Y+=this.providerBoundEntryBytes(V)}else if(V.type==="file"){if(W.has(this.toReadLocatorKey({path:V.path,startLine:null,endLine:null})))Y+=j0(this.truncateMiddle(V.content))}return Y}providerBoundEntryBytes($){let W=this.truncateNestedStrings($);return j0(JSON.stringify(W))}addMissingToolResults($){let W=this.collectToolResultIds($),Z=[],Q=new Map,J=!1,j=()=>{if(Q.size===0)return;X(this.createMissingToolResultMessage(Q)),Q.clear(),J=!0},X=(Y)=>{let V=Z.at(-1);if(this.shouldMergeUserAfterToolResults(V,Y)){Z[Z.length-1]={...V,content:[...V.content,...this.contentBlocksForUserMerge(Y.content)]},J=!0;return}Z.push(Y)};for(let Y of $){if(this.isToolResultOnlyMessage(Y)){if(X(this.appendMissingToolResults(Y,Q)),Q.size>0)Q.clear(),J=!0;continue}if(Array.isArray(Y.content)){let V=Y.content.filter((H)=>H.type==="tool_result"),B=Y.content.filter((H)=>H.type!=="tool_result");if(V.length>0){let H=this.appendMissingToolResults({...Y,role:"user",content:V},Q);if(X(H),Q.size>0)Q.clear();J=!0}if(B.length>0||V.length===0){if(V.length===0)j();let H=V.length>0?{...Y,content:B}:Y;if(X(H),H.role==="assistant")this.trackMissingToolCalls(H,W,Q)}continue}j(),X(Y)}return j(),J?Z:$}appendMissingToolResults($,W){if(W.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(W)]}}shouldMergeUserAfterToolResults($,W){return $?.role==="user"&&W.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(W.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}return W}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}trackMissingToolCalls($,W,Z){if(!Array.isArray($.content))return;for(let Q of $.content){if(Q.type!=="tool_use"||W.has(Q.id))continue;Z.set(Q.id,Q.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([W,Z])=>({type:"tool_result",tool_use_id:W,name:Z,content:[{type:"text",text:this.formatMissingToolResultText(Z)}],is_error:!0}))}formatMissingToolResultText($){return $?`${TG} Tool: ${$}.`:TG}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let W=$,Z=this.readResultLocatorCache.get(W);if(Z===void 0)Z=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(W,Z);if(Z.length>0)return Z;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let W=$,Z=[],Q=this.extractLocatorFromReadRequest(W);if(Q)Z.push(Q);if(Array.isArray(W.files))for(let J of W.files){let j=this.extractLocatorFromReadRequest(J);if(j)Z.push(j)}if(Array.isArray(W.file_paths)){for(let J of W.file_paths)if(typeof J==="string"&&J.length>0)Z.push({path:J,startLine:null,endLine:null})}return this.dedupeReadLocators(Z)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);let W=[];for(let Z of $){if(Z.type==="text"){W.push(...this.tryParseReadLocators(Z.text));continue}if(C$(Z)){let Q=this.extractLocatorFromResultEntry(Z);if(Q)W.push(Q)}}return this.dedupeReadLocators(W)}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Z=[];for(let Q of $){let J=this.extractLocatorFromResultEntry(Q);if(J)Z.push(J)}return this.dedupeReadLocators(Z)}let W=this.extractLocatorFromResultEntry($);return W?[W]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(!Z)return;return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(Z)return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)};if(typeof W.query==="string"&&W.query.length>0)return this.parseReadQuery(W.query);return}extractPath($){let W=[$.path,$.file_path,$.filePath];for(let Z of W)if(typeof Z==="string"&&Z.length>0)return Z;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let W=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!W)return{path:$,startLine:null,endLine:null};return{path:W[1],startLine:Number(W[2]),endLine:W[3]==="EOF"?null:Number(W[3])}}dedupeReadLocators($){let W=new Map;for(let Z of $)W.set(this.toReadLocatorKey(Z),Z);return Array.from(W.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,W){let Z=this.latestFullContentOwnerByPathCache.get($.path);if(Z&&Z!==W)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==W}replaceOutdatedReadContent($,W){let Z=new Set(W.map((j)=>this.toReadLocatorKey(j))),Q=new Set(W.map((j)=>j.path));if(typeof $==="string")return this.replaceOutdatedInString($,Z)??N2;let J=0;for(let j of $)if(j.type==="text")J+=this.countOutdatedImageEntries(j.text,Z);return $.map((j)=>{if(j.type==="file"){if(!Q.has(j.path))return j;return{...j,content:N2}}if(j.type==="image"){if(J===0)return j;return J-=1,{type:"text",text:N2}}if(C$(j))return this.replaceOutdatedReadEntry(j,Z);if(j.type!=="text")return j;let X=this.replaceOutdatedInString(j.text,Z);if(X===null)return{...j,text:N2};return X===j.text?j:{...j,text:X}})}countOutdatedImageEntries($,W){let Z;try{Z=JSON.parse($)}catch{return 0}let Q=Array.isArray(Z)?Z:[Z],J=0;for(let j of Q){if(!j||typeof j!=="object")continue;let X=j,Y=this.extractLocatorFromResultEntry(X);if(!Y)continue;if(!W.has(this.toReadLocatorKey(Y)))continue;if(X.result==="Successfully read image"||X.content==="Successfully read image")J+=1}return J}replaceOutdatedInString($,W){let Z;try{Z=JSON.parse($)}catch{return null}let Q=Array.isArray(Z)?Z.map((J)=>this.replaceOutdatedReadEntry(J,W)):this.replaceOutdatedReadEntry(Z,W);return JSON.stringify(Q)}replaceOutdatedReadEntry($,W){if(!$||typeof $!=="object")return $;let Z=this.extractLocatorFromResultEntry($);if(!Z||!W.has(this.toReadLocatorKey(Z)))return $;let Q={...$};if(typeof Q.result==="string")Q.result=N2;else if(typeof Q.content==="string")Q.content=N2;else Q.result=N2;return Q}isReadTool($){return!!$&&BR.has($)}resolveToolName($){let W=this.toolNameByIdCache.get($.tool_use_id);if(W!==void 0)return W;return typeof $.name==="string"&&$.name.length>0?$.name.toLowerCase():void 0}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((W)=>{if(W.type==="file"){let Z=this.truncateMiddle(W.content);return Z===W.content?W:{...W,content:Z}}if(W.type==="text"){let Z=this.truncateMiddle(W.text);return Z===W.text?W:{...W,text:Z}}if(C$(W))return this.truncateNestedStrings(W);return W})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let W=!1,Z=$.map((Q)=>{let J=this.truncateNestedStrings(Q);if(J!==Q)W=!0;return J});return W?Z:$}if($!==null&&typeof $==="object"){if(QJ($))return $;let W=!1,Z={};for(let[Q,J]of Object.entries($)){let j=this.truncateNestedStrings(J);if(j!==J)W=!0;Z[Q]=j}return W?Z:$}return $}truncateMiddle($){return n8($,this.maxToolResultChars,OG)}truncateAssistantText($){if(this.hasRepeatedToolCallMarkup($))return n8($,this.maxAssistantToolMarkupChars,GR);return n8($,this.maxAssistantTextChars,HR)}hasRepeatedToolCallMarkup($){if($.length<=this.maxAssistantToolMarkupChars)return!1;let W=0;for(let Z of $.matchAll(KR))if(W+=1,W>=VR)return!0;return!1}truncateToTotalTextBudget($){let W=this.countMessageTextBytes($);if(W<=this.maxTotalTextBytes)return $;let Z=$.map((J)=>{if(!Array.isArray(J.content))return{...J};return{...J,content:J.content.map((j)=>DR(j))}}),Q=this.collectTruncationCandidates(Z);for(let J of Q){if(W<=this.maxTotalTextBytes)break;let j=J.byteLength;if(j<=J.minBytes)continue;let X=W-this.maxTotalTextBytes,Y=Math.max(J.minBytes,j-X),V=UR(J.get(),Y,J.makeMarker);J.set(V),W-=j-j0(V)}return Z}countMessageTextBytes($){let W=0;for(let Z of $){if(typeof Z.content==="string"){W+=j0(Z.content);continue}for(let Q of Z.content)if(Q.type==="text")W+=j0(Q.text);else if(Q.type==="thinking")W+=j0(Q.thinking);else if(Q.type==="file")W+=j0(Q.content);else if(Q.type==="tool_use")W+=VZ(Q.input);else if(Q.type==="tool_result"){if(typeof Q.content==="string")W+=j0(Q.content);else for(let J of Q.content)if(J.type==="text")W+=j0(J.text);else if(J.type==="file")W+=j0(J.content);else if(C$(J))W+=VZ(J)}}return W}collectTruncationCandidates($){let W=[],Z=[];for(let Q of $){if(Q.role==="assistant"&&typeof Q.content==="string"){W.push({byteLength:j0(Q.content),minBytes:LG,makeMarker:zG,get:()=>Q.content,set:(J)=>{Q.content=J}});continue}if(!Array.isArray(Q.content))continue;for(let J of Q.content){if(J.type==="tool_use"){BZ(J.input,Z);continue}if(Q.role==="assistant"&&J.type==="text"){W.push({byteLength:j0(J.text),minBytes:LG,makeMarker:zG,get:()=>J.text,set:(j)=>{J.text=j}});continue}if(J.type!=="tool_result")continue;if(typeof J.content==="string"){W.push({byteLength:j0(J.content),minBytes:Z5,makeMarker:Q5,get:()=>J.content,set:(j)=>{J.content=j}});continue}for(let j of J.content)if(j.type==="text")W.push({byteLength:j0(j.text),minBytes:Z5,makeMarker:Q5,get:()=>j.text,set:(X)=>{j.text=X}});else if(j.type==="file")W.push({byteLength:j0(j.content),minBytes:Z5,makeMarker:Q5,get:()=>j.content,set:(X)=>{j.content=X}});else if(C$(j))BZ(j,W)}}return W.sort((Q,J)=>J.byteLength-Q.byteLength),Z.sort((Q,J)=>J.byteLength-Q.byteLength),[...W,...Z]}applyMediaBudget($){let W=this.resolveMediaBudget();if(W.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&W.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&W.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Z=eM(),Q=!1,J=$.map((j)=>{if(!Array.isArray(j.content))return j;let X=!1,Y=j.content.map((V)=>{let B=this.applyMediaBudgetToBlock(V,W,Z);if(B!==V)X=!0;return B});if(!X)return j;return Q=!0,{...j,content:Y}});return Q?J:$}resolveMediaBudget(){return $R(this.mediaBudget)}applyMediaBudgetToBlock($,W,Z){if(WJ($))return this.limitImageContent($,W,Z);if($.type!=="tool_result"||typeof $.content==="string")return $;let Q=!1,J=$.content.map((j)=>{let X=this.applyMediaBudgetToToolResultEntry(j,W,Z);if(X!==j)Q=!0;return X});return Q?{...$,content:J}:$}applyMediaBudgetToToolResultEntry($,W,Z){if(WJ($))return this.limitImageContent($,W,Z);if(C$($))return this.limitNestedMedia($,W,Z);return $}limitNestedMedia($,W,Z){if(WJ($)){let Q=this.limitImageContent($,W,Z);return Q.type==="text"?Q.text:Q}if(Array.isArray($)){let Q=!1,J=$.map((j)=>{let X=this.limitNestedMedia(j,W,Z);if(X!==j)Q=!0;return X});return Q?J:$}if($!==null&&typeof $==="object"){let Q=!1,J={};for(let[j,X]of Object.entries($)){let Y=this.limitNestedMedia(X,W,Z);if(Y!==X)Q=!0;J[j]=Y}return Q?J:$}return $}limitImageContent($,W,Z){if(!EG($))return{type:"text",text:_G};let Q=WR($.mediaType,$.data,{maxImageEncodedBytes:W.maxImageEncodedBytes,maxImageDecodedBytes:W.maxImageDecodedBytes,maxTotalMediaBytes:W.maxTotalMediaBytes},Z);if(!Q.ok)return{type:"text",text:_G};return{...$,data:Q.base64,mediaType:Q.mediaType}}}var qG=String.raw`[\|\uFF5C]`,KR=new RegExp(String.raw`<\s*(?:${qG}\s*)?DSML\s*(?:${qG}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function j0($){return Buffer.byteLength($,"utf8")}function MG($){if($===void 0)return;let W=Number.parseInt($,10);return Number.isFinite(W)&&W>0?W:void 0}function FR($){if($===void 0)return;let W=$.trim().toLowerCase();if(W==="infinity"||W==="disable")return Number.POSITIVE_INFINITY;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>=0?Z:void 0}function W5($,W){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):W}function AR($,W){if(typeof $!=="number"||Number.isNaN($)||$<0)return W;return Number.isFinite($)?Math.floor($):$}function n8($,W,Z){if($.length<=W)return $;let Q=Z($.length-W),J=Math.max(0,Math.floor((W-Q.length)/2)),j=Math.max(0,$.length-J*2),X=Z(j),Y=Math.max(0,Math.floor((W-X.length)/2)),V=$.slice(0,Y),B=Y>0?$.slice(-Y):"";return`${V}${X}${B}`}function UR($,W,Z){if(j0($)<=W)return $;let Q=0,J=$.length,j=n8($,0,Z);while(Q<=J){let X=Q+J>>>1,Y=n8($,X,Z);if(j0(Y)<=W)j=Y,Q=X+1;else J=X-1}return j}function DR($){if($.type==="tool_use")return{...$,input:HZ($.input)};if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((W)=>C$(W)?HZ(W):{...W})}}function C$($){if($===null||typeof $!=="object")return!1;let W=$.type;return W!=="text"&&W!=="image"&&W!=="file"}function WJ($){return $!==null&&typeof $==="object"&&$.type==="image"}function EG($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function QJ($){return EG($)}function VZ($){if(typeof $==="string")return j0($);if(Array.isArray($)){let W=0;for(let Z of $)W+=VZ(Z);return W}if($!==null&&typeof $==="object"){if(QJ($))return 0;let W=0;for(let Z of Object.values($))W+=VZ(Z);return W}return 0}function BZ($,W){if(Array.isArray($)){$.forEach((Z,Q)=>{if(typeof Z==="string")W.push({byteLength:j0(Z),minBytes:Z5,makeMarker:Q5,get:()=>$[Q],set:(J)=>{$[Q]=J}});else BZ(Z,W)});return}if($!==null&&typeof $==="object"){if(QJ($))return;let Z=$;for(let Q of Object.keys(Z)){let J=Z[Q];if(typeof J==="string")W.push({byteLength:j0(J),minBytes:Z5,makeMarker:Q5,get:()=>Z[Q],set:(j)=>{Z[Q]=j}});else BZ(J,W)}}}function HZ($){if(Array.isArray($))return $.map(HZ);if($!==null&&typeof $==="object"){let W={};for(let[Z,Q]of Object.entries($))W[Z]=HZ(Q);return W}return $}function JJ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class jJ{messages=[];conversationId=JJ();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=JJ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=JJ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function NG($){let{agentConfig:W}=$,Z=_R(W),Q=fR(W),J=$.hooks,j=LR(W.maxParallelToolCalls);return{sessionId:$.sessionId??W.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??W.systemPrompt,messageModelInfo:Q,model:$.model,modelOptions:Z,tools:$.tools,hooks:J,prepareTurn:$.prepareTurn,consumePendingUserMessage:W.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??W.logger,telemetry:$.telemetry??W.telemetry,initialMessages:$.initialMessages,completionPolicy:W.completionPolicy,maxIterations:W.maxIterations,toolExecution:j,toolPolicies:W.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:W.requestToolApproval}}function _R($){let W={};if($.thinking!==void 0)W.thinking=$.thinking;if($.reasoningEffort!==void 0)W.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)W.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)W.maxTokensPerTurn=$.maxTokensPerTurn;if($.temperature!==void 0)W.temperature=$.temperature;if($.apiTimeoutMs!==void 0)W.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(W).length>0?W:void 0}function fR($){let W=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:W}}function LR($){if($===void 0)return;return $>=2?"parallel":"sequential"}var wG={};w(wG,{normalizeConnectionUpdate:()=>w2,buildConnectionUpdate:()=>XJ});function XJ($){let W={};if($.providerId!==void 0)W.providerId=$.providerId;if($.modelId!==void 0)W.modelId=$.modelId;if($.apiKey!==void 0)W.apiKey=$.apiKey;if($.baseUrl!==void 0)W.baseUrl=$.baseUrl;if($.headers!==void 0)W.headers=$.headers;if($.providerConfig!==void 0)W.providerConfig=$.providerConfig;if($.thinking===!1)return W.thinking=!1,W.reasoningEffort=null,W.thinkingBudgetTokens=null,W;if($.thinking===!0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort??null,W.thinkingBudgetTokens=null;else if($.reasoningEffort!==void 0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort;if(typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0,W.thinkingBudgetTokens=Math.trunc($.thinkingBudgetTokens);return W}function w2($){let W={...$},Z=Object.hasOwn($,"thinking"),Q=Object.hasOwn($,"thinkingBudgetTokens");if($.thinking===!1||$.thinking===null)return W.reasoningEffort=void 0,W.thinkingBudgetTokens=void 0,W;if(!Z&&Q&&typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0;return W}function TR(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function OR($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function YJ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(YJ);let W={};for(let Z of Object.keys($).sort())W[Z]=YJ($[Z]);return W}function zR($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(YJ($))}catch{return String($)}}function qR($,W,Z,Q){if(W===$.lastToolName&&Z===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=W,$.lastToolSignature=Z,{softWarning:$.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Q.hardThreshold}}var CG={softThreshold:3,hardThreshold:5};class VJ{config;state=TR();constructor($){this.config={softThreshold:$?.softThreshold??CG.softThreshold,hardThreshold:$?.hardThreshold??CG.hardThreshold}}inspect($){let W=zR($.input),Z=qR(this.state,$.name,W,this.config);if(Z.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Z.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){OR(this.state)}}class BJ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let W=this.options.maxConsecutiveMistakes,Z=$.forceAtLimit&&W?W:this.consecutiveMistakes+1;this.consecutiveMistakes=Z;let Q=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:Z,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!W||Z<W)return{action:"continue"};let J={iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details};this.options.onLimitTelemetry?.(J);let j=await RR(J,this.options.onLimitReached);if(j.action==="continue"){let X=j.guidance?.trim();if(X)this.options.appendRecoveryNotice(X,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:X}}return{action:"stop",reason:j.reason?.trim()||void 0,message:MR({iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details,stopReason:j.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function MR($){let W=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Z=$.details?.trim();if(Z)W.push(`Error: ${Z}`);let Q=$.stopReason?.trim();if(Q)W.push(`Decision: ${Q}`);return W.push("Session state was preserved. Send a new prompt to resume from the latest state."),W.join(" ")}async function RR($,W){if(!W)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await W($)}catch(Z){return{action:"stop",reason:Z instanceof Error?Z.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function ER($){switch($){case"auto_compaction":case"manual_compaction":case"compaction_budget_emergency":return $;default:return}}function NR($){let W=$.content.filter((Z)=>Z.type==="text");if(W.length===0)return;return W.map((Z)=>Z.text).join("")}function wR($){let W=$.content.filter((Z)=>Z.type==="reasoning");if(W.length===0)return;return{reasoning:W.map((Z)=>Z.text).join(""),redacted:W.some((Z)=>Z.redacted===!0)}}function CR($){return $.content.find((W)=>W.type==="tool-result")}function PR($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function SR($){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 HJ{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:ER($.metadata?.reason),metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let W=[],Z=NR($);if(Z!==void 0)W.push({type:"content_end",contentType:"text",text:Z});let Q=wR($);if(Q!==void 0)W.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return W}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let W=this.toolStartedAt.get($.toolCall.toolCallId),Z=W===void 0?void 0:Date.now()-W;this.toolStartedAt.delete($.toolCall.toolCallId);let Q=CR($.message),J=Q?.output,j=SR(Q);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:J,error:j,durationMs:Z}]}translateUsage($){let W=$.inputTokens-this.lastUsage.inputTokens,Z=$.outputTokens-this.lastUsage.outputTokens,Q=$.cacheReadTokens-this.lastUsage.cacheReadTokens,J=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,j=this.lastUsage.totalCost??0,Y=($.totalCost??0)-j;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,W),outputTokens:Math.max(0,Z),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:J===0?void 0:Math.max(0,J),cost:Y===0?void 0:Y,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let W={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:PR($.status),text:$.outputText,iterations:$.iterations,usage:W}]}}function mR($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function vR($){let Z=(typeof $.content==="function"?await $.content():$.content).trim();return Z.length>0?Z:void 0}function cR($,W){let Z=$.trim(),Q=W.map((J)=>J.trim()).filter(Boolean).join(`
472
472
 
473
473
  `);if(Z&&Q)return`${Z}
474
474
 
475
- ${Q}`;return Z||Q}function cR($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function uR($,W){return $.filter((Z)=>cR(Z.name,W))}function dR($,W){return u1(uR($,W))}function lR($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return{};return{beforeRun:async(Z)=>{for(let Q of W){let J=await Q.beforeRun?.(Z);if(J?.stop)return J}return},afterRun:async(Z)=>{for(let Q of W)await Q.afterRun?.(Z)},beforeModel:async(Z)=>{let Q=Z.request,J;for(let j of W){let X=await j.beforeModel?.({...Z,request:Q});if(!X)continue;if(X.stop)return X;J={...J,...X,options:PG(J?.options,X.options)},Q={...Q,...X.messages?{messages:X.messages}:{},...X.tools?{tools:X.tools}:{},...X.options?{options:PG(Q.options,X.options)}:{}}}return J},afterModel:async(Z)=>{for(let Q of W){let J=await Q.afterModel?.(Z);if(J?.stop)return J}return},beforeTool:async(Z)=>{let Q=Z.input,J;for(let j of W){let X=await j.beforeTool?.({...Z,input:Q});if(!X)continue;if(X.stop||X.skip)return X;if(J={...J,...X},Object.hasOwn(X,"input"))Q=X.input}return J},afterTool:async(Z)=>{let Q=Z.result,J;for(let j of W){let X=await j.afterTool?.({...Z,result:Q});if(!X)continue;if(X.stop)return X;if(J={...J,...X},X.result)Q=X.result}return J},onEvent:async(Z)=>{for(let Q of W)await Q.onEvent?.(Z)}}}class P${config;agentId;parentAgentId;logger;telemetry;conversation;mistakeTracker;loopTracker;loopDetectionDisabled;messageBuilder;contributionRegistry;extensionsInitialized=!1;listeners=new Set;createAgentRuntimeImpl;activeRunId=null;running=!1;abortRequested=!1;abortReason;activeRuntime=null;activeRunPromise=null;eventAdapter=new BJ;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,W={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=W.logger??$.logger,this.telemetry=W.telemetry??$.telemetry,this.createAgentRuntimeImpl=W.createAgentRuntimeImpl??IR,this.conversation=new JJ($.initialMessages),this.messageBuilder=new WJ(MG()),this.contributionRegistry=xR({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let Z=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new VJ({maxConsecutiveMistakes:Z,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(j)=>this.emitLegacyEvent(j),log:(j,X,Y)=>pR(this.logger,j,X,Y),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,X)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let J=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new YJ(J)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let W=new Set(this.config.tools.map((Q)=>Q.name)),Z=[...this.config.tools];for(let Q of $)if(!W.has(Q.name))Z.push(Q),W.add(Q.name);this.config={...this.config,tools:Z}}updateConnection($){let W=w2($),Z={...this.config};if(W.providerId!==void 0)Z.providerId=W.providerId;if(W.modelId!==void 0)Z.modelId=W.modelId;if(W.apiKey!==void 0)Z.apiKey=W.apiKey;if(W.baseUrl!==void 0)Z.baseUrl=W.baseUrl;if(W.headers!==void 0)Z.headers=W.headers;if(W.providerConfig!==void 0)Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"reasoningEffort"))Z.reasoningEffort=W.reasoningEffort??void 0;if(Object.hasOwn(W,"thinkingBudgetTokens"))Z.thinkingBudgetTokens=W.thinkingBudgetTokens??void 0;if(Object.hasOwn(W,"thinking")){if(Z.thinking=W.thinking??void 0,W.thinking===!1||W.thinking===null)Z.reasoningEffort=void 0,Z.thinkingBudgetTokens=void 0}this.config=Z}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.messageBuilder.resetConversationState(),this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let W=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=W,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(W)}async shutdown($,W){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,W,Z){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!1})}continue($,W,Z){return this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let W of this.contributionRegistry.getRegisteredRules()){let Z=await mR(W);if(Z)$.push(Z)}return vR(this.config.systemPrompt,$)}executeRun($){let W;return W=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===W)this.activeRunPromise=null}),this.activeRunPromise=W,W}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let W=new Date,Z=$.userMessage;if(Z!==void 0){let _=await iR(Z,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:_})}let Q=await this.composeSystemPrompt(),J=UG(this.config,this.logger,this.telemetry),j=new Map;for(let _ of this.contributionRegistry.getRegisteredTools())j.set(_.name,_);let X=dR([...j.values()],this.config.toolPolicies),Y=new Map;for(let _ of X)Y.set(_.name,_);for(let _ of this.config.tools)Y.set(_.name,_);let V=this.conversation.getConversationId(),B=SG(this.config),H=Array.from(Y.values()),G=jZ(this.conversation.getMessages()),K=EG({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:V,parentAgentId:this.parentAgentId,model:J,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:B?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[iW]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(B,H),initialMessages:G,systemPrompt:Q}),F=this.createAgentRuntimeImpl(K);if(this.activeRuntime=F,this.abortRequested)F.abort(this.abortReason);let A=F.subscribe((_)=>{this.handleRuntimeEvent(_)}),D,U;try{if($.isContinue)D=await F.continue(void 0);else D=await F.run("")}catch(_){U=_ instanceof Error?_:Error(String(_))}finally{A();try{await this.activeTrackerWork}catch(_){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:_})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(D&&D.messages.length>0){let _=i8(D.messages);this.conversation.replaceMessages(_)}let f=new Date;try{return this.buildLegacyResult({runResult:D,thrownError:U,startedAt:W,endedAt:f})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize({tolerateSetupErrors:this.config.hookErrorMode!=="throw"})}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=lR([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((W)=>W.hooks)]);return{...$,beforeModel:async(W)=>{let Z=await $.beforeModel?.(W);if(Z?.stop)return Z;let Q=Z?.messages??W.request.messages,J=await this.prepareMessagesForModelRequest(Q);return{...Z,messages:J}}}}createRuntimePrepareTurn($,W){let Z=this.config.prepareTurn;if(!Z)return;return async(Q)=>{let J=i8(Q.messages),j=await this.prepareProviderMessagesForApi(J),X=await Z({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:J,apiMessages:j,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:W,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!X)return;return{...X.messages?{messages:jZ(X.messages)}:{},...X.systemPrompt!==void 0?{systemPrompt:X.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let W=await this.prepareProviderMessagesForApi(XZ($));return jZ(W)}async prepareProviderMessagesForApi($){let W=$,Z=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of Z)W=await Q.build(W);return this.messageBuilder.buildForApi(W)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let W=this.toolStartedAt.get($.toolCall.toolCallId),Z=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let J=$.message.content.find((V)=>V.type==="tool-result"),j=J?.type==="tool-result"&&J.isError===!0,X=j?gR(J?.type==="tool-result"?J.output:void 0):void 0,Y={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:J?.type==="tool-result"?J.output:void 0,error:X,durationMs:W===void 0?0:Z.getTime()-W.getTime(),startedAt:W??Z,endedAt:Z};if(this.currentRunToolCalls.push(Y),j){if(this.currentTurnFailedTools+=1,X)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${X}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let W=this.currentTurnFailedTools,Z=this.currentTurnSuccessfulTools;if(W>0&&Z===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${W} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(Z>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let W of this.eventAdapter.translate($))this.emitLegacyEvent(W)}syncConversationFromRuntimeMessage($,W){if($.length>0){this.conversation.replaceMessages(i8($));return}if(W.length===0)return;let Z=new Set(this.conversation.getMessages().map((J)=>J.id).filter((J)=>typeof J==="string")),Q=i8(W).filter((J)=>!J.id||!Z.has(J.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let W of this.listeners)try{W($)}catch(Z){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Z})}}inspectLoopForToolCall($,W,Z){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:W});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:Z,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let W=await this.mistakeTracker.record($);if(W.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]}),this.activeRuntime?.abort(W.reason??W.message)})}buildLegacyResult($){let{runResult:W,thrownError:Z,startedAt:Q,endedAt:J}=$,j=J.getTime()-Q.getTime(),X=Z?"error":rR(W),Y=(W?.status==="failed"?W.error?.message:void 0)||W?.outputText||"",V=W?{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens>0?W.usage.cacheReadTokens:void 0,cacheWriteTokens:W.usage.cacheWriteTokens>0?W.usage.cacheWriteTokens:void 0,totalCost:W.usage.totalCost}:this.currentRunUsage,B=W?i8(W.messages):this.conversation.getMessages(),H=SG(this.config);if(Z)throw Z;return{text:Y,usage:V,messages:B,toolCalls:this.currentRunToolCalls,iterations:W?.iterations??0,finishReason:X,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Q,endedAt:J,durationMs:j}}}function pR($,W,Z,Q){if(!$)return;if(W==="debug"){$.debug(Z,Q);return}if(W==="error"&&$.error){$.error(Z,Q);return}let J=W==="warn"?"warn":W==="error"?"error":"info";$.log(Z,{...Q,severity:J})}function rR($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function iR($,W,Z,Q){let{buildInitialUserContent:J}=await Promise.resolve().then(() => CG);return J($,W,Z,Q)}function SG($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let W=t3($);if(W?.[$.modelId])return W[$.modelId];return}import{buildClineSystemPrompt as bG}from"@cline/shared";function yG($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return bG({ide:W.clineIdeName?.trim()||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,rules:`# Team Teammate Role
476
- ${Z}`,platform:W.clinePlatform,metadata:W.workspaceMetadata})}function hG($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return bG({ide:W.clineIdeName||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,overridePrompt:Z,metadata:W.workspaceMetadata,platform:W.clinePlatform})}function S$($){let W={...$};return{getRuntimeConfig:()=>W,getConnectionConfig:()=>({providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,temperature:W.temperature}),updateConnectionDefaults:(Z)=>{W={...W,...Z}}}}function C2($){let W=$.configProvider.getRuntimeConfig(),Z=$.kind==="teammate"?yG($.prompt,W):hG($.prompt,W);return{...$.configProvider.getConnectionConfig(),systemPrompt:Z,tools:$.tools,maxIterations:$.maxIterations??W.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:W.hooks,extensions:W.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:W.logger,role:$.role}}function b$($){let W=C2($),Z=new P$(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);return Z}var oR=HJ.object({systemPrompt:HJ.string().describe("System prompt defining the sub-agent's behavior"),task:HJ.string().describe("Task for the sub-agent to complete")});function y$($){return nR({name:"spawn_agent",description:"Spawn a sub-agent with a custom system prompt for specialized tasks. Use when delegating work that benefits from focused expertise.",inputSchema:aR(oR),execute:async(W,Z)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(W,Z):$.subAgentTools??[],J=b$({kind:"subagent",prompt:W.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:Z.agentId,abortSignal:Z.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=J.getAgentId(),X=J.getConversationId(),Y=Z.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:X,parentAgentId:Y,input:W})}catch{}try{let V=await J.run(W.task),B={text:V.text,iterations:V.iterations,finishReason:V.finishReason,usage:{inputTokens:V.usage.inputTokens,outputTokens:V.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,result:B,agentResult:V})}catch{}return B}catch(V){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,error:V instanceof Error?V:Error(String(V))})}catch{}throw V}},timeoutMs:300000,retryable:!1})}import{createTool as _0,TEAM_AWAIT_TIMEOUT_MS as sR,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as tR,TEAM_RUN_TEXT_PREVIEW_LIMIT as eR,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as $E,TeamAttachOutcomeFragmentInputSchema as kG,TeamAwaitRunsInputSchema as IG,TeamBroadcastInputSchema as xG,TeamBroadcastToolResultSchema as WE,TeamCancelRunInputSchema as gG,TeamCancelRunToolResultSchema as ZE,TeamCleanupInputSchema as mG,TeamCleanupToolResultSchema as QE,TeamCreateOutcomeInputSchema as vG,TeamCreateOutcomeToolResultSchema as JE,TeamFinalizeOutcomeInputSchema as cG,TeamFinalizeOutcomeToolResultSchema as jE,TeamListOutcomesInputSchema as uG,TeamListRunsInputSchema as dG,TeamMailboxMessageToolResultSchema as XE,TeamMissionLogInputSchema as lG,TeamMissionLogToolResultSchema as YE,TeamOutcomeFragmentToolResultSchema as pG,TeamOutcomeToolResultSchema as VE,TeamReadMailboxInputSchema as rG,TeamReviewOutcomeFragmentInputSchema as iG,TeamRunTaskInputSchema as nG,TeamRunTaskToolResultSchema as GJ,TeamRunToolSummarySchema as KJ,TeamSendMessageInputSchema as aG,TeamSendMessageToolResultSchema as BE,TeamShutdownTeammateInputSchema as oG,TeamSimpleAgentStatusToolResultSchema as sG,TeamSpawnTeammateInputSchema as tG,TeamStatusInputSchema as eG,TeamStatusToolResultSchema as HE,TeamTaskInputSchema as $K,TeamTaskToolResultSchema as J5,validateWithZod as g,zodToJsonSchema as f0}from"@cline/shared";function WK($,W){let Z=$.replace(/\s+/g," ").trim();if(Z.length<=W)return Z;return`${Z.slice(0,Math.max(0,W-3)).trimEnd()}...`}function P2($,W){if($===void 0)throw Error(`Missing required field: ${W}`);return $}function GE($){let W=$.result;if(!W)return;return{textPreview:WK(W.text,eR),iterations:W.iterations,finishReason:W.finishReason,durationMs:W.durationMs,usage:{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens,cacheWriteTokens:W.usage.cacheWriteTokens,totalCost:W.usage.totalCost}}}function HZ($){return $?.toISOString()}function FJ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:WK($.message,tR),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:HZ($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:HZ($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:HZ($.heartbeatAt),lastProgressAt:HZ($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:GE($)}}function KE($){if($.status==="failed")throw Error(`Run "${$.id}" failed${$.error?`: ${$.error}`:""}`);if($.status==="cancelled")throw Error(`Run "${$.id}" was cancelled${$.error?`: ${$.error}`:""}`);if($.status==="interrupted")throw Error(`Run "${$.id}" was interrupted${$.error?`: ${$.error}`:""}`)}var a8=["team_spawn_teammate","team_shutdown_teammate","team_status","team_task","team_run_task","team_cancel_run","team_list_runs","team_await_runs","team_send_message","team_broadcast","team_read_mailbox","team_mission_log","team_cleanup","team_create_outcome","team_attach_outcome_fragment","team_review_outcome_fragment","team_finalize_outcome","team_list_outcomes"];function ZK($){let W=[];if($.createBaseTools)W.push(...$.createBaseTools());W.push(...S2({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:C2({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:W,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function o8($){let W=$.leadAgentId??"lead",Z=$.restoredFromPersistence===!0,Q=S2({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),J=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;ZK({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),J.push(j.agentId)}return{tools:Q,restoredFromPersistence:Z,restoredTeammates:J}}function S2($){let W=$.allowSpawn??!0,Z=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,J=[];if(Z)J.push(_0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:f0(tG),execute:async(X)=>{let Y=g(tG,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!W)throw Error("Spawning teammates is disabled in this context.");let V={agentId:Y.agentId,rolePrompt:Y.rolePrompt};if(ZK({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:V}),!Q)$.onLeadToolsUnlocked?.(S2({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return g(sG,{agentId:Y.agentId,status:"spawned"})}}));if(!Q)return J;J.push(_0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:f0(oG),execute:async(X)=>{let Y=g(oG,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(Y.agentId,Y.reason),g(sG,{agentId:Y.agentId,status:"stopped"})}})),J.push(_0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:f0(eG),execute:async(X)=>{return g(eG,X),g(HE,$.runtime.getSnapshot())}})),J.push(_0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:f0($K),execute:async(X)=>{let Y=g($K,X);switch(Y.action){case"create":{let V=new Set($E.create??[]),B=Object.entries(X).filter(([G,K])=>V.has(G)&&K!=null).map(([G])=>G),H=$.runtime.createTask({title:P2(Y.title,"title"),description:P2(Y.description,"description"),dependsOn:Y.dependsOn,assignee:Y.assignee,createdBy:$.requesterId});return g(J5,{action:"create",taskId:H.id,status:H.status,...B.length>0?{ignoredFields:B,note:`Ignored fields for action=create: ${B.join(", ")}`}:{}})}case"list":return g(J5,{action:"list",tasks:$.runtime.listTaskItems({status:Y.status,assignee:Y.assignee})});case"claim":{let V=$.runtime.claimTask(P2(Y.taskId,"taskId"),$.requesterId);return g(J5,{action:"claim",taskId:V.id,status:V.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let V=$.runtime.completeTask(P2(Y.taskId,"taskId"),$.requesterId,P2(Y.summary,"summary"));return g(J5,{action:"complete",taskId:V.id,status:V.status})}case"block":{let V=$.runtime.blockTask(P2(Y.taskId,"taskId"),$.requesterId,P2(Y.reason,"reason"));return g(J5,{action:"block",taskId:V.id,status:V.status})}}}}));let j=new Map;return J.push(_0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:f0(nG),execute:async(X)=>{let Y=g(nG,X);if(Y.runMode==="async"){let H=$.runtime.startTeammateRun(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0});return g(GJ,{agentId:Y.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${Y.agentId} and queued as ${H.id}.`,runId:H.id})}let V=j.get(Y.agentId);if(V){let H=await V;return g(GJ,{...H,status:"joined",deduped:!0,message:`Task for ${Y.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let B=$.runtime.routeToTeammate(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0}).then((H)=>g(GJ,{agentId:Y.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${Y.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(Y.agentId)});return j.set(Y.agentId,B),await B}})),J.push(_0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:f0(gG),execute:async(X)=>{let Y=g(gG,X),V=$.runtime.cancelRun(Y.runId,Y.reason);return g(ZE,{runId:V.id,status:V.status})}})),J.push(_0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:f0(dG),execute:async(X)=>g(KJ.array(),$.runtime.listRuns(g(dG,X)).map(FJ))})),J.push(_0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:f0(IG),timeoutMs:sR,execute:async(X)=>{let Y=g(IG,X);if(Y.runId){let H=await $.runtime.awaitRun(Y.runId);return KE(H),g(KJ,FJ(H))}let V=await $.runtime.awaitAllRuns(),B=V.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(B.length>0){let H=B.map((G)=>`${G.id}:${G.status}${G.error?`(${G.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return g(KJ.array(),V.map(FJ))}})),J.push(_0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:f0(aG),execute:async(X)=>{let Y=g(aG,X),V=$.runtime.sendMessage($.requesterId,Y.toAgentId,Y.subject,Y.body,Y.taskId??void 0);return g(BE,{id:V.id,toAgentId:V.toAgentId})}})),J.push(_0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:f0(xG),execute:async(X)=>{let Y=g(xG,X),V=$.runtime.broadcast($.requesterId,Y.subject,Y.body,{taskId:Y.taskId??void 0});return g(WE,{delivered:V.length})}})),J.push(_0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:f0(rG),execute:async(X)=>{let Y=g(rG,X);return g(XE.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:Y.unreadOnly,markRead:!0}))}})),J.push(_0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:f0(lG),execute:async(X)=>{let Y=g(lG,X),V=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:Y.taskId||void 0,kind:Y.kind,summary:Y.summary,evidence:Y.evidence?.length?Y.evidence:void 0,nextAction:Y.nextAction||void 0});return g(YE,{id:V.id})}})),J.push(_0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:f0(mG),execute:async(X)=>{if(g(mG,X),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),g(QE,{status:"cleaned"})}})),J.push(_0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:f0(vG),execute:async(X)=>{let Y=g(vG,X),V=$.runtime.createOutcome({title:Y.title,requiredSections:Y.requiredSections,createdBy:$.requesterId});return g(JE,{outcomeId:V.id,status:V.status,requiredSections:V.requiredSections})}})),J.push(_0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:f0(kG),execute:async(X)=>{let Y=g(kG,X),V=$.runtime.attachOutcomeFragment({outcomeId:Y.outcomeId,section:Y.section,sourceAgentId:$.requesterId,sourceRunId:Y.sourceRunId||void 0,content:Y.content});return g(pG,{fragmentId:V.id,status:V.status})}})),J.push(_0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:f0(iG),execute:async(X)=>{let Y=g(iG,X),V=$.runtime.reviewOutcomeFragment({fragmentId:Y.fragmentId,reviewedBy:$.requesterId,approved:Y.approved});return g(pG,{fragmentId:V.id,status:V.status})}})),J.push(_0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:f0(cG),execute:async(X)=>{let Y=g(cG,X),V=$.runtime.finalizeOutcome(Y.outcomeId);return g(jE,{outcomeId:V.id,status:V.status})}})),J.push(_0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:f0(uG),execute:async(X)=>{return g(uG,X),g(VE.array(),$.runtime.listOutcomes())}})),J}function GZ($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}function QK($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var FE=[{id:"read_files",description:"Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Long files are windowed; page with start_line/end_line.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:y$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...a8]}],AE={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function UE($){return $==="plan"||$==="yolo"?$:"act"}function jK($){let W=UE($.mode),Z=a0[e1({mode:W})],Q=r8($.providerId??"",$.modelId??"",W,p8);return{mode:W,flags:{...Z,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function JK($,W){if(W.disabledToolIds?.has($))return!1;let{flags:Z}=jK(W);if($==="spawn_agent")return Z.enableSpawnAgent===!0;if($==="teams")return Z.enableAgentTeams===!0;if($==="editor")return Z.enableEditor===!0||Z.enableApplyPatch===!0;let Q=AE[$];return Q?Z[Q]===!0:!1}function DE($,W){if($.id==="editor"){let{flags:Z}=jK(W),Q=Z.enableApplyPatch===!0&&Z.enableEditor!==!0;return{...$,defaultEnabled:JK($.id,W),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:JK($.id,W)}}function b2($={}){return FE.map((W)=>DE(W,$))}function KZ($={}){return b2($).filter((W)=>W.defaultEnabled).map((W)=>W.id)}function FZ($){if(!$.enabled)return new Set;let W=b2($.availabilityContext),Z=new Set(W.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(W.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!Z.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${W.map((J)=>J.id).join(", ")}`);return new Set($.allowlist)}function j5($,W={}){return b2(W).filter((Z)=>$.has(Z.id)).flatMap((Z)=>Z.headlessToolNames)}function AZ($,W={}){return j5($,W)}function y2($={}){let{executorOptions:W={},executors:Z,...Q}=$,J={...l8(W),...Z??{}};return N$({...Q,executors:J})}import{mkdirSync as zE,writeFileSync as qE}from"node:fs";import{dirname as ME}from"node:path";import{normalizeUserInput as RE,stripModeNotices as EE}from"@cline/shared";import{nanoid as NE}from"nanoid";var YK={};w(YK,{sanitizeSessionToken:()=>h2,parseTeamTaskSubSessionId:()=>t8,parseSubSessionId:()=>Y5,makeTeamTaskSubSessionId:()=>X5,makeSubSessionId:()=>s8,deriveSubsessionStatus:()=>V5});import{nanoid as LE}from"nanoid";function h2($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function s8($,W){let Z=h2($),Q=h2(W),J=`${Z}__${Q}`;return J.length>180?J.slice(0,180):J}function X5($,W){let Z=h2($),Q=h2(W);return`${Z}__teamtask__${Q}__${LE(6)}`}function t8($){let Z=$.indexOf("__teamtask__");if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+12),j=J.lastIndexOf("__");if(j<=0)return null;let X=J.slice(0,j),Y=J.slice(j+2);if(!Q||!X||!Y)return null;return{rootSessionId:Q,agentId:X,teamTaskId:Y}}function Y5($){if(t8($))return null;let W="__",Z=$.indexOf(W);if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+W.length);if(!Q||!J)return null;return{rootSessionId:Q,agentId:J}}function V5($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let W=String($.reason??"").toLowerCase();if(W.includes("cancel")||W.includes("abort")||W.includes("interrupt"))return"cancelled";if(W.includes("fail")||W.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as Z0}from"zod";var HK={};w(HK,{isTerminalSessionStatus:()=>BK,isNonTerminalSessionStatus:()=>K0,SessionSource:()=>F0,SESSION_STATUSES:()=>B5,NON_TERMINAL_SESSION_STATUSES:()=>VK});import{SESSION_STATUS_VALUES as TE}from"@cline/shared";var B5=TE,VK=["idle","running","pending"];function BK($){return!VK.includes($)}function K0($){return!BK($)}var F0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var OE=Z0.enum(B5),m0=Z0.object({version:Z0.literal(1),session_id:Z0.string().min(1),source:Z0.string().min(1),pid:Z0.number().int(),started_at:Z0.string().min(1),ended_at:Z0.string().min(1).optional(),exit_code:Z0.number().int().nullable().optional(),status:OE,interactive:Z0.boolean(),provider:Z0.string().min(1),model:Z0.string().min(1),cwd:Z0.string().min(1),workspace_root:Z0.string().min(1),team_name:Z0.string().min(1).optional(),enable_tools:Z0.boolean(),enable_spawn:Z0.boolean(),enable_teams:Z0.boolean(),prompt:Z0.string().optional(),metadata:Z0.record(Z0.string(),Z0.unknown()).optional(),messages_path:Z0.string().min(1).optional(),compaction_path:Z0.string().min(1).optional()});function GK($){if(!$)return!1;return Object.values($).some((W)=>typeof W==="function")}function UJ($,W){let Z=[...$??[],...W??[]];if(Z.length===0)return;let Q=[],J=new Set;for(let j of Z){if(J.has(j.name))continue;J.add(j.name),Q.push(j)}return Q}function KK($){return JSON.stringify($,(W,Z)=>{if(Z instanceof Error)return{name:Z.name,message:Z.message,stack:Z.stack};return Z})}function $$($){return typeof $==="string"&&$.trim()?$.trim():void 0}function AJ($,W){let Z={...$};Z.id=$$(Z.id)??NE();let Q=Z.modelInfo&&typeof Z.modelInfo==="object"?{...Z.modelInfo}:void 0,J={id:$$(Q?.id)??$$(Z.modelId)??$$(W?.id),provider:$$(Q?.provider)??$$(Z.providerId)??$$(W?.provider),family:$$(Q?.family)??$$(W?.family)};if(delete Z.providerId,delete Z.modelId,J.id&&J.provider)Z.modelInfo={id:J.id,provider:J.provider,...J.family?{family:J.family}:{}};else delete Z.modelInfo;return Z}function UZ($){return $.map((W)=>AJ(W))}function DZ($,W,Z=[]){let Q=$.map((V,B)=>{let H=Z[B],K=H?.role===V.role&&JSON.stringify(H.content)===JSON.stringify(V.content)?{...H,...V}:{...V};return AJ(K)}),J=Z.length,j=[];for(let V=J;V<Q.length;V+=1)if(Q[V]?.role==="assistant")j.push(V);if(j.length===0){let V=[...Q].reverse().findIndex((B)=>B.role==="assistant");if(V===-1)return Q;j.push(Q.length-1-V)}let X=j[j.length-1],Y=j.some((V)=>Q[V]?.metrics);for(let V of j){let B=Q[V],H=B.metrics;if(!H&&V===X&&!Y){let G=W.usage;H={inputTokens:G.inputTokens,outputTokens:G.outputTokens,cacheReadTokens:G.cacheReadTokens??0,cacheWriteTokens:G.cacheWriteTokens??0,cost:G.totalCost}}Q[V]={...AJ(B,{id:W.model.id,provider:W.model.provider,family:W.model.info?.family}),...H?{metrics:H}:{},ts:B.ts??W.endedAt.getTime()}}return Q}function H5($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??void 0,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??void 0,parentAgentId:$.parentAgentId??void 0,agentId:$.agentId??void 0,conversationId:$.conversationId??void 0,isSubagent:$.isSubagent,prompt:$.prompt??void 0,metadata:$.metadata??void 0,messagesPath:$.messagesPath??void 0,updatedAt:$.updatedAt}}var wE=120;function k2($){let W=$?.trim();return W?W.slice(0,wE):void 0}function DJ($){let W=EE(RE($??"")).trim();if(!W)return;return k2(W.split(`
477
- `)[0]?.trim())}function h$($){if(!$)return;let W={...$},Z=k2(typeof W.title==="string"?W.title:void 0);if(Z)W.title=Z;else delete W.title;return Object.keys(W).length>0?W:void 0}function G5($){let W=h$($.metadata)??{},Z=$.title!==void 0?k2($.title):DJ($.prompt);if(Z)W.title=Z;return Object.keys(W).length>0?W:void 0}function _J($){let W=t8($);if(W)return{agent:"teammate",sessionId:W.rootSessionId,taskType:"team"};let Z=Y5($);if(Z)return{agent:"subagent",sessionId:Z.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function fJ($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:UZ($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function FK($,W,Z){zE(ME($),{recursive:!0}),qE($,`${JSON.stringify(fJ({updatedAt:W,context:Z,messages:[]}),null,2)}
478
- `,"utf8")}function AK($,W){return m0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:W?.endedAt??$.endedAt??void 0,exit_code:W?.exitCode??$.exitCode??void 0,status:W?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:W?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function UK($,W,Z){let Q=0;while(!0){let J=await $();if(J===void 0)return{updated:!1};let j=await W(J);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Q+=1,Q>=Z)return j;continue}return j}}R0();var DK={};w(DK,{summarizeUsageFromMessages:()=>$6,sumUsageTotals:()=>K5,getCurrentContextSize:()=>LJ,createInitialAccumulatedUsage:()=>z0,accumulateUsageTotals:()=>L0});function z0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function L0($,W){return{inputTokens:$.inputTokens+Math.max(0,W.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,W.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,W.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,W.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,W.totalCost??0)}}function K5($){let W=z0();for(let Z of $)W=L0(W,Z);return W}function e8($){return typeof $==="number"&&Number.isFinite($)?$:0}function $6($){let W=z0();for(let Z of $){let Q=Z.metrics;if(!Q)continue;W=L0(W,{inputTokens:e8(Q.inputTokens),outputTokens:e8(Q.outputTokens),cacheReadTokens:e8(Q.cacheReadTokens),cacheWriteTokens:e8(Q.cacheWriteTokens),totalCost:e8(Q.cost)})}return W}function LJ($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z?.role!=="assistant")continue;let Q=e8(Z.metrics?.inputTokens);return Q>0?Q:void 0}return}function CE($){if(!$||typeof $!=="object")return;let W=$,Z=W.skill??W.skill_name??W.skillName;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0?Q:void 0}function TJ($){if(!$||typeof $!=="object")return{};let W=$;return{agentId:typeof W.agentId==="string"?W.agentId:void 0,conversationId:typeof W.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W.parentAgentId==="string"?W.parentAgentId:void 0}}function W$($){let W=$.agentId?.trim();if(!W)return;let Z=$.parentAgentId?.trim()||void 0,Q=$.teamRole,J="root";if(Q==="teammate")J="team_teammate";else if(Q==="lead")J="team_lead";else if(Z)J="subagent";return{agentId:W,agentKind:J,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Z,createdByAgentId:$.createdByAgentId?.trim()||Z||void 0,isSubagent:Boolean(Z),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function PE($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function SE($){let W=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Z of W){let Q=Z?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function OJ($,W,Z){let{sessionId:Q,config:J,liveSession:j,emit:X}=$,Y=J.telemetry,V=j?.runtime.teamRuntime,B=Z?.isPrimaryAgentEvent??!0,H=TJ(W),G=W$({agentId:Z?.agentId??H.agentId,conversationId:Z?.conversationId??H.conversationId,parentAgentId:Z?.parentAgentId??H.parentAgentId,createdByAgentId:Z?.createdByAgentId,teamId:Z?.teamId??V?.getTeamId(),teamName:Z?.teamName??V?.getTeamName(),teamRole:Z?.teamRole,teamAgentId:Z?.teamAgentId});if(W.type==="content_start"&&W.contentType==="tool"&&W.toolName==="skills"){let K=CE(W.input);if(K)QW(Y,{ulid:Q,skillName:K,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:J.providerId,modelId:J.modelId,...G})}if(W.type==="content_end"&&W.contentType==="tool"){let K=W.toolName??"unknown",F=!W.error;if(T8(Y,{ulid:Q,tool:K,autoApproved:void 0,success:F,modelId:J.modelId,provider:J.providerId,...G}),!F&&(K==="editor"||K==="apply_patch"))JW(Y,{ulid:Q,modelId:J.modelId,provider:J.providerId,errorType:W.error,...G})}if(W.type==="notice"&&W.reason==="api_error")V4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.message,...G});if(W.type==="error")V4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.error?.message??"unknown error",...G});if(W.type==="usage"&&j?.turnUsageBaseline){let K=PE(W);if(B){j.turnPrimaryUsage=L0(j.turnPrimaryUsage??z0(),K);let A=L0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Q,A),L8(Y,{ulid:Q,provider:J.providerId,model:J.modelId,source:"assistant",mode:J.mode,...G}),WW(Y,{ulid:Q,tokensIn:W.inputTokens,tokensOut:W.outputTokens,cacheWriteTokens:W.cacheWriteTokens,cacheReadTokens:W.cacheReadTokens,totalCost:W.cost,model:J.modelId,...G})}else{let A=SE({isPrimaryAgentEvent:B,overrides:Z,eventMetadata:H}),D=j.turnUsageByAgent??new Map;j.turnUsageByAgent=D,D.set(A,L0(D.get(A)??z0(),K))}let F=L0(j.turnPrimaryUsage??z0(),K5(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,L0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,F))}if(W.type==="iteration_end"&&B)$.persistMessages(Q,j?.agent.getMessages()??[],j?.config.systemPrompt);X({type:"agent_event",payload:{sessionId:Q,event:W,teamAgentId:Z?.teamAgentId,teamRole:Z!==void 0?Z.teamRole??(B?"lead":void 0):void 0}}),X({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:KK(W),ts:Date.now()}})}function Z$($){return $.workspaceRoot??$.cwd}import{resolveProviderRequestHeaders as mw}from"@cline/llms";import{hasRuntimeConfigExtension as vw}from"@cline/shared";X1();import{existsSync as zZ,readFileSync as fN,statSync as LN}from"node:fs";import{basename as TN,dirname as TZ,join as qZ,resolve as OZ}from"node:path";import{discoverPluginModulePaths as ON,resolveConfiguredPluginModulePaths as xK,resolvePluginConfigSearchPaths as zN,SKILLS_CONFIG_DIRECTORY_NAME as qN}from"@cline/shared/storage";import{resolve as sE}from"node:path";import{normalizePluginManifest as tE}from"@cline/shared";import{existsSync as w0,readFileSync as Z6}from"node:fs";import{builtinModules as bE,createRequire as RJ}from"node:module";import{dirname as k$,extname as A5,isAbsolute as yE,resolve as o}from"node:path";import{fileURLToPath as fK}from"node:url";import{PLUGIN_FILE_EXTENSIONS as hE}from"@cline/shared";var LK=k$(fK(import.meta.url)),kE=RJ(import.meta.url),IE=o(LK,"..","..","..","..",".."),zJ=mE(IE),xE=["@cline/sdk","@cline/agents","@cline/core","@cline/core/hub","@cline/core/hub/daemon-entry","@cline/core/telemetry","@cline/llms","@cline/llms/browser","@cline/shared","@cline/shared/automation","@cline/shared/browser","@cline/shared/storage","@cline/shared/db","@cline/shared/types"],EJ=new Set(bE.flatMap(($)=>[$,$.replace(/^node:/,"")])),F5=new Set(hE),gE=["development","node","import","require","default"];function mE($){let W={},Z={"@cline/sdk":o($,"packages/sdk/src/index.ts"),"@cline/agents":o($,"packages/agents/src/index.ts"),"@cline/core":o($,"packages/core/src/index.ts"),"@cline/llms":o($,"packages/llms/src/index.ts"),"@cline/shared":o($,"packages/shared/src/index.ts"),"@cline/shared/storage":o($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":o($,"packages/shared/src/db/index.ts")};for(let[Q,J]of Object.entries(Z))if(w0(J))W[Q]=J;for(let Q of["agents","core","llms","shared"]){let J=o($,"packages",Q),j=o(J,"package.json");if(!w0(j))continue;try{let X=JSON.parse(Z6(j,"utf8"));if(typeof X.name!=="string"||!X.exports)continue;if(typeof X.exports==="string"){let Y=o(J,X.exports);if(w0(Y))W[X.name]=Y;continue}if(typeof X.exports!=="object")continue;for(let[Y,V]of Object.entries(X.exports)){let B=vE(J,V);if(!B)continue;let H=Y==="."?X.name:`${X.name}/${Y.replace(/^\.\//,"")}`;W[H]=B}}catch{}}return W}function vE($,W){let Z=NJ(W);if(!Z)return null;let Q=TK($,Z);for(let J of Q)if(w0(J))return J;return null}function NJ($,W=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(W.has($))return null;W.add($);let Z=$;for(let Q of gE){let J=NJ(Z[Q],W);if(J)return J}return null}function TK($,W){let Z=W.replace(/^\.\//,""),Q=[o($,W)];if(Z.startsWith("dist/")){let J=Z.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[o($,`${J}.ts`),o($,`${J}.tsx`),o($,`${J}.mts`),o($,`${J}.cts`),...Q]}return Q}function cE($){return Object.fromEntries(Object.entries($).sort(([W],[Z])=>Z.length-W.length))}function _Z($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function W6($){if($.startsWith("@")){let[W,Z]=$.split("/",3);return Z?`${W}/${Z}`:$}return $.split("/",1)[0]??$}function uE($){let W=W6($);if($===W)return".";return`.${$.slice(W.length)}`}function OK($){return W6($).startsWith("@cline/")}function qJ($,W){let Z=W6(W),Q=k$($);while(!0){let J=o(Q,"node_modules",Z);if(w0(J)||w0(o(J,"package.json")))return!0;let j=o(Q,"..");if(j===Q)return!1;Q=j}}function _K($){return MJ($)!==null}function MJ($){try{return kE.resolve($)}catch{}return dE($)}function dE($){let W=W6($),Z=zK(W);if(!Z)return null;let Q=o(Z,"package.json");try{let J=JSON.parse(Z6(Q,"utf8")),j=uE($),X=j==="."&&typeof J.exports==="string"?J.exports:J.exports&&typeof J.exports==="object"&&Object.hasOwn(J.exports,j)?J.exports[j]:void 0,Y=NJ(X)??(j==="."&&typeof J.main==="string"?J.main:null);if(!Y)return null;let V=o(Z,Y),B=[V,...TK(Z,Y).filter((H)=>H!==V)];for(let H of B)if(w0(H))return H;return null}catch{return null}}function lE(){let $=[LK],W=process.env.CLINE_WRAPPER_PATH?.trim();if(W)$.push(k$(k$(W)));let Z=process.execPath?.trim();if(Z)$.push(k$(Z));return[...new Set($.map((Q)=>o(Q)))]}function pE($,W){let Z=$;while(!0){let Q=o(Z,"package.json");if(w0(Q))try{if(JSON.parse(Z6(Q,"utf8")).name===W)return Z}catch{}let J=o(Z,"node_modules",W,"package.json");if(w0(J))return k$(J);let j=o(Z,"..");if(j===Z)return null;Z=j}}function zK($){for(let W of lE()){let Z=pE(W,$);if(Z)return Z}return null}function rE($){let Z=k$($);for(let Q=0;Q<4;Q++){let J=o(Z,"package.json");if(w0(J))try{let X=JSON.parse(Z6(J,"utf8"));return X!=null&&typeof X==="object"&&"cline"in X}catch{return!1}let j=o(Z,"..");if(j===Z)return!1;Z=j}return!1}function qK($,W){let Z=W.startsWith("file:")?fK(W):yE(W)?W:o(k$($),W);if(w0(Z)&&F5.has(A5(Z)))return Z;for(let Q of F5){let J=`${Z}${Q}`;if(w0(J))return J}for(let Q of F5){let J=o(Z,`index${Q}`);if(w0(J))return J}return null}function MK($){let W=new Set,Z=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of Z)for(let J of $.matchAll(Q)){let j=J[1];if(j)W.add(j)}return[...W]}function iE($){return A5($)!==".ts"}function RK($,W,Z=new Set){if(Z.has($)||!w0($))return;if(Z.add($),!F5.has(A5($)))return;let Q=Z6($,"utf8"),J=iE($);for(let j of MK(Q)){if(j.startsWith("node:")||EJ.has(j))continue;if(_Z(j)){if(!J)continue;if(Object.hasOwn(zJ,j)||Object.hasOwn(zJ,W6(j))||qJ($,j)||OK(j)&&_K(j)||W&&_K(j))continue;throw Error(`Cannot find module '${W6(j)}'`)}let X=qK($,j);if(X)RK(X,W,Z)}}function EK($,W=new Set,Z=new Set){if(W.has($)||!w0($))return Z;if(W.add($),!F5.has(A5($)))return Z;let Q=Z6($,"utf8");for(let J of MK(Q)){if(Z.add(J),_Z(J))continue;let j=qK($,J);if(j)EK(j,W,Z)}return Z}function nE($,W){let Z=RJ($),Q={},J=EK($),j=new Set(xE);for(let[X,Y]of Object.entries(zJ)){try{Z.resolve(X);continue}catch{}Q[X]=Y}for(let X of J)if(_Z(X)&&(OK(X)||W))j.add(X);for(let X of j){if(Object.hasOwn(Q,X)||qJ($,X))continue;let Y=MJ(X);if(Y)Q[X]=Y}if(!W)return Q;for(let X of J){if(!_Z(X)||Object.hasOwn(Q,X)||qJ($,X)||X.startsWith("node:")||EJ.has(X))continue;let Y=MJ(X);if(Y)Q[X]=Y}return Q}function aE($){let W=A5($);return W===".ts"||W===".tsx"||W===".mts"||W===".cts"}var I2;function oE(){if(I2!==void 0)return I2;let $=zK("jiti");if(!$)return I2=null,null;let W=o($,"dist","babel.cjs");if(!w0(W))return I2=null,null;try{let Q=RJ(W)(W);I2=typeof Q==="function"?Q:null}catch{I2=null}return I2}async function NK($,W={}){let Z=!rE($);RK($,Z);let Q=nE($,Z),J=cE(Q),j=await import("jiti"),X=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!X)throw Error("Unable to load jiti");let Y=Object.entries(J).filter(([,G])=>aE(G)).map(([G])=>G),V=oE(),B=V?(G)=>V({...G,interopDefault:!0}):void 0;return await X($,{alias:J,cache:W.useCache,requireCache:W.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...EJ],transformModules:Y,tryNative:!1,...B?{transform:B}:{}}).import($,{})}function wK($,W){if(!$)return!0;if($.providerIds?.length){if(!W?.providerId||!$.providerIds.includes(W.providerId))return!1}if($.modelIds?.length){if(!W?.modelId||!$.modelIds.includes(W.modelId))return!1}return!0}function CK($){return typeof $==="object"&&$!==null}function wJ($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function eE($,W){if(!CK($.manifest))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);if(!wJ($.manifest.capabilities))throw Error(`Invalid plugin module at ${W}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${W}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!wJ($.manifest.providerIds))throw Error(`Invalid plugin module at ${W}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!wJ($.manifest.modelIds))throw Error(`Invalid plugin module at ${W}: manifest.modelIds must be a string array when provided`)}function $N($,W){if(!CK($))throw Error(`Invalid plugin module at ${W}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${W}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);eE($,W)}async function U5($,W={}){let Z=sE(W.cwd??process.cwd(),$),Q=await NK(Z,{useCache:W.useCache}),J=W.exportName??"plugin",j=Q.default??Q[J];$N(j,Z);let X=j,Y=X.setup,V=Y?(B,H)=>{let G={...W.session,...H.session},K={...H,session:Object.keys(G).length>0?G:void 0,client:W.client??H.client,user:W.user??H.user,workspaceInfo:W.workspaceInfo??H.workspaceInfo,automation:W.automation??H.automation,logger:W.logger??H.logger,telemetry:W.telemetry??H.telemetry};return Y(B,K)}:void 0;return{...X,manifest:tE(X.manifest),setup:V}}async function fZ($,W={}){return(await x2($,W)).plugins}async function x2($,W={}){let Z=[],Q=[],J=new Map,j=0;for(let Y of $)try{let V=await U5(Y,W);if(!wK(V.manifest,W))continue;let B=J.get(V.name);if(B)Q.push({type:"duplicate_plugin_override",pluginName:V.name,pluginPath:Y,overriddenPluginPath:B.pluginPath,message:`Plugin "${V.name}" from ${Y} overrides ${B.pluginPath}`});J.set(V.name,{plugin:V,pluginPath:Y,order:j++})}catch(V){let B=V instanceof Error?V.message:String(V);Z.push({pluginPath:Y,phase:"load",message:B,stack:V instanceof Error?V.stack:void 0})}let X=[...J.values()].sort((Y,V)=>Y.order-V.order);return{plugins:X.map((Y)=>Y.plugin),pluginPaths:X.map((Y)=>Y.pluginPath),failures:Z,warnings:Q}}import{existsSync as bJ}from"node:fs";import{createRequire as IK}from"node:module";import{dirname as LZ,join as J6}from"node:path";import{fileURLToPath as jN}from"node:url";var hK={};w(hK,{resolveSubprocessRuntimeExecutable:()=>CJ,buildSubprocessSandboxCommand:()=>yK,SubprocessSandbox:()=>Q6,CLINE_JS_RUNTIME_PATH_ENV:()=>bK});import{spawn as WN}from"node:child_process";import{basename as ZN}from"node:path";import{augmentNodeCommandForDebug as QN,withResolvedClineBuildEnv as JN}from"@cline/shared";function PK($){if($ instanceof Error)return $;return Error(String($))}var bK="CLINE_JS_RUNTIME_PATH";function SK($){let W=$?.trim();if(!W)return!1;let Z=ZN(W).toLowerCase();return Z==="node"||Z==="node.exe"||Z==="bun"||Z==="bun.exe"}function CJ($={}){let W=$.env??process.env,Z=$.runtimeExecutable?.trim()||W[bK]?.trim();if(Z)return Z;let Q=$.execPath?.trim()||process.execPath;if(SK(Q))return Q;for(let J of[W.BUN_EXEC_PATH,W.npm_node_execpath,W.NODE]){let j=J?.trim();if(j&&SK(j))return j}return"node"}function yK($,W={}){let Z=CJ({env:W.env,execPath:W.execPath,runtimeExecutable:W.runtimeExecutable});return QN([Z,...$],{env:W.env,execArgv:W.execArgv,debugRole:W.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class Q6{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let W=this.pending.get($);if(!W)return;if(this.pending.delete($),W.timeout)clearTimeout(W.timeout);return W}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],W=yK($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Z=WN(W[0]??CJ(this.options),W.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:JN(process.env),windowsHide:!0});this.process=Z;let Q="",J=(j)=>{let X=Q+j;Q=X.length>4000?X.slice(-4000):X};Z.stderr?.setEncoding("utf8"),Z.stderr?.on("data",(j)=>{J(j)}),Z.on("message",(j)=>{this.onMessage(j)}),Z.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${PK(j).message}`))}),Z.on("exit",(j,X)=>{this.process=null;let Y=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(X)})${Y?`: ${Y}`:""}`))})}async call($,W,Z={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let J=`req_${++this.requestCounter}`,j={type:"call",id:J,method:$,args:W};return await new Promise((X,Y)=>{let V={resolve:(B)=>X(B),reject:Y};if((Z.timeoutMs??0)>0)V.timeout=setTimeout(()=>{this.clearPendingRequest(J),this.shutdown().catch(()=>{}),Y(Error(`${this.processLabel} call timed out after ${Z.timeoutMs}ms: ${$}`))},Z.timeoutMs);this.pending.set(J,V),Q.send(j,(B)=>{if(!B)return;let H=this.clearPendingRequest(J);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${PK(B).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((W)=>{let Z=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}W()},300);$.once("exit",()=>{clearTimeout(Z),W()});try{$.kill("SIGTERM")}catch{clearTimeout(Z),W()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let W=this.clearPendingRequest($.id);if(!W)return;if($.ok){W.resolve($.result);return}W.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[W,Z]of this.pending.entries()){if(this.pending.delete(W),Z.timeout)clearTimeout(Z.timeout);Z.reject($)}}}function XN($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],mcpServers:$.contributions?.mcpServers??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function D5($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function YN(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function VN(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Z=IK($).resolve(`${YN()}/package.json`),Q=J6(LZ(Z),"extensions","plugin-sandbox-bootstrap.js");return bJ(Q)?Q:void 0}catch{return}}function BN(){let $=process.execPath?.trim();if(!$)return;let W=J6(LZ(LZ($)),"extensions","plugin-sandbox-bootstrap.js");return bJ(W)?W:void 0}function HN(){let $=LZ(jN(import.meta.url)),W=IK(import.meta.url),Z=[J6($,"plugin-sandbox-bootstrap.js"),J6($,"extensions","plugin-sandbox-bootstrap.js"),J6($,"agents","plugin-sandbox-bootstrap.js"),VN(),BN()];for(let j of Z.filter((X)=>typeof X==="string"))if(bJ(j))return{file:j};let Q=J6($,"plugin-sandbox-bootstrap.ts"),J="jiti";try{J=W.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(J)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
479
- `)}}var PJ=HN();function SJ($,W,Z){if(typeof $==="number"&&$>0)return $;if(Z){let Q=process.env[Z];if(Q){let J=Number(Q);if(Number.isInteger(J)&&J>0)return J}}return W}async function j6($){let W=new Q6({name:"plugin-sandbox",..."file"in PJ?{bootstrapFile:PJ.file}:{bootstrapScript:PJ.script},onEvent:$.onEvent}),Z=SJ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Q=SJ($.hookTimeoutMs,3000),J=SJ($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},X,Y=()=>{return X??=W.call("initialize",j,{timeoutMs:Z}).finally(()=>{X=void 0}),X},V;try{V=await W.call("initialize",j,{timeoutMs:Z})}catch(G){throw await W.shutdown().catch(()=>{}),G}let B=V.plugins.map(XN);return{extensions:B.map((G)=>{let K={name:G.name,__clinePluginPath:G.pluginPath,manifest:G.manifest,setup:(F)=>{GN(F,W,G,J,Y),KN(F,W,G,J,Y),FN(F,W,G,J,Y),UN(F,W,G,J,Y),AN(F,G)}};return K.hooks=_N(W,G,Q,Y),K}),failures:V.failures,pluginPaths:B.map((G)=>G.pluginPath),shutdown:async()=>{await W.shutdown()},warnings:V.warnings}}function GN($,W,Z,Q,J){for(let j of Z.contributions?.tools??[]){let X={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(Y,V)=>{try{return await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}catch(B){if(!D5(B))throw B;return await J(),await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}}};$.registerTool(X)}}function KN($,W,Z,Q,J){for(let j of Z.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(X)=>{try{return await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}catch(Y){if(!D5(Y))throw Y;return await J(),await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}}})}function FN($,W,Z,Q,J){for(let j of Z.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}catch(X){if(!D5(X))throw X;return await J(),await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}}:j.content??""})}function AN($,W){for(let Z of W.contributions?.providers??[])$.registerProvider({name:Z.name,description:Z.description,metadata:Z.metadata});for(let Z of W.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Z.eventType,source:Z.source,description:Z.description,attributesSchema:Z.attributesSchema,payloadSchema:Z.payloadSchema,examples:Z.examples,metadata:Z.metadata});for(let Z of W.contributions?.mcpServers??[])$.registerMcpServer(Z)}function UN($,W,Z,Q,J){for(let j of Z.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(X){try{let Y=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return kK(Y)?Y:X}catch(Y){if(!D5(Y))throw Y;await J();let V=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return kK(V)?V:X}}})}function kK($){return Array.isArray($)&&$.every((W)=>typeof W==="object"&&W!==null&&("role"in W)&&("content"in W))}function DN($,W,Z,Q,J){return async(j)=>{try{return await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}catch(X){if(!D5(X))throw X;return await J(),await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}}}function _N($,W,Z,Q){let J={};for(let j of W.hooks??[])J[j]=DN($,W.pluginId,j,Z,Q);return Object.keys(J).length>0?J:void 0}var hJ="package.json",MN="package";function _5($){return zN($)}function f5($){return ON($)}function RN($){try{return zZ($)&&LN($).isDirectory()}catch{return!1}}function kJ($){let W=[],Z=new Set;for(let Q of $){let J=OZ(Q);if(Z.has(J))continue;Z.add(J),W.push(J)}return W}function gK($){let W=kJ($);return DW(W)}function mK($){return _5($).flatMap((W)=>f5(W)).filter((W)=>zZ(W))}function EN($,W){let Z=[];for(let Q of $)try{Z.push(...xK([Q],W))}catch{}return Z}function yJ($){return typeof $==="object"&&$!==null}function NN($){try{let W=JSON.parse(fN(qZ($,hJ),"utf8"));if(!yJ(W)||!yJ(W.cline))return[];let Z=W.cline.plugins;if(!Array.isArray(Z))return[];let Q=[];for(let J of Z){if(typeof J==="string"){Q.push(J);continue}if(!yJ(J)||!Array.isArray(J.paths))continue;for(let j of J.paths)if(typeof j==="string")Q.push(j)}return Q}catch{return[]}}function vK($,W){let Z=OZ(W);return NN($).some((Q)=>OZ($,Q)===Z)}function wN($,W){return TN($)===MN&&zZ(qZ(TZ($),hJ))&&vK(TZ($),W)}function CN($){let W=OZ($),Z=[],Q=TZ(W);while(!0){if(wN(Q,W)){Z.push(Q);break}if(zZ(qZ(Q,hJ))){if(vK(Q,W))Z.push(Q);break}let J=TZ(Q);if(J===Q)break;Q=J}return kJ(Z)}function Q$($={}){let W=$.cwd??process.cwd(),Z=mK($.workspacePath),Q=xK($.pluginPaths??[],W);return gK([...Q,...Z])}function PN($={}){let W=$.cwd??process.cwd(),Z=mK($.workspacePath),Q=EN($.pluginPaths??[],W);return gK([...Q,...Z])}function J$($){let W=[];for(let Z of $)for(let Q of CN(Z)){let J=qZ(Q,qN);if(RN(J))W.push(J)}return kJ(W)}function cK($={}){return J$(PN($))}async function X6($={}){let W=Q$($);if(W.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Q=await x2(W,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Q.plugins,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}let Z=await j6({pluginPaths:W,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:Z.extensions??[],shutdown:Z.shutdown,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}import{execFile as SN}from"node:child_process";import{promisify as bN}from"node:util";var yN=bN(SN);function IJ($,W){$?.log(W,{severity:"warn"})}function hN($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))return;let Z=W;if(!Z.latest||!Array.isArray(Z.history))return;let Q=Z.latest,J=Z.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:J}}async function g2($,W){let Z=await yN("git",["-C",$,...W],{windowsHide:!0});return{stdout:Z.stdout.trim(),stderr:Z.stderr.trim()}}async function xJ($,W){if(!$)return;let Z=`refs/cline/checkpoints/${W}/`;try{let{stdout:Q}=await g2($,["for-each-ref","--format=%(refname)",Z]),J=Q.trim().split(`
480
- `).filter(Boolean);await Promise.allSettled(J.map((j)=>g2($,["update-ref","-d",j])))}catch{}}async function uK($,W,Z){if(!$||Z.length===0)return;await Promise.allSettled(Z.map((Q)=>g2($,["update-ref",`refs/cline/checkpoints/${W}/${Q.runCount}`,Q.ref])))}function kN($,W){let Z=$.findIndex((Q)=>Q.runCount===W.runCount);if(Z<0)return[...$,W];return $.map((Q,J)=>J===Z?W:Q)}function dK($){let W=$.initialRunCount??0,Z,Q=async()=>{if(Z!==void 0)return Z;try{Z=(await g2($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Z=!1}return Z},J=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:W});if(!await Q())return;let j=async(B)=>{try{let G=(await g2($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!G)return;return{ref:G,createdAt:Date.now(),runCount:W,kind:"commit"}}catch(H){IJ($.logger,`${B}: ${H instanceof Error?H.message:String(H)}`);return}},X=`cline checkpoint session=${$.sessionId} run=${W}`,Y="";try{Y=(await g2($.cwd,["stash","create",X])).stdout.trim()}catch(B){return IJ($.logger,`Checkpoint snapshot failed: ${B instanceof Error?B.message:String(B)}`),j("Checkpoint HEAD fallback failed")}if(!Y)return j("Checkpoint HEAD fallback failed");let V=`refs/cline/checkpoints/${$.sessionId}/${W}`;try{await g2($.cwd,["update-ref",V,Y])}catch(B){IJ($.logger,`Checkpoint store failed: ${B instanceof Error?B.message:String(B)}`);return}return{ref:Y,createdAt:Date.now(),runCount:W,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;W+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||W<1)return;let X=await J();if(!X)return;let Y=await $.readSessionMetadata(),V=hN(Y);if(V?.latest.ref===X.ref)return;let B=kN(V?.history??[],X);await $.writeSessionMetadata({...Y??{},checkpoint:{latest:X,history:B}});return}}}import{spawn as lN}from"node:child_process";import{appendFileSync as pN,readFileSync as rN}from"node:fs";import{join as iN}from"node:path";import{augmentNodeCommandForDebug as rK,withResolvedClineBuildEnv as vJ}from"@cline/shared";import{ensureHookLogDir as lK}from"@cline/shared/storage";function Y6($,W){if(!W)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:W}}import{existsSync as IN,readdirSync as xN}from"node:fs";import{basename as gN,extname as mN,join as vN}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as MZ,resolveHooksConfigSearchPaths as cN}from"@cline/shared/storage";function L5($){return cN($)}var V6;((H)=>{H.TaskStart="TaskStart";H.TaskResume="TaskResume";H.TaskCancel="TaskCancel";H.TaskComplete="TaskComplete";H.TaskError="TaskError";H.PreToolUse="PreToolUse";H.PostToolUse="PostToolUse";H.UserPromptSubmit="UserPromptSubmit";H.PreCompact="PreCompact";H.SessionShutdown="SessionShutdown"})(V6||={});var T5={["TaskStart"]:"agent_start",["TaskResume"]:"agent_resume",["TaskCancel"]:"agent_abort",["TaskComplete"]:"agent_end",["TaskError"]:"agent_error",["PreToolUse"]:"tool_call",["PostToolUse"]:"tool_result",["UserPromptSubmit"]:"prompt_submit",["PreCompact"]:void 0,["SessionShutdown"]:"session_shutdown"},uN=new Map(Object.values(V6).map(($)=>[$.toLowerCase(),$])),dN=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function O5($){let W=mN($).toLowerCase();if(!dN.has(W))return;let Z=gN($,W).trim().toLowerCase();return uN.get(Z)}function I$($){let W=[],Z=new Set,Q=L5($).filter((J)=>IN(J));for(let J of Q)try{for(let j of xN(J,{withFileTypes:!0})){if(!j.isFile())continue;let X=O5(j.name);if(!X)continue;let Y=vN(J,j.name);if(Z.has(Y))continue;Z.add(Y),W.push({fileName:X,hookEventName:T5[X],path:Y})}}catch{}return W.sort((J,j)=>J.path.localeCompare(j.path))}function EZ($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))W[Z]=typeof Q==="string"?Q:JSON.stringify(Q);return W}function RZ($,W,Z){let Q=Z instanceof Error?`: ${Z.message}`:"",J=`${W}${Q}`;if($){try{$.log(J,{severity:"warn",...Z!==void 0?{error:Z}:{}})}catch{}return}console.warn(J)}function nN($,W){if(!W)return $;if(!$)return{...W};let Z=[$.context,W.context].filter((J)=>typeof J==="string"&&J.length>0).join(`
481
- `),Q=[...$.appendMessages??[],...W.appendMessages??[]];return{cancel:$.cancel===!0||W.cancel===!0?!0:void 0,review:$.review===!0||W.review===!0?!0:void 0,context:Z||void 0,overrideInput:W.overrideInput!==void 0?W.overrideInput:$.overrideInput,systemPrompt:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function aN($){if(!$||typeof $!=="object")return;let W=$,Z=typeof W.context==="string"?W.context:typeof W.contextModification==="string"?W.contextModification:typeof W.errorMessage==="string"?W.errorMessage:void 0;return{cancel:typeof W.cancel==="boolean"?W.cancel:void 0,review:typeof W.review==="boolean"?W.review:void 0,context:Z,overrideInput:Object.hasOwn(W,"overrideInput")?W.overrideInput:void 0}}function gJ($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function C0($,W){let Z=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:W.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:W.workspacePath?[W.workspacePath]:[],workspaceInfo:W.workspaceInfo,userId:Z,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function oN($){let W=$.trim();if(!W)return{};let Q=W.split(`
482
- `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse hook stdout JSON"}}}async function sN($,W){let Z=$.stdin;if(!Z)throw Error("hook command failed to create stdin");await new Promise((Q,J)=>{let j=!1,X=()=>{Z.off("error",V),Z.off("finish",B),$.off("close",H)},Y=(G)=>{if(j)return;if(j=!0,X(),G){let K=G.code;if(K==="EPIPE"||K==="ERR_STREAM_DESTROYED"){Q();return}J(G);return}Q()},V=(G)=>Y(G),B=()=>Y(),H=()=>Y();Z.on("error",V),Z.once("finish",B),$.once("close",H);try{Z.end(W)}catch(G){Y(G)}})}async function iK($,W){if(W.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await pK($,W)}catch(Z){let Q=$w(W.command,process.platform,Z);if(!Q)throw Z;return await pK($,{...W,command:Q})}}async function pK($,W){let Z=rK(W.command,{env:W.env,debugRole:"hook"}),Q=lN(Z[0],Z.slice(1),{cwd:W.cwd,env:vJ(W.env),stdio:W.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W.detached,windowsHide:!0}),J=new Promise((K)=>{Q.once("spawn",()=>K())}),j=new Promise((K,F)=>{Q.once("error",(A)=>F(A))}),X=JSON.stringify($);if(await Promise.race([J,j]),await sN(Q,X),W.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let Y="",V="",B=!1,H;Q.stdout.on("data",(K)=>{Y+=K.toString()}),Q.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,Q.kill("SIGKILL")},W.timeoutMs);Q.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:D}=oN(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:D,timedOut:B})})});return await Promise.race([G,j])}function tN($){try{let Z=rN($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Z?.startsWith("#!"))return;let Q=Z.slice(2).trim();if(!Q)return;let J=Q.split(/\s+/).filter(Boolean);return J.length>0?J:void 0}catch{return}}function eN($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function $w($,W=process.platform,Z){if(W!=="win32"||!eN(Z))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function nK($){if($.length===0)return;let[W,...Z]=$,Q=W.replace(/\\/g,"/").toLowerCase(),J=Q.split("/").at(-1)??Q;if(J==="env")return nK(Z);if(J==="bash"||J==="sh"||J==="zsh")return[J,...Z];if(J==="python3"||J==="python")return process.platform==="win32"?["py","-3",...Z]:[J,...Z];return $}function Ww($){let W=tN($);if(W&&W.length>0)return[...nK(W)??W,$];let Z=$.toLowerCase();if(Z.endsWith(".sh")||Z.endsWith(".bash")||Z.endsWith(".zsh"))return["bash",$];if(Z.endsWith(".js")||Z.endsWith(".mjs")||Z.endsWith(".cjs"))return rK(["node",$],{debugRole:"hook"});if(Z.endsWith(".ts")||Z.endsWith(".mts")||Z.endsWith(".cts"))return["bun","run",$];if(Z.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Z.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function Zw($){let W={};for(let Z of I$($)){if(!Z.hookEventName)continue;let Q=Z.hookEventName,J=W[Q]??[];J.push(Ww(Z.path)),W[Q]=J}return W}async function Qw($){let W;for(let Z of $.commands){let Q=Z.join(" ");try{let J=await iK($.payload,{command:Z,cwd:$.cwd,env:vJ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(J?.timedOut){RZ($.logger,`hook command timed out: ${Q}`);continue}if(J?.parseError){RZ($.logger,`hook command returned invalid JSON control output: ${Q} (${J.parseError})`);continue}W=nN(W,aN(J?.parsedJson))}catch(J){RZ($.logger,`hook command failed: ${Q}`,J)}}return W}function m2($){for(let W of $.commands){let Z=W.join(" ");iK($.payload,{command:W,cwd:$.cwd,env:vJ(process.env),detached:!0}).catch((Q)=>{RZ($.logger,`hook command failed: ${Z}`,Q)})}}function x$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function mJ($,W){return{...x$($.snapshot),userMessage:W}}function aK($){return{...x$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function oK($){return{...x$($.snapshot),iteration:$.snapshot.iteration,record:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}}function sK($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function Jw($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}function B6($){let W={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Z=(Q)=>{let J=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
483
- `,X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??iN(lK(),"hooks.jsonl");lK(X),pN(X,J,"utf8")};return{beforeRun:async(Q)=>{let J=mJ(Q,"");Z({...C0(J,W),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let J=aK(Q);Z({...C0(J,W),hookName:"tool_call",iteration:J.iteration,tool_call:{id:J.call.id,name:J.call.name,input:J.call.input},preToolUse:{toolName:J.call.name,parameters:EZ(J.call.input)}});return},afterTool:async(Q)=>{let J=oK(Q);Z({...C0(J,W),hookName:"tool_result",iteration:J.iteration,tool_result:J.record,postToolUse:{toolName:J.record.name,parameters:EZ(J.record.input),result:typeof J.record.output==="string"?J.record.output:JSON.stringify(J.record.output),success:!J.record.error,executionTimeMs:J.record.durationMs}});return},afterRun:async({snapshot:Q,result:J})=>{let j=x$(Q);if(J.status==="completed"){Z({...C0(j,W),hookName:"agent_end",iteration:J.iterations,turn:{outputText:J.outputText,status:J.status},taskComplete:{taskMetadata:{}}});return}if(J.status==="aborted"||gJ(J.error?.message)){Z({...C0(j,W),hookName:"agent_abort",reason:J.error?.message,taskCancel:{taskMetadata:{}}});return}if(J.error)Z({...C0(j,W),hookName:"agent_error",iteration:J.iterations,error:{name:J.error.name,message:J.error.message,stack:J.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let J=mJ({snapshot:Q.snapshot},sK(Q.message.content));Z({...C0(J,W),hookName:"prompt_submit",userPromptSubmit:{prompt:J.userMessage,attachments:[]}})}}}function z5($){let W=Zw($.workspacePath);if(!Object.values(W).some((G)=>G.length>0))return;let Q=async(G,K)=>{let F=W[K]??[];if(F.length===0)return;m2({commands:F,cwd:$.cwd,logger:$.logger,payload:K==="agent_resume"?{...C0(G,$),hookName:K,taskResume:{taskMetadata:{},previousState:{}}}:{...C0(G,$),hookName:K,taskStart:{taskMetadata:{}}}})},J=async(G)=>{let K=W.prompt_submit??[];if(K.length>0)m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"prompt_submit",userPromptSubmit:{prompt:G.userMessage,attachments:[]}}})},j=async(G)=>{let K=W.tool_call??[];if(K.length===0)return;return Qw({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...C0(G,$),hookName:"tool_call",iteration:G.iteration,tool_call:{id:G.call.id,name:G.call.name,input:G.call.input},preToolUse:{toolName:G.call.name,parameters:EZ(G.call.input)}}})},X=async(G)=>{let K=W.tool_result??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"tool_result",iteration:G.iteration,tool_result:G.record,postToolUse:{toolName:G.record.name,parameters:EZ(G.record.input),result:typeof G.record.output==="string"?G.record.output:JSON.stringify(G.record.output),success:!G.record.error,executionTimeMs:G.record.durationMs}}})},Y=async(G)=>{let K=W.agent_end??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"agent_end",iteration:G.iteration,turn:G.turn,taskComplete:{taskMetadata:{}}}})},V=async(G)=>{let K=W.agent_error??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"agent_error",iteration:G.iteration,error:{name:G.error.name,message:G.error.message,stack:G.error.stack}}})},B=async(G)=>{if(gJ(G.reason)){let F=W.agent_abort??[];if(F.length>0)m2({commands:F,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"agent_abort",reason:G.reason,taskCancel:{taskMetadata:{}}}})}let K=W.session_shutdown??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"session_shutdown",reason:G.reason}})},H={};if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0||(W.prompt_submit?.length??0)>0){if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0)H.beforeRun=async(G)=>{let K=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(x$(G.snapshot),K);return};if((W.prompt_submit?.length??0)>0)H.onEvent=async(G)=>{if(G.type!=="message-added"||G.message.role!=="user")return;await J(mJ({snapshot:G.snapshot},sK(G.message.content)))}}if((W.tool_call?.length??0)>0)H.beforeTool=async(G)=>{let K=await j(aK(G));return Jw(K)};if((W.tool_result?.length??0)>0)H.afterTool=async(G)=>{await X(oK(G));return};if((W.agent_end?.length??0)>0)H.afterRun=async({snapshot:G,result:K})=>{if(K.status!=="completed")return;await Y({...x$(G),iteration:K.iterations,turn:{outputText:K.outputText,status:K.status}})};if((W.agent_error?.length??0)>0||(W.agent_abort?.length??0)>0||(W.session_shutdown?.length??0)>0){let G=H.afterRun;H.afterRun=async(K)=>{await G?.(K);let{snapshot:F,result:A}=K;if(A.status==="aborted"||gJ(A.error?.message)){await B({...x$(F),reason:A.error?.message});return}if(A.error)await V({...x$(F),iteration:A.iterations,error:A.error})}}return H}function H6($){return Y6("core.hook_config_files",z5($))}function v2($,W){let Z=$.map((Q)=>Q[W]).filter((Q)=>typeof Q==="function");if(Z.length===0)return;return async(Q)=>{let J;for(let j of Z){let X=await j(Q);if(!X||typeof X!=="object")continue;let Y=X;J={...J??{},...Y,stop:J?.stop===!0||Y.stop===!0?!0:Y.stop,options:J?.options||Y.options?{...J?.options??{},...Y.options??{}}:void 0}}return J}}function c2($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return;return{beforeRun:v2(W,"beforeRun"),afterRun:v2(W,"afterRun"),beforeModel:v2(W,"beforeModel"),afterModel:v2(W,"afterModel"),beforeTool:v2(W,"beforeTool"),afterTool:v2(W,"afterTool"),onEvent:v2(W,"onEvent")}}var tK={};w(tK,{normalizeRuntimeCapabilities:()=>P0});function P0(...$){let W,Z;for(let J of $){if(!J)continue;if(J.toolExecutors)W={...W??{},...J.toolExecutors};if(J.requestToolApproval)Z=J.requestToolApproval}let Q=W&&Object.keys(W).length>0;if(!Q&&!Z)return;return{...Q?{toolExecutors:W}:{},...Z?{requestToolApproval:Z}:{}}}var YF={};w(YF,{toProviderConfig:()=>s0,emptyStoredProviderSettings:()=>v$,StoredProviderSettingsSchema:()=>A6,StoredProviderSettingsEntrySchema:()=>aZ,ProviderSettingsSchemaTyped:()=>F6});import{z as m$}from"zod";var XF={};w(XF,{toProviderConfig:()=>s0,safeParseSettings:()=>nZ,safeCreateProviderConfig:()=>oJ,parseSettings:()=>iZ,normalizeProviderId:()=>K6,isBuiltInProviderId:()=>nJ,createProviderConfig:()=>aJ,SapSettingsSchema:()=>lZ,ReasoningSettingsSchema:()=>vZ,ProviderSettingsSchema:()=>g$,ProviderProtocolSchema:()=>xZ,ProviderIdSchema:()=>N5,ProviderClientSchema:()=>gZ,OcaSettingsSchema:()=>pZ,ModelCatalogSettingsSchema:()=>rZ,GcpSettingsSchema:()=>uZ,BUILT_IN_PROVIDER_IDS:()=>iJ,BUILT_IN_PROVIDER:()=>E5,AzureSettingsSchema:()=>dZ,AwsSettingsSchema:()=>cZ,AuthSettingsSchema:()=>mZ});import*as o0 from"@cline/llms";import{z as N}from"zod";var jF={};w(jF,{resolveProviderConfig:()=>R5,getProviderConfig:()=>IZ,getLiveModelsCatalog:()=>G6,clearPublicModelsCatalogCache:()=>Nw,clearPrivateModelsCatalogCache:()=>rJ,clearLiveModelsCatalogCache:()=>pJ,OPENAI_COMPATIBLE_PROVIDERS:()=>M5,DEFAULT_MODELS_CATALOG_URL:()=>bZ});import*as $0 from"@cline/llms";function cJ($){if(!Array.isArray($))return[];return $.map((W)=>{if(typeof W==="string")return W.trim();if(W&&typeof W==="object"){let Z=W;for(let Q of[Z.id,Z.name,Z.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter((W)=>W.length>0)}function jw($,W){let Z=cJ($);if(Z.length>0)return Z;if(!$||typeof $!=="object")return[];let Q=$,J=cJ(Q.data??Q.models);if(J.length>0)return J;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let X=Object.keys(Q.models).filter((Y)=>Y.trim().length>0);if(X.length>0)return X}let j=Q.providers?.[W];if(j&&typeof j==="object"){let Y=cJ(j.models??j);if(Y.length>0)return Y}return[]}async function NZ($,W){let Z=await fetch($,{method:"GET"});if(!Z.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Z.status}`);return jw(await Z.json(),W)}function eK($){return $.replace(/\/+$/,"")}function wZ($,W,Z){let Q=Z?.trim();if(!Q)return;let J=$?.trim();if(!J||!W?.trim())return Q;try{let j=new URL(Q),X=new URL(W),Y=new URL(J);if(j.origin!==X.origin)return Q;let V=eK(X.pathname),B=eK(Y.pathname);if(V&&j.pathname.startsWith(`${V}/`)){let H=j.pathname.slice(V.length);Y.pathname=`${B}${H}`}else Y.pathname=j.pathname;return Y.search=j.search,Y.hash=j.hash,Y.toString()}catch{return Q}}function Xw($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{...Z}]))}function Yw($){if($.baseUrl.length===0)return!1;switch($.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return $.protocol==="openai-chat"}}var Vw=Object.values($0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:Xw($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),WF=Object.fromEntries(Vw.map(($)=>[$.id,$]));function Bw($){return WF[$]}function Hw(){return Object.fromEntries(Object.entries(WF).filter(([,$])=>Yw($)))}function ZF($=[]){let W=$.flatMap((Z)=>{switch(Z){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Z];default:return[]}});return W.length>0?W:void 0}var bZ="https://models.dev/api.json",Gw=600000,QF=300000,Kw=5000,SZ=new Map,q5=new Map,uJ=new Map,CZ=new Map;async function Fw(){return $0.getGeneratedProviderModels()}async function Aw($,W={},Z={},Q={},J={},j={}){if($==="litellm")return $0.sortModelsByReleaseDate(Q);let X=await Fw(),Y=$0.resolveProviderModelCatalogKeys($),V=Object.assign({},...Y.map((G)=>X[G]??{}));if(Boolean($0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl))return $0.sortModelsByReleaseDate({...J,...j});if($==="openai-codex")return $0.sortModelsByReleaseDate({...W,...$0.filterOpenAICodexModels(Z),...J,...j});if($==="cline-pass"&&Object.keys(Z).length>0)return{...Z,...j};let H=$0.sortModelsByReleaseDate({...V,...W,...Z,...Q,...J});if($==="cline")return $0.sortModelsByReleaseDate({...$0.preferCanonicalModelIds(H,$0.VERCEL_OPENROUTER_MODEL_ID_ALIAS_RULES),...j});return $0.sortModelsByReleaseDate({...H,...j})}function Uw($,W){let Z=$0.resolveProviderModelCatalogKeys($);return Object.assign({},...Z.map((Q)=>W[Q]??{}))}function yZ($){let W=$?.trim();return W&&W.length>0?W:""}function lJ($){let W=$.apiKey?.trim()||$.accessToken?.trim();return W&&W.length>0?W:void 0}function Dw($){let W=2166136261;for(let Z=0;Z<$.length;Z+=1)W^=$.charCodeAt(Z),W+=(W<<1)+(W<<4)+(W<<7)+(W<<8)+(W<<24);return(W>>>0).toString(16)}function _w($,W){return`${$}:${yZ(W.baseUrl)}:${Dw(lJ(W)??"")}`}async function hZ($,W,Z=Kw){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await fetch($,{...W,signal:Q.signal})}finally{clearTimeout(J)}}function u2($,W,Z){if(Z&&!$.includes(W))$.push(W)}function kZ($,W){let Z=["streaming","tools"];return u2(Z,"images",Boolean(W.supportsImages)),u2(Z,"prompt-cache",Boolean(W.supportsPromptCache)),u2(Z,"reasoning",Boolean(W.supportsReasoning)),{id:$,name:W.name??$,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxTokens:W.maxTokens,capabilities:Z,releaseDate:W.releaseDate,status:"active"}}async function fw($,W){let Z=await hZ("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"}});if(!Z.ok)throw Error(`Baseten model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;if(Y.includes("whisper")||Y.includes("tts")||Y.includes("embedding"))continue;let V=X.supported_features??[];j[Y]=kZ(Y,{name:Y,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,supportsReasoning:V.includes("reasoning")||V.includes("reasoning_effort"),supportsImages:!1})}return j}function $F($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let W=Number($);return Number.isFinite(W)?W:void 0}return}async function Lw($,W){let Z=await hZ("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":W}});if(!Z.ok)throw Error(`Hicap model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;j[Y]=kZ(Y,{name:Y,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return j}async function Tw($,W){let Q=`${(yZ($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,J=await hZ(Q,{method:"GET",headers:{Authorization:`Bearer ${W}`,accept:"application/json"}});if(!J.ok)throw Error(`Poolside model refresh failed: HTTP ${J.status}`);let X=(await J.json())?.data??[],Y={};for(let V of X){let B=V.id?.trim();if(!B)continue;let H=V.supported_features??[],G=V.supported_sampling_parameters??[],K=V.input_modalities??[],F=["streaming"];u2(F,"tools",H.includes("tools")),u2(F,"reasoning",H.includes("reasoning")),u2(F,"temperature",G.includes("temperature")),u2(F,"images",K.includes("image"));let A={input:$F(V.pricing?.prompt),output:$F(V.pricing?.completion)};Y[B]={id:B,name:V.name??B,description:V.description,contextWindow:V.context_length,maxInputTokens:V.context_length,maxTokens:V.max_completion_tokens,capabilities:F,pricing:A.input!==void 0||A.output!==void 0?A:void 0,status:"active"}}return Y}function Ow($){let W=yZ($).replace(/\/+$/,"");if(!W)return"http://localhost:4000";return W.endsWith("/v1")?W.slice(0,-3):W}function zw($){return[`${$}/v1/model/info`,`${$}/model/info`]}async function qw($){let W=(await $.text().catch(()=>"")).replace(/\s+/g," ").trim(),Z=500,Q=W?`: ${W.slice(0,500)}${W.length>500?"...":""}`:"";return`HTTP ${$.status}${Q}`}async function Mw($,W){let Z=Ow($.baseUrl),Q=[],J=[["x-litellm-api-key",{"x-litellm-api-key":W}],["Authorization",{Authorization:`Bearer ${W}`}]];for(let j of zw(Z))for(let[X,Y]of J)try{let V=await hZ(j,{method:"GET",headers:{accept:"application/json",...Y}});if(V.ok){let H=(await V.json())?.data??[],G={};for(let K of H){let F=K.model_name?.trim(),D=K.litellm_params?.model?.trim()||F;if(!D)continue;let U=K.model_info,f=kZ(D,{name:F??D,maxTokens:U?.max_output_tokens??U?.max_tokens,maxInputTokens:U?.max_input_tokens??U?.max_tokens,supportsImages:U?.supports_vision,supportsPromptCache:U?.supports_prompt_caching,supportsReasoning:U?.supports_reasoning});if(G[D]=f,F)G[F]={...f,id:F,name:F}}return G}Q.push(`${new URL(j).pathname} (${X}): ${await qw(V)}`)}catch(V){let B=V instanceof Error?V.message:String(V);Q.push(`${new URL(j).pathname} (${X}): ${B}`)}throw Error(`LiteLLM model refresh failed. Attempts: ${Q.join("; ")}`)}var JF={baseten:fw,hicap:Lw,litellm:Mw,poolside:Tw},dJ=new Map,PZ=new Map;function Rw($,W){return`${$}:${yZ(W.baseUrl)}`}async function Ew($,W,Z){let Q=$0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],J=wZ(Z.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!J)return{};let j=W?.cacheTtlMs??QF,X=Rw($,Z),Y=Date.now(),V=dJ.get(X);if(V&&V.expiresAt>Y)return V.data;let B=PZ.get(X);if(B)return B;let H=NZ(J,$).then((G)=>{let K=Object.fromEntries(G.map((F)=>[F,kZ(F,{name:F})]));return dJ.set(X,{data:K,expiresAt:Y+j}),K}).finally(()=>{PZ.delete(X)});return PZ.set(X,H),H}function Nw(){dJ.clear(),PZ.clear()}async function ww($,W){let Z=lJ(W);if(!Z)return{};let Q=JF[$];if(!Q)return{};return Q(W,Z)}function Cw($,W,Z){if(!Z)return!1;if(!JF[$])return!1;if(W?.loadPrivateOnAuth===!1)return!1;return Boolean(lJ(Z))}async function Pw($,W,Z){let Q=W?.cacheTtlMs??QF,J=_w($,Z),j=Date.now(),X=uJ.get(J);if(X&&X.expiresAt>j)return X.data;let Y=CZ.get(J);if(Y)return Y;let V=ww($,Z).then((B)=>{return uJ.set(J,{data:B,expiresAt:j+Q}),B}).finally(()=>{CZ.delete(J)});return CZ.set(J,V),V}async function Sw($){return $0.fetchLiveProviderModels($,globalThis.fetch)}async function G6($={}){let W=$.url??bZ,Z=$.cacheTtlMs??Gw,Q=Date.now(),J=SZ.get(W);if(J&&J.expiresAt>Q)return J.data;let j=q5.get(W);if(j)return j;let X=Sw(W).then((Y)=>{return SZ.set(W,{data:Y,expiresAt:Q+Z}),Y}).finally(()=>{q5.delete(W)});return q5.set(W,X),X}function pJ($){if($){SZ.delete($),q5.delete($);return}SZ.clear(),q5.clear()}function rJ(){uJ.clear(),CZ.clear()}function bw($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{baseUrl:Z.baseUrl,modelId:Z.modelId,capabilities:ZF(Z.capabilities)}]))}var M5=bw(Hw());function IZ($){let W=Bw($);if(!W)return;return{baseUrl:W.baseUrl||void 0,modelId:W.modelId,knownModels:W.knownModels,capabilities:ZF(W.capabilities)}}async function R5($,W,Z){let Q=IZ($);if(!Q)return;try{let J=W?.loadLatestOnInit?await G6(W):void 0,j=J?Uw($,J):{},X=Z&&Cw($,W,Z)?await Pw($,W,Z):{},V=Boolean($0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Z??{providerId:$,modelId:Q.modelId,baseUrl:Q.baseUrl}:Z,B=V?await Ew($,W,V).catch(()=>({})):{},H=await Aw($,Q.knownModels,j,X,B,Z?.knownModels);return{...Q,knownModels:H}}catch(J){if(W?.failOnError)throw J;if($==="litellm")return{...Q,knownModels:{}};return Q}}var E5=o0.BUILT_IN_PROVIDER,iJ=o0.BUILT_IN_PROVIDER_IDS,nJ=o0.isBuiltInProviderId,K6=o0.normalizeProviderId,N5=N.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),xZ=N.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),gZ=N.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),mZ=N.object({apiKey:N.string().optional(),accessToken:N.string().optional(),refreshToken:N.string().optional(),expiresAt:N.number().int().positive().optional(),accountId:N.string().optional(),organizationId:N.string().optional(),organizationName:N.string().optional(),memberId:N.string().optional(),metadata:N.record(N.string(),N.unknown()).optional()}),yw=N.enum(["none","low","medium","high","xhigh"]),vZ=N.object({enabled:N.boolean().optional(),effort:yw.optional(),budgetTokens:N.number().int().positive().optional()}),cZ=N.object({accessKey:N.string().optional(),secretKey:N.string().optional(),sessionToken:N.string().optional(),region:N.string().optional(),profile:N.string().optional(),authentication:N.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:N.boolean().optional(),useCrossRegionInference:N.boolean().optional(),useGlobalInference:N.boolean().optional(),endpoint:N.string().url().optional(),customModelBaseId:N.string().optional()}),uZ=N.object({projectId:N.string().optional(),region:N.string().optional()}),dZ=N.object({apiVersion:N.string().optional(),useIdentity:N.boolean().optional()}),lZ=N.object({clientId:N.string().optional(),clientSecret:N.string().optional(),tokenUrl:N.string().url().optional(),resourceGroup:N.string().optional(),deploymentId:N.string().optional(),useOrchestrationMode:N.boolean().optional(),api:N.enum(["orchestration","foundation-models"]).optional(),defaultSettings:N.record(N.string(),N.unknown()).optional()}),pZ=N.object({mode:N.enum(["internal","external"]).optional(),usePromptCache:N.boolean().optional()}),rZ=N.object({loadLatestOnInit:N.boolean().optional(),loadPrivateOnAuth:N.boolean().optional(),url:N.string().url().optional(),cacheTtlMs:N.number().int().positive().optional(),failOnError:N.boolean().optional()}),g$=N.object({provider:N5,apiKey:N.string().optional(),auth:mZ.optional(),model:N.string().optional(),protocol:xZ.optional(),client:gZ.optional(),routingProviderId:N5.optional(),maxTokens:N.number().int().positive().optional(),contextWindow:N.number().int().positive().optional(),baseUrl:N.string().url().optional(),headers:N.record(N.string(),N.string()).optional(),timeout:N.number().int().positive().optional(),reasoning:vZ.optional(),aws:cZ.optional(),gcp:uZ.optional(),azure:dZ.optional(),sap:lZ.optional(),oca:pZ.optional(),region:N.string().optional(),apiLine:N.enum(["china","international"]).optional(),capabilities:N.array(N.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:rZ.optional()});function iZ($){return g$.parse($)}function nZ($){return g$.safeParse($)}function hw($){return $.protocol==="openai-responses"||$.client==="openai"}function s0($,W={}){let Z=$.provider,Q=K6(Z),J=W.includeKnownModels!==!1,j=$.reasoning?.effort||"none",X=j==="none"?void 0:j,Y=M5[Q],V=Object.assign({},...o0.resolveProviderModelCatalogKeys(Q).map((D)=>o0.getGeneratedModelsForProvider(D))),B=Object.keys(V)[0],H=h8(Q,$),G=$.baseUrl??(Q==="oca"?$.oca?.mode==="internal"?xW:gW:Y?.baseUrl),K=$.routingProviderId??(hw($)&&Q!==E5.OPENAI_NATIVE?E5.OPENAI_NATIVE:void 0),F=J?Y?.knownModels??(Object.keys(V).length>0?V:void 0):void 0,A={providerId:Z,clientType:$.client,routingProviderId:K,modelId:$.model??Y?.modelId??B??"default",...J?{knownModels:F}:{},apiKey:H,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:G,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:X,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??Y?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(A).filter(([D,U])=>U!==void 0))}function aJ($){let W=iZ($);return s0(W)}function oJ($){let W=nZ($);if(W.success)return{success:!0,config:s0(W.data)};return{success:!1,error:W.error}}var F6=g$;var aZ=m$.object({settings:g$,updatedAt:m$.string().datetime(),tokenSource:m$.enum(["manual","oauth","migration"]).default("manual")}),A6=m$.object({version:m$.literal(1),lastUsedProvider:m$.string().min(1).optional(),providers:m$.record(m$.string(),aZ)});function v$(){return{version:1,providers:{}}}X1();var VF={};w(VF,{InMemoryWorkspaceManager:()=>U6});import{upsertWorkspaceInfo as kw,WorkspaceManifestSchema as sJ}from"@cline/shared";class U6{manifest;listeners=new Set;constructor($){this.manifest=sJ.parse($??{workspaces:{}})}async addWorkspacePath($){let W=await _8($);return this.manifest=kw(this.manifest,W),this.emit({type:"workspace_added",workspace:W}),W}async switchWorkspace($){let W=_1($),Z=this.manifest.workspaces[W];if(Z)return this.manifest=sJ.parse({...this.manifest,currentWorkspacePath:W}),this.emit({type:"workspace_switched",workspace:Z}),Z;let Q=await this.addWorkspacePath(W);return this.manifest=sJ.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let W=_1($);return this.manifest.workspaces[W]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let W of this.listeners)W($)}}R0();import{createHash as Iw}from"node:crypto";var BF=new Set,HF=new Set;function xw($){return Iw("sha256").update($).digest("hex")}function gw($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function GF($){if(!$.telemetry)return;let W=xw($.rootPath),Z=$.rootCount??1;if(!BF.has(W))BF.add(W),s9($.telemetry,{root_count:Z,vcs_types:gw($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!HF.has(W)){HF.add(W);let Q=Error($.initError.message);Q.name=$.initError.errorType||"Error",t9($.telemetry,Q,{fallback_to_single_root:!0,workspace_count:Z})}}function cw($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function uw($,W,Z){if(W.length>0)for(let j of W)Z?.log(j.message,{severity:"warn"});if($.length===0)return;let Q=$.slice(0,3).map(cw).join("; "),J=$.length>3?`; and ${$.length-3} more`:"";Z?.log(`Some plugins failed to initialize. ${Q}${J}. Use --verbose for more details.`,{severity:"warn"});for(let j of $)Z?.log(`Plugin initialization failed (${j.phase}) for ${j.pluginPath}`,{severity:"warn",stack:j.stack,pluginPath:j.pluginPath,pluginName:j.pluginName})}function dw($,W){let Z=typeof $.thinking==="boolean",Q=typeof $.reasoningEffort==="string";if(!Z&&!Q)return W;return{...W??{},...Z?{enabled:$.thinking}:{},...Q?{effort:$.reasoningEffort}:{}}}function KF($,W){return vw($,W)}function lw($){let W=0;for(let Z of $??[]){if(Z.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0)?.kind==="recovery_notice")continue;W+=1}return W}function pw($,W,Z,Q,J,j){let X=Q.getProviderSettings($.providerId),Y=J||X?.modelCatalog?{...J??{},...X?.modelCatalog??{}}:void 0,V=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,B=mw({providerId:$.providerId,sessionId:W,source:Z,defaultSource:F0.CLI,client:{name:$.extensionContext?.client?.name,version:$.extensionContext?.client?.version,versionHeaderFallback:$.headers?.["X-CLIENT-VERSION"],platform:$.extensionContext?.client?.platform,platformVersion:$.extensionContext?.client?.platformVersion,isMultiRoot:$.extensionContext?.client?.isMultiRoot},coreVersion:R8,openAiCodex:{accountId:V?.accountId??X?.auth?.accountId,accessToken:V?.accessToken??$.apiKey??X?.auth?.accessToken??X?.apiKey,userAgentVersion:process.env.npm_package_version},headers:{stored:X?.headers,config:$.headers,session:V?.headers}}),H={...X??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??X?.apiKey,baseUrl:$.baseUrl??X?.baseUrl,headers:void 0,reasoning:dw($,X?.reasoning),modelCatalog:Y},G={...s0(H),...V??{}};if(B)G.headers=B;if($.knownModels)G.knownModels=$.knownModels;if($.extensionContext)G.extensionContext=$.extensionContext;let F=$.fetch??G.fetch??j;if(F)G.fetch=F;return G}async function FF($){let{input:W,sessionId:Z,providerSettingsManager:Q,defaultTelemetry:J,defaultCapabilities:j,defaultToolPolicies:X,defaultFetch:Y,onPluginEvent:V,onTeamEvent:B,createSubAgentLifecycleCallbacks:H,createSpawnTool:G,localRuntime:K,readSessionMetadata:F,writeSessionMetadata:A}=$,D=Z$(W.config),{modelCatalogDefaults:U,userInstructionService:f,configExtensions:_,onTeamRestored:R,...O}=K??{},T=Object.keys(O).length>0?O:void 0,{workspaceInfo:L,workspaceMetadata:C,gitState:E,durationMs:p,vcsType:x,initError:P}=await b7(D),r=T?.extensionContext,d={...r??{},workspace:{...L,...r?.workspace??{}},session:{...r?.session??{},sessionId:Z},logger:r?.logger??T?.logger,telemetry:r?.telemetry??T?.telemetry??J};GF({telemetry:d.telemetry,rootPath:L.rootPath,workspaceInfo:L,rootCount:1,vcsType:x,durationMs:p,initError:P,featureFlagEnabled:!0});let I1=H6({cwd:W.config.cwd,workspacePath:D,rootSessionId:Z,logger:T?.logger,workspaceInfo:L}),$2=GK(T?.hooks)?void 0:B6({rootSessionId:Z,workspacePath:D,workspaceInfo:L}),A$=c2([T?.hooks,$2]),I0;if(KF(_,"plugins"))try{I0=await X6({pluginPaths:T?.pluginPaths,workspacePath:D,cwd:W.config.cwd,onEvent:V,providerId:W.config.providerId,modelId:W.config.modelId,workspaceInfo:L,session:d.session,client:d.client,user:d.user,logger:d.logger,telemetry:d.telemetry,automation:d.automation}),uw(I0.failures,I0.warnings,T?.logger)}catch(t6){let F8=t6 instanceof Error?t6.message:String(t6);T?.logger?.log?.(`plugin loading failed; continuing without plugins (${F8})`)}let D1=UJ(I1?[I1]:void 0,UJ(T?.extensions,_W(I0?.extensions))),K8=KF(_,"plugins")?J$(I0?.pluginPaths??[]):void 0,V0={...W.config,...T??{},sessionId:Z,hooks:A$,extensions:D1,extensionContext:d,telemetry:d.telemetry},d0=pw(V0,Z,W.source,Q,U,Y),J1=c2([V0.hooks,V0.checkpoint?.enabled===!0?dK({cwd:V0.cwd,sessionId:Z,logger:V0.logger,createCheckpoint:V0.checkpoint?.createCheckpoint,initialRunCount:lw(W.initialMessages),readSessionMetadata:F,writeSessionMetadata:A}):void 0]),y={...V0,providerConfig:d0,workspaceMetadata:C,hooks:J1},j1=W.toolPolicies??V0.toolPolicies??X,k=P0(j,W.capabilities),W0=k?.requestToolApproval,T0=k?.toolExecutors,q0=H?.(y),d9=new U6({currentWorkspacePath:L.rootPath,workspaces:{[L.rootPath]:L}});return{effectiveInput:W,config:y,providerConfig:d0,workspaceMetadata:C,workspaceInfo:L,gitState:E,extensions:D1,hooks:J1,toolPolicies:j1,requestToolApproval:W0,pluginSandboxShutdown:I0?.shutdown,runtimeBuilderInput:{config:y,hooks:J1,extensions:D1,onTeamEvent:B,createSpawnTool:G,onTeamRestored:R,onSubAgentEvent:q0?.onSubAgentEvent,onSubAgentStart:q0?.onSubAgentStart,onSubAgentEnd:q0?.onSubAgentEnd,userInstructionService:f,pluginSkillDirectories:K8,configExtensions:_,toolExecutors:T0,toolPolicies:j1,workspaceManager:d9,logger:y.logger,telemetry:y.telemetry,requestToolApproval:W0}}}import{existsSync as oZ,mkdirSync as rw,readdirSync as iw,rmdirSync as nw,rmSync as aw,unlinkSync as ow}from"node:fs";import{dirname as AF,join as w5}from"node:path";function X0(){return new Date().toISOString()}function C5($){if(!$||!oZ($))return;try{ow($)}catch{}}function sw($){let W=t8($);if(W)return{rootSessionId:W.rootSessionId,fileStem:`${W.agentId}__${W.teamTaskId}`};let Z=Y5($);if(Z)return{rootSessionId:Z.rootSessionId,fileStem:Z.agentId};return{rootSessionId:$,fileStem:$}}class tJ{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return w5(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let W=this.sessionArtifactsDir($);if(!oZ(W))rw(W,{recursive:!0});return W}sessionMessagesPath($){return w5(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionCompactionPath($){return w5(this.sessionArtifactsDir($),`${$}.compaction.json`)}sessionManifestPath($,W=!1){let Z=W?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return w5(Z,`${$}.json`)}removeSessionDirIfEmpty($){let W=this.sessionArtifactsDir($),Z=this.ensureSessionsDir();while(W.startsWith(Z)&&W!==Z){if(!oZ(W)){W=AF(W);continue}try{if(iw(W).length>0)break;nw(W)}catch{break}W=AF(W)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!oZ($))return;try{aw($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,W,Z){let{rootSessionId:Q,fileStem:J}=sw($),j=this.sessionArtifactsDir(Q);return{messagesPath:w5(j,`${J}.messages.json`)}}}import{resolveDocumentsExtensionPath as tw}from"@cline/shared/storage";R0();function UF($,W,Z,Q,J){if(Z)$W($.telemetry,{ulid:W,apiProvider:$.providerId,...J});else e9($.telemetry,{ulid:W,apiProvider:$.providerId,...J});ew($.telemetry,{workspacePath:Q})}function ew($,W){let Z=tw("Hooks"),Q=I$(W.workspacePath),J=new Map;for(let j of Q){let X=j.hookEventName??"unknown",Y=J.get(X)??{global:0,workspace:0};if(j.path===Z||j.path.startsWith(`${Z}/`))Y.global+=1;else Y.workspace+=1;J.set(X,Y)}for(let[j,X]of J.entries())BW($,j,X.global,X.workspace)}function DF($,W){for(let Z of W.mentions)YW($,Z,W.matchedFiles.includes(Z)?1:0,"file",!W.matchedFiles.includes(Z));for(let Z of W.matchedFiles)jW($,"file",Z.length);for(let Z of W.ignoredMentions)XW($,"file","not_found",Z)}var U_={};w(U_,{ProviderSettingsManager:()=>k1});import{chmodSync as O_,existsSync as UY,mkdirSync as hg,readFileSync as kg,renameSync as Ig,rmSync as xg,writeFileSync as gg}from"node:fs";import{basename as z_,dirname as DY}from"node:path";import{resolveProviderSettingsPath as mg}from"@cline/shared/storage";var q={};w(q,{writeModelsFileSync:()=>w9,writeHubDiscovery:()=>OW,writeGlobalSettings:()=>f1,withHubStartupLock:()=>zW,verifyHubConnection:()=>z1,updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>T6,updateMcpServerOAuthStateAsync:()=>i5,updateMcpServerOAuthState:()=>i2,updateLocalProvider:()=>Y7,uninstallPlugin:()=>T9,uninstallMarketplaceSkill:()=>rQ,uninstallMarketplacePlugin:()=>iQ,uninstallMarketplaceMcpServerFromSettings:()=>lQ,uninstallMarketplaceEntry:()=>NX,truncateNotificationBody:()=>k9,truncateCommandOutput:()=>L2,toggleDisabledTool:()=>UW,toTeamProgressLifecycleEvent:()=>S6,toProviderConfig:()=>s0,toHubStatusUrl:()=>s7,toHubHealthUrl:()=>qW,toHookConfigFileName:()=>O5,syncStoredProviderRegistration:()=>vX,syncPluginMcpServersToSettings:()=>f9,summarizeUsageFromMessages:()=>$6,stopLocalHubServerGracefully:()=>B3,startLocalOAuthServer:()=>H1,startHubWebSocketServer:()=>g9,startHubServer:()=>f_,startClineDeviceAuth:()=>O3,splitCoreSessionConfig:()=>D4,spawnDetachedHubServerWithRetry:()=>N8,spawnDetachedHubServer:()=>Q3,setTelemetryOptOutGlobally:()=>CV,setSdkLogger:()=>U3,setMcpServerDisabled:()=>p2,setDisabledTools:()=>l7,setDisabledPlugin:()=>xV,setCompactionStrategyGlobally:()=>yV,setAutoUpdateEnabledGlobally:()=>SV,sendHubCommand:()=>AB,sdkDebug:()=>s,saveProviderOAuthCredentials:()=>F2,saveLocalProviderSettings:()=>iX,saveLocalProviderOAuthCredentials:()=>sX,sanitizeSessionToken:()=>h2,safeParseSettings:()=>nZ,safeCreateProviderConfig:()=>oJ,runSubprocessEvent:()=>g6,runHook:()=>v6,reviveTeamStateDates:()=>GZ,restartLocalHubIfIdleAfterStartupTimeout:()=>wW,resolveWorkspaceHubOwnerContext:()=>sV,resolveWorkflowsConfigSearchPaths:()=>v5,resolveSkillsConfigSearchPaths:()=>g5,resolveSharedHubOwnerContext:()=>V1,resolveSessionBackend:()=>oj,resolveRulesConfigSearchPaths:()=>m5,resolveProviderConfig:()=>R5,resolveProviderApiKeyFromSettings:()=>w3,resolveProductionHubOwnerContext:()=>O1,resolvePluginSkillDirectoriesFromPaths:()=>J$,resolvePluginConfigSearchPaths:()=>_5,resolveModelsRegistryPath:()=>h1,resolveMcpServerRegistrations:()=>t0,resolveMarketplaceMcpServerName:()=>z9,resolveLocalClineAuthToken:()=>eX,resolveHubUrl:()=>H3,resolveHubOwnerContext:()=>r1,resolveHubEndpointOptions:()=>T1,resolveHubBuildId:()=>TW,resolveHooksConfigSearchPaths:()=>L5,resolveDisabledToolNames:()=>L1,resolveDisabledPluginPaths:()=>G4,resolveDefaultMcpSettingsPath:()=>J0,resolveDefaultHubPort:()=>E8,resolveDefaultHubPathname:()=>Z3,resolveDefaultHubHost:()=>W3,resolveCoreSelectedToolIds:()=>FZ,resolveCoreDistinctId:()=>x0,resolveCompatibleLocalHubUrl:()=>T4,resolveClineDir:()=>iV,resolveClineDataDir:()=>Y2,resolveAndLoadAgentPlugins:()=>X6,resolveAgentPluginPaths:()=>Q$,requestHubShutdown:()=>L4,requestDesktopToolApproval:()=>GX,removePluginMcpServersFromSettings:()=>L9,rememberRecoverableLocalHubUrl:()=>O$,registerRemoteConfigSessionBlobUpload:()=>kQ,registerMcpServersFromSettingsFile:()=>n2,registerDisposable:()=>Pg,refreshProviderModelsFromSource:()=>nX,refreshOpenAICodexToken:()=>IW,refreshOcaToken:()=>vW,refreshClineToken:()=>hW,readSessionCheckpointHistory:()=>Z8,readRemoteConfigSessionBlobUploadMetadata:()=>ZX,readModelsFileSync:()=>n6,readHubDiscovery:()=>D0,readGlobalSettings:()=>E0,readCompactionStrategyGlobally:()=>bV,readBearerToken:()=>f7,projectSessionCompactionState:()=>A2,probeHubServer:()=>i1,probeHubConnection:()=>FB,prewarmFileIndex:()=>WZ,prewarmDetachedHubServer:()=>RW,prepareRemoteConfigCoreIntegration:()=>JX,parseWorkflowConfigFromMarkdown:()=>x5,parseUserCommandEnvelope:()=>Cg,parseSkillConfigFromMarkdown:()=>k5,parseSettings:()=>iZ,parseSessionCompactionState:()=>G1,parseRuleConfigFromMarkdown:()=>I5,parsePluginSource:()=>Z7,parseMcpInstallArgs:()=>_9,parseHookEventPayload:()=>m6,parseConfiguredAgentConfig:()=>Y9,normalizeWorkspacePath:()=>_1,normalizeUserInput:()=>wg,normalizeSdkError:()=>Ng,normalizeRuntimeCapabilities:()=>P0,normalizeProviderId:()=>K6,normalizeOAuthProvider:()=>aX,normalizeHubWebSocketUrl:()=>z$,noopBasicLogger:()=>Eg,migrateLegacyProviderSettings:()=>y9,mergeRulesForSystemPrompt:()=>D8,mergeAgentHooks:()=>c2,marketplaceEntryKey:()=>EX,markLocalProviderEnabled:()=>lX,makeTeamTaskSubSessionId:()=>X5,makeSubSessionId:()=>s8,loginOpenAICodex:()=>q4,loginOcaOAuth:()=>N4,loginLocalProvider:()=>oX,loginClineOAuth:()=>O4,loginAndSaveProviderOAuthCredentials:()=>C4,loginAndSaveLocalProviderOAuthCredentials:()=>tX,loadOpenTelemetryAdapter:()=>ex,loadMcpSettingsFile:()=>l2,loadLlmsConfigFromFile:()=>GY,loadConfiguredAgentConfigs:()=>w6,loadAgentPluginsFromPathsWithDiagnostics:()=>x2,loadAgentPluginsFromPaths:()=>fZ,loadAgentPluginFromPath:()=>U5,listSessionHistoryFromBackend:()=>Cj,listPluginToolsWithDiagnostics:()=>DQ,listPluginTools:()=>o5,listMcpServerOAuthStatuses:()=>n5,listLocalProviders:()=>pX,listHookConfigFiles:()=>I$,isToolDisabledGlobally:()=>hV,isTelemetryOptedOutGlobally:()=>AW,isSessionNotFoundError:()=>p1,isRuleEnabled:()=>l9,isPluginDisabledGlobally:()=>IV,isOfficialPluginSlug:()=>W7,isOAuthProvider:()=>K2,isMarketplaceSkillInstalled:()=>pQ,isLocalHubOrigin:()=>AY,isLocalHubHostName:()=>L7,isHubReconnectableTransportError:()=>Y3,isHubCommandTimeoutError:()=>NW,isDiscoveryFilePresent:()=>aV,isClinePassLimitMessage:()=>Fg,isClinePassLimitError:()=>Kg,isClineOrgIndividualInferenceSubscriptionMessage:()=>Gg,isClineOrgIndividualInferenceSubscriptionError:()=>Hg,isClineNotSubscribedMessage:()=>Bg,isClineNotSubscribedError:()=>Vg,isClineAccountActionRequest:()=>sZ,isBuiltInProviderId:()=>nJ,isAutoUpdateEnabledGlobally:()=>PV,installPlugin:()=>yX,installMcpServer:()=>KX,identifyAccount:()=>c1,hashSecret:()=>N0,hasMcpSettingsFile:()=>X$,getValidOpenAICodexCredentials:()=>M4,getValidOcaCredentials:()=>w4,getValidClineCredentials:()=>z4,getProviderOAuthCredentialsFromSettings:()=>P4,getProviderConfigFields:()=>$Y,getProviderConfig:()=>IZ,getProviderAuthStorageId:()=>N3,getProviderAuthHandler:()=>H0,getPersistedProviderApiKey:()=>h8,getMcpServerOAuthState:()=>r2,getMarketplaceSkillCandidates:()=>q9,getLocalProviderModels:()=>rX,getLiveModelsCatalog:()=>G6,getGlobalMarketplaceSkillPaths:()=>M9,getFileIndex:()=>t1,getCurrentContextSize:()=>LJ,getCoreHeadlessToolNames:()=>j5,getCoreDefaultEnabledToolIds:()=>KZ,getCoreBuiltinToolCatalog:()=>b2,getCoreAcpToolNames:()=>AZ,getClinePassSubscriptionUrl:()=>Yg,getClineOrgIndividualInferenceSubscriptionMessage:()=>Xg,getClineNotSubscribedMessage:()=>jg,getClineDefaultSystemPrompt:()=>Ag,generateWorkspaceInfoWithDiagnostics:()=>$4,generateWorkspaceInfo:()=>_8,formatRulesForSystemPrompt:()=>U8,formatProviderOAuthApiKey:()=>C3,formatDisplayUserInput:()=>Rg,findInstalledGlobalMarketplaceSkillName:()=>R9,findCheckpointForRun:()=>I6,filterExtensionToolRegistrations:()=>_W,filterDisabledTools:()=>u1,filterDisabledPluginPaths:()=>DW,fetchClineRecommendedModels:()=>BY,extractClinePassLimitMessage:()=>Jg,executeClineAccountAction:()=>tZ,ensureHubWebSocketServer:()=>T7,ensureHubServer:()=>L_,ensureDetachedHubServer:()=>QB,ensureCustomProvidersLoadedSync:()=>S9,ensureCustomProvidersLoaded:()=>b9,ensureCompatibleLocalHubUrl:()=>H2,enrichPromptWithMentions:()=>d8,emptyWorkspaceManifest:()=>zg,emptyStoredProviderSettings:()=>v$,discoverPluginModulePaths:()=>f5,disablePluginMcpServersInSettings:()=>DX,deriveSubsessionStatus:()=>V5,deleteLocalProvider:()=>V7,defineLlmsConfig:()=>HY,createWorkflowsConfigDefinition:()=>d5,createUserInstructionConfigService:()=>c$,createToolPoliciesWithPreset:()=>QZ,createTool:()=>Og,createTeamName:()=>gQ,createSubprocessHooks:()=>SQ,createSpawnAgentTool:()=>y$,createSkillsConfigDefinition:()=>c5,createShellTool:()=>o4,createShellExecutor:()=>T2,createSessionHost:()=>h6,createSessionCompactionState:()=>k8,createRuntimeHost:()=>h6,createRulesConfigDefinition:()=>u5,createRemoteConfigSessionMessagesArtifactUploader:()=>QX,createProviderConfig:()=>aJ,createOpenTelemetryTelemetryService:()=>U4,createOAuthClientCallbacks:()=>D6,createMcpTools:()=>M6,createLocalHubScheduleRuntimeHandlers:()=>__,createLlmsSdk:()=>FY,createInitialAccumulatedUsage:()=>z0,createInMemoryHubOwnerContext:()=>nV,createHubServerUrl:()=>Y1,createHubAuthToken:()=>LW,createHookConfigFileHooks:()=>z5,createHookConfigFileExtension:()=>H6,createHookAuditHooks:()=>B6,createEditorExecutor:()=>M2,createDisabledMcpToolPolicy:()=>a5,createDisabledMcpToolPolicies:()=>UQ,createDelegatedAgentConfigProvider:()=>S$,createDelegatedAgent:()=>b$,createDefaultToolsWithPreset:()=>JZ,createDefaultTools:()=>N$,createDefaultShellExecutor:()=>$5,createDefaultMcpServerClientFactory:()=>z6,createDefaultExecutors:()=>l8,createCoreSettingsService:()=>o2,createCoreSessionSnapshot:()=>N1,createContributionRegistry:()=>Tg,createContextCompactionPrepareTurn:()=>m4,createConfiguredTelemetryService:()=>d1,createConfiguredTelemetryHandle:()=>M8,createConfiguredAgentTools:()=>C6,createCompactionStateAwarePrepareTurn:()=>v4,createClineTelemetryServiceMetadata:()=>Lg,createClineTelemetryServiceConfig:()=>fg,createCheckpointComparePlan:()=>NQ,createBuiltinTools:()=>y2,createApplyPatchExecutor:()=>q2,createAgentTeamsTools:()=>S2,createAgentRuntime:()=>yg,createAgentHooksExtension:()=>Y6,connectToHub:()=>CW,computePatchChanges:()=>c8,completeClineDeviceAuth:()=>z3,compareCheckpointToWorkspace:()=>A9,collectPluginMcpOAuthCandidates:()=>Q7,clearPrivateModelsCatalogCache:()=>rJ,clearLiveModelsCatalogCache:()=>pJ,clearHubDiscovery:()=>g0,captureWorkspacePathResolved:()=>zV,captureWorkspaceInitialized:()=>s9,captureWorkspaceInitError:()=>t9,captureToolUsage:()=>T8,captureTokenUsage:()=>WW,captureTaskRestarted:()=>$W,captureTaskCreated:()=>e9,captureTaskCompleted:()=>Y4,captureSubagentExecution:()=>B4,captureSkillUsed:()=>QW,captureSdkError:()=>_g,captureProviderConfigured:()=>qV,captureProviderApiError:()=>V4,captureModeSwitch:()=>ZW,captureMentionUsed:()=>jW,captureMentionSearchResults:()=>YW,captureMentionFailed:()=>XW,captureHookDiscovery:()=>BW,captureExtensionActivated:()=>OV,captureDiffEditFailure:()=>JW,captureConversationTurnEvent:()=>L8,captureCompactionSkipped:()=>GW,captureCompactionExecuted:()=>HW,captureAuthSucceeded:()=>m1,captureAuthStarted:()=>g1,captureAuthLoggedOut:()=>L$,captureAuthFailed:()=>v1,captureAgentUnexpectedReasoningTokens:()=>TV,captureAgentTeamCreated:()=>VW,captureAgentCreated:()=>T$,buildWorkspaceMetadata:()=>W4,buildTeamProgressSummary:()=>P6,buildSdkErrorProperties:()=>Ug,buildRemoteConfigSessionBlobUploadMetadata:()=>yQ,buildMcpInstallTransport:()=>mQ,buildDelegatedAgentConfig:()=>C2,buildConnectionUpdate:()=>jJ,buildConfiguredAgentToolName:()=>V9,buildConfiguredAgentToolDescriptors:()=>B9,buildCheckpointWorkspaceDiff:()=>wQ,bootstrapAgentTeams:()=>o8,authorizeMcpServerOAuth:()=>GQ,addLocalProvider:()=>dX,accumulateUsageTotals:()=>L0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>h5,UnifiedConfigFileWatcher:()=>d2,ToolPresets:()=>a0,TelemetryService:()=>z8,TelemetryLoggerSink:()=>A4,TEAM_TOOL_NAMES:()=>a8,SubprocessSandbox:()=>Q6,StructuredCommandInputSchema:()=>_2,StoredProviderSettingsSchema:()=>A6,StoredProviderSettingsEntrySchema:()=>aZ,SqliteTeamStore:()=>j8,SqliteSessionStore:()=>C1,SessionVersioningService:()=>o$,SessionVersioningError:()=>c0,SessionSource:()=>F0,SessionNotFoundError:()=>l1,SapSettingsSchema:()=>lZ,SKILLS_CONFIG_DIRECTORY_NAME:()=>y5,SESSION_STATUSES:()=>B5,SESSION_NOT_FOUND_ERROR_CODE:()=>X2,SDK_ERROR_TELEMETRY_EVENT:()=>Sg,RpcClineAccountService:()=>S5,RemoteRuntimeHost:()=>N6,ReasoningSettingsSchema:()=>vZ,RULES_CONFIG_DIRECTORY_NAME:()=>jQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>hQ,ProviderSettingsSchema:()=>g$,ProviderSettingsManager:()=>k1,ProviderProtocolSchema:()=>xZ,ProviderIdSchema:()=>N5,ProviderClientSchema:()=>gZ,PatchActionType:()=>z2,OpenTelemetryProvider:()=>q8,OcaSettingsSchema:()=>pZ,OPENAI_COMPATIBLE_PROVIDERS:()=>M5,NodeHubClient:()=>B1,NoOpFeatureFlagsProvider:()=>W8,NativeHubTransportAdapter:()=>x9,ModelCatalogSettingsSchema:()=>rZ,McpSettingsUpdateSkippedError:()=>L6,McpSettingsMutatorPurityError:()=>u$,McpSettingsLockTimeoutError:()=>d$,MAX_COMMAND_OUTPUT_CHARS:()=>a1,LocalRuntimeHost:()=>b1,Llms:()=>$g,InMemoryWorkspaceManager:()=>U6,InMemoryMcpManager:()=>a2,HubUIClient:()=>F3,HubTransportError:()=>y0,HubSessionClient:()=>K3,HubServerTransport:()=>o6,HubScheduleService:()=>f8,HubScheduleCommandService:()=>A8,HubRuntimeHost:()=>Y$,HubCommandError:()=>w8,HookEventPayloadSchema:()=>PQ,HookEventNameSchema:()=>CQ,HookConfigFileName:()=>V6,HOOK_CONFIG_FILE_EVENT_MAP:()=>T5,HOOKS_CONFIG_DIRECTORY_NAME:()=>MZ,GlobalSettingsSchema:()=>H4,GcpSettingsSchema:()=>uZ,FileTeamPersistenceStore:()=>G7,FeatureFlagsService:()=>$8,FeatureFlagDefaultValue:()=>Mg,FEATURE_FLAGS:()=>qg,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>_7,DefaultToolNames:()=>O0,DefaultRuntimeBuilder:()=>d6,DefaultLlmsSdk:()=>h9,DEFAULT_MODELS_CATALOG_URL:()=>bZ,DEFAULT_HUB_PORT:()=>e7,DEFAULT_HUB_PATHNAME:()=>$3,DEFAULT_HUB_HOST:()=>t7,CoreSettingsService:()=>l$,CoreSessionService:()=>S1,ContributionRegistry:()=>Dg,CommandExitError:()=>o1,ClinePassLimitError:()=>Qg,ClineOrgIndividualInferenceSubscriptionError:()=>Zg,ClineNotSubscribedError:()=>Wg,ClineCore:()=>U9,ClineAccountService:()=>P5,ChatViewStateSchema:()=>XY,ChatSummarySchema:()=>D7,ChatSessionStatusSchema:()=>F7,ChatSessionConfigSchema:()=>K7,ChatMessageSchema:()=>U7,ChatMessageRoleSchema:()=>A7,CORE_TELEMETRY_EVENTS:()=>v,CORE_BUILD_VERSION:()=>YY,BrowserWebSocketHubAdapter:()=>I9,BUILT_IN_PROVIDER_IDS:()=>iJ,BUILT_IN_PROVIDER:()=>E5,AzureSettingsSchema:()=>dZ,AwsSettingsSchema:()=>cZ,AuthSettingsSchema:()=>mZ,AgentTeamsRuntime:()=>e2,AgentTeam:()=>y6,Agent:()=>bg,ALL_DEFAULT_TOOL_NAMES:()=>D$});M(q,f00);import*as $g from"@cline/llms";import{ClineNotSubscribedError as Wg,ClineOrgIndividualInferenceSubscriptionError as Zg,ClinePassLimitError as Qg,extractClinePassLimitMessage as Jg,getClineNotSubscribedMessage as jg,getClineOrgIndividualInferenceSubscriptionMessage as Xg,getClinePassSubscriptionUrl as Yg,isClineNotSubscribedError as Vg,isClineNotSubscribedMessage as Bg,isClineOrgIndividualInferenceSubscriptionError as Hg,isClineOrgIndividualInferenceSubscriptionMessage as Gg,isClinePassLimitError as Kg,isClinePassLimitMessage as Fg}from"@cline/llms";import{buildClineSystemPrompt as Ag,buildSdkErrorProperties as Ug,ContributionRegistry as Dg,captureSdkError as _g,createClineTelemetryServiceConfig as fg,createClineTelemetryServiceMetadata as Lg,createContributionRegistry as Tg,createTool as Og,emptyWorkspaceManifest as zg,FEATURE_FLAGS as qg,FeatureFlagDefaultValue as Mg,formatDisplayUserInput as Rg,noopBasicLogger as Eg,normalizeSdkError as Ng,normalizeUserInput as wg,parseUserCommandEnvelope as Cg,registerDisposable as Pg,SDK_ERROR_TELEMETRY_EVENT as Sg}from"@cline/shared";import"@cline/shared/storage";var fF={};w(fF,{isClineAccountActionRequest:()=>sZ,executeClineAccountAction:()=>tZ,RpcClineAccountService:()=>S5,ClineAccountService:()=>P5});function $C($){if(typeof $!=="object"||$===null||!("error"in $))return;let W=$.error;return typeof W==="string"&&W.trim()?W:void 0}function _F($,W,Z){let Q=$C(Z);if(Q)return Q;let J=W.trim();if(J){let j=J.length>200?`${J.slice(0,200)}...`:J;return`Cline account request failed with status ${$}: ${j}`}return`Cline account request failed with status ${$}`}class P5{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let W=$.apiBaseUrl.trim();if(!W)throw Error("apiBaseUrl is required");this.apiBaseUrl=W,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let W=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(W)}/balance`)}async fetchUsageTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/usages`)).items??[]}async fetchPaymentTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchAvailableSubscriptionPlans($){let W=new URL("/api/v1/plans",this.apiBaseUrl);if($?.type)W.searchParams.set("type",$.type);return this.request(`${W.pathname}${W.search}`)}async fetchCurrentUserPlan(){return this.request("/api/v1/users/me/plan")}async fetchOrganization($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}`)}async fetchOrganizationBalance($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}/balance`)}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");let Z=await this.resolveOrganizationMemberId(W,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(W)}/members/${encodeURIComponent(Z)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let W=$?.trim();if(W)return W;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let J=await this.fetchMe();if(!J.id?.trim())throw Error("Unable to resolve current user id");return J.id}async resolveOrganizationMemberId($,W){let Z=W?.trim();if(Z)return Z;let J=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(J)return J;let X=(await this.fetchUserOrganizations()).find((Y)=>Y.organizationId===$)?.memberId;if(!X?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return X}async request($,W){let Z=(await this.getAuthTokenFn())?.trim();if(!Z)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},J=new AbortController,j=setTimeout(()=>J.abort(),this.requestTimeoutMs);try{let X=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:W?.method??"GET",headers:{Authorization:`Bearer ${Z}`,"Content-Type":"application/json",...Q??{}},body:W?.body!==void 0?JSON.stringify(W.body):void 0,signal:J.signal});if(X.status===204||W?.expectNoContent){if(!X.ok)throw Error(`Cline account request failed with status ${X.status}`);return}let Y=await X.text(),V;if(Y.trim())try{V=JSON.parse(Y)}catch{if(!X.ok)throw Error(_F(X.status,Y,void 0));throw Error("Cline account response was not valid JSON")}if(!X.ok)throw Error(_F(X.status,Y,V));if(typeof V==="object"&&V!==null){let B=V;if(typeof B.success==="boolean"){if(!B.success)throw Error(B.error||"Cline account request failed");return B.data}}if(V===void 0||V===null)throw Error("Cline account response payload was empty");return V}finally{clearTimeout(j)}}}function sZ($){return $.action==="clineAccount"}async function tZ($,W){switch($.operation){case"fetchMe":return W.fetchMe();case"fetchBalance":return W.fetchBalance($.userId);case"fetchUsageTransactions":return W.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return W.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return W.fetchUserOrganizations();case"fetchOrganizationBalance":return W.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return W.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await W.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return W.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class S5{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:W})}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:W,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var LF={};w(LF,{createOAuthClientCallbacks:()=>D6});function D6($){return{onAuth:({url:W,instructions:Z})=>{if($.onOutput?.(Z??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(W)).catch((Q)=>{$.onOpenUrlError?.({url:W,error:Q})})}catch(Q){$.onOpenUrlError?.({url:W,error:Q})}$.onOutput?.(W)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}var dU={};w(dU,{ClineCore:()=>U9});function TF($){if($===!0)return{};if(!$)return;return $}function OF($){if($==="user")return"global";return $}class eJ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let W=this.getService().ingestEvent($);return{event:W.event,duplicate:W.duplicate,matchedSpecIds:W.matchedSpecs.map((Z)=>Z.specId),queuedRuns:W.queuedRuns,suppressions:W.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function zF($){let{host:W}=$;return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||F0.CLI,interactive:!1,config:{providerId:K6(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:QC(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content),delivery:Q.delivery});if(!J)throw Error("ClineCore automation runtime returned no result");return{result:ZC(J)}},async abortSession(Z){return await W.abort(Z,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}function eZ($){let W=WC($.automationService,$.automation),Z=$.context?.client??($.clientName?{name:$.clientName}:void 0),Q=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),J=$.context?.logger??$.logger,j=$.context?.telemetry??$.telemetry;if(!W&&!Z&&!Q&&!J&&!j)return $.context;return{...$.context??{},...Z?{client:Z}:{},...Q?{user:Q}:{},...J?{logger:J}:{},...j?{telemetry:j}:{},...W?{automation:W}:{}}}function WC($,W){if(!$)return;return{ingestEvent:(Z)=>{W.ingestEvent(Z)}}}function ZC($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function QC($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var MA={};w(MA,{createCoreSettingsService:()=>o2,CoreSettingsService:()=>l$});import{existsSync as t5,readFileSync as uP}from"node:fs";import{basename as Uj,dirname as _A,extname as dP,isAbsolute as TA,join as lP,relative as OA,resolve as fA}from"node:path";var kF={};w(kF,{resolveWorkflowsConfigSearchPaths:()=>v5,resolveSkillsConfigSearchPaths:()=>g5,resolveRulesConfigSearchPaths:()=>m5,parseWorkflowConfigFromMarkdown:()=>x5,parseSkillConfigFromMarkdown:()=>k5,parseRuleConfigFromMarkdown:()=>I5,createWorkflowsConfigDefinition:()=>d5,createUserInstructionConfigService:()=>c$,createSkillsConfigDefinition:()=>c5,createRulesConfigDefinition:()=>u5,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>h5,UnifiedConfigFileWatcher:()=>d2,SKILLS_CONFIG_DIRECTORY_NAME:()=>y5,RULES_CONFIG_DIRECTORY_NAME:()=>jQ});import{createHash as JC}from"node:crypto";import{watch as jC}from"node:fs";import{readdir as XC,readFile as YC}from"node:fs/promises";import{join as VC}from"node:path";function BC($){return JC("sha1").update($).digest("hex")}function RF($){return Boolean($&&typeof $==="object"&&"code"in $)}function qF($){return RF($)&&$.code==="ENOENT"}function MF($){return RF($)&&($.code==="EACCES"||$.code==="EPERM")}class d2{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,W){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=W?.debounceMs??75,this.emitParseErrors=W?.emitParseErrors??!1;for(let Z of $){if(this.definitionsByType.has(Z.type))throw Error(`Duplicate unified config definition type '${Z.type}'.`);this.definitionsByType.set(Z.type,Z),this.recordsByType.set(Z.type,new Map),this.discoveredDirectoriesByType.set(Z.type,new Set);for(let Q of Z.directories){let J=this.baseTypesByDirectory.get(Q);if(J)J.add(Z.type);else this.baseTypesByDirectory.set(Q,new Set([Z.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let W=this.definitionsByType.get($);if(!W)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(W)})}getSnapshot($){let W=this.recordsByType.get($);return new Map([...W?.entries()??[]].map(([Z,Q])=>[Z,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[W,Z]of this.recordsByType.entries())$.set(W,new Map([...Z.entries()].map(([Q,J])=>[Q,{...J}])));return $}emit($){for(let W of this.listeners)W($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[W,Z]of this.watchersByDirectory.entries()){if($.has(W))continue;Z.close(),this.watchersByDirectory.delete(W)}this.watchedTypesByDirectory=$;for(let W of $.keys()){if(this.watchersByDirectory.has(W))continue;try{let Z=jC(W,()=>{let Q=this.watchedTypesByDirectory.get(W);if(!Q)return;for(let J of Q)this.pendingTypes.add(J);this.scheduleFlush()});this.watchersByDirectory.set(W,Z),Z.on("error",(Q)=>{let J=this.watchedTypesByDirectory.get(W);if(!J)return;for(let j of J)this.emit({kind:"error",type:j,error:Q,filePath:W})})}catch(Z){if(!qF(Z)&&!MF(Z)){let Q=$.get(W);if(!Q)continue;for(let J of Q)this.emit({kind:"error",type:J,error:Z,filePath:W})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let W of $){let Z=this.definitionsByType.get(W);if(!Z)continue;await this.refreshTypeInternal(Z)}})},this.debounceMs)}async refreshTypeInternal($){let{records:W,discoveredDirectories:Z}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[J,j]of Q.entries()){if(W.has(J))continue;this.emit({kind:"remove",type:$.type,id:J,filePath:j.filePath})}for(let[J,j]of W.entries()){let X=Q.get(J);if(X&&X.filePath===j.filePath&&X.fingerprint===j.fingerprint)continue;this.emit({kind:"upsert",record:{type:j.type,id:J,item:j.item,filePath:j.filePath}})}if(this.recordsByType.set($.type,W),this.discoveredDirectoriesByType.set($.type,Z),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let W=new Map,Z=new Set;for(let Q of $.directories){Z.add(Q);let J=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let j of J){let{fileName:X,filePath:Y}=j;if(Z.add(j.directoryPath),$.includeFile&&!$.includeFile(X,Y))continue;try{let V=await YC(Y,"utf8"),B={type:$.type,directoryPath:j.directoryPath,fileName:X,filePath:Y,content:V},H=$.parseFile(B),G=$.resolveId(H,B).trim();if(!G)continue;W.set(G,{type:$.type,id:G,item:H,filePath:Y,fingerprint:BC(V)})}catch(V){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:V,filePath:Y})}}}return{records:W,discoveredDirectories:Z}}buildDesiredTypesByDirectory(){let $=new Map;for(let[W,Z]of this.baseTypesByDirectory.entries())$.set(W,new Set(Z));for(let[W,Z]of this.discoveredDirectoriesByType.entries())for(let Q of Z){let J=$.get(Q);if(J)J.add(W);else $.set(Q,new Set([W]))}return $}async readDirectoryFileCandidates($){try{return(await XC($,{withFileTypes:!0})).filter((Z)=>Z.isFile()).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:VC($,Z.name)})).sort((Z,Q)=>Z.fileName.localeCompare(Q.fileName))}catch(W){if(qF(W)||MF(W))return[];throw W}}}import{readdir as Wj,readFile as HC,stat as $j}from"node:fs/promises";import{basename as j$,dirname as GC,extname as WQ,join as v0,resolve as b5}from"node:path";import{AGENTS_RULES_FILE_NAME as EF,RULES_CONFIG_DIRECTORY_NAME as jQ,resolveGlobalAgentsRulesPath as KC,resolveRulesConfigSearchPaths as FC,resolveSkillsConfigSearchPaths as AC,resolveWorkflowsConfigSearchPaths as UC,SKILLS_CONFIG_DIRECTORY_NAME as y5,WORKFLOWS_CONFIG_DIRECTORY_NAME as h5}from"@cline/shared/storage";import DC from"yaml";var $Q="SKILL.md",_C="managed.json",fC=new Set([".md",".markdown",".txt"]);function Zj($){return $.trim().toLowerCase()}function _6($){let W=$;return W?.code==="ENOENT"||W?.code==="EACCES"||W?.code==="EPERM"||W?.code==="ELOOP"}function ZQ($){return fC.has(WQ($).toLowerCase())}function NF($){let W=[],Z=new Set;for(let Q of $){let J=b5(Q);if(Z.has(J))continue;Z.add(J),W.push(Q)}return W}function LC($){let W=[...$?.directories??g5($?.workspacePath)];if($?.pluginSkillDirectories)W.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)W.push(...cK({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return NF(W)}async function Qj($){try{let W=await Wj($,{withFileTypes:!0}),Z=[];for(let Q of W){if(!Q.isDirectory())continue;let J=v0($,Q.name),j=v0(J,_C);try{let X=await HC(j,"utf8"),Y=JSON.parse(X);if(Y&&typeof Y==="object")Z.push(J)}catch(X){if(_6(X))continue;if(X?.name==="SyntaxError")continue;throw X}}return Z.sort((Q,J)=>Q.localeCompare(J))}catch(W){if(_6(W))return[];throw W}}function Jj($){let W=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Z=$.match(W);if(!Z)return{data:{},body:$,hadFrontmatter:!1};let[,Q,J]=Z;try{let j=DC.parse(Q);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:J,hadFrontmatter:!0}}catch(j){let X=j instanceof Error?j.message:String(j);return{data:{},body:$,hadFrontmatter:!0,parseError:X}}}function QQ($,W,Z){if($===void 0||$===null){if(Z)throw Error(`Missing required frontmatter field '${W}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${W}' must be a string.`);let Q=$.trim();if(!Q&&Z)throw Error(`Frontmatter field '${W}' cannot be empty.`);return Q||void 0}function f6($,W){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${W}' must be a boolean.`);return $}function TC($,W){if(j$($.filePath).toLowerCase()!==EF.toLowerCase())return j$($.filePath,WQ($.filePath));if(W&&b5($.filePath)===b5(W,EF))return"Workspace AGENTS.md";if(b5($.filePath)===b5(KC()))return"Global AGENTS.md";return j$($.filePath,WQ($.filePath))}function k5($,W){let{data:Z,body:Q,parseError:J}=Jj($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in skill file.");let Y=QQ(Z.name,"name",!1)??W.trim();if(!Y)throw Error("Missing skill name.");return{name:Y,description:QQ(Z.description,"description",!1),disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function I5($,W){let{data:Z,body:Q,parseError:J}=Jj($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in rule file.");let X=QQ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing rule name.");return{name:X,disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function x5($,W){let{data:Z,body:Q,parseError:J}=Jj($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in workflow file.");let X=QQ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing workflow name.");return{name:X,disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function g5($){return AC($)}function m5($){return FC($)}function v5($){return UC($)}async function wF($){if(j$($)===".cline"){let W=await Qj($);return(await Promise.all(W.map((Q)=>wF(v0(Q,y5))))).flat()}try{let W=await Wj($,{withFileTypes:!0}),Z=[];for(let Q of W){if(Q.isFile()&&Q.name===$Q){Z.push({directoryPath:$,fileName:Q.name,filePath:v0($,Q.name)});continue}let J=v0($,Q.name);if(Q.isDirectory()||Q.isSymbolicLink()&&await $j(J).then((X)=>X.isDirectory()).catch((X)=>{if(_6(X))return!1;throw X}))Z.push({directoryPath:J,fileName:$Q,filePath:v0(J,$Q)})}return Z}catch(W){if(_6(W))return[];throw W}}async function JQ($){if(j$($)===".cline"){let W=await Qj($);return(await Promise.all(W.map((Q)=>JQ(v0(Q,"rules.md"))))).flat()}try{if((await $j($)).isFile())return[{directoryPath:GC($),fileName:j$($),filePath:$}]}catch(W){if(!_6(W))throw W}try{let Z=(await Wj($,{withFileTypes:!0})).filter((J)=>J.isFile()&&ZQ(J.name)).map((J)=>({directoryPath:$,fileName:J.name,filePath:v0($,J.name)})),Q=v0($,"AGENTS.md");try{if((await $j(Q)).isFile()){if(!Z.some((X)=>X.fileName==="AGENTS.md"))Z.push({directoryPath:$,fileName:"AGENTS.md",filePath:Q})}}catch{}return Z}catch(W){if(_6(W))return[];throw W}}async function OC($){if(j$($)===".cline"){let W=await Qj($);return(await Promise.all(W.map((Q)=>JQ(v0(Q,h5))))).flat()}return JQ($)}function c5($){let W=LC($),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Z?NF([...W,Z]):W,discoverFiles:wF,includeFile:(Q)=>Q===$Q,parseFile:(Q)=>k5(Q.content,j$(Q.directoryPath)),resolveId:(Q)=>Zj(Q.name)}}function u5($){let W=$?.directories??m5($?.workspacePath),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Z?[...W,Z]:W,discoverFiles:JQ,includeFile:(Q,J)=>Q===".clinerules"||ZQ(Q)||ZQ(J),parseFile:(Q)=>I5(Q.content,TC(Q,$?.workspacePath)),resolveId:(Q)=>Zj(Q.name)}}function d5($){let W=$?.directories??v5($?.workspacePath),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Z?[...W,Z]:W,discoverFiles:OC,includeFile:(Q)=>ZQ(Q),parseFile:(Q)=>x5(Q.content,j$(Q.filePath,WQ(Q.filePath))),resolveId:(Q)=>Zj(Q.name)}}function CF($){let W=[c5($?.skills),u5($?.rules),d5($?.workflows)];return new d2(W,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as PF}from"@cline/shared";function zC($,W){if($.description?.trim())return PF($.description,".");if(W==="workflow")return;return PF($.instructions,".")}function qC($){return $.disabled!==!0}function SF($,W){return[...$.getSnapshot(W).entries()].map(([Z,Q])=>({id:Z,record:Q})).filter(({record:Z})=>qC(Z.item)).map(({id:Z,record:Q})=>({id:Z,name:Q.item.name,instructions:Q.item.instructions,description:zC(Q.item,W),kind:W})).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function l5($){let W=new Map;for(let Z of[...SF($,"workflow"),...SF($,"skill")])if(!W.has(Z.name))W.set(Z.name,Z);return[...W.values()].sort((Z,Q)=>Z.name.localeCompare(Q.name))}function bF($,W){if(!$.startsWith("/")||$.length<2)return $;let Z=$.match(/^\/(\S+)/);if(!Z)return $;let Q=Z[1];if(!Q)return $;let J=Q.length+1,j=$.slice(J),X=l5(W).find((Y)=>Y.name===Q);return X?`${X.instructions}${j}`:$}function XQ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function MC($){if(!$||$.length===0)return;let W=$.map(XQ).filter((Z)=>Z.length>0);return W.length>0?new Set(W):void 0}function RC($,W,Z){if(!Z)return!0;let Q=XQ($),J=XQ(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function p5($,W){let Z=MC(W);return[...$.getSnapshot("skill").entries()].map(([J,j])=>{let X=j.item;return{id:J,name:X.name.trim(),description:X.description?.trim(),disabled:X.disabled===!0,skill:X}}).filter((J)=>RC(J.id,J.name,Z))}function EC($,W){return p5($,W).filter((Z)=>!Z.disabled).map((Z)=>Z.name.trim()).filter((Z)=>Z.length>0).sort((Z,Q)=>Z.localeCompare(Q))}function NC($,W,Z){let Q=XQ(W);if(!Q)return{error:"Missing skill name."};let J=p5($,Z),j=J.find((H)=>H.id===Q);if(j){let{skill:H}=j;if(H.disabled===!0)return{error:`Skill "${H.name}" is configured but disabled.`};return{id:j.id,skill:H}}let X=Q.includes(":")?Q.split(":").at(-1)??Q:Q,Y=J.filter(({id:H})=>{if(H===X)return!0;return H.endsWith(`:${X}`)}),V=Y.filter(({skill:H})=>H.disabled!==!0);if(V.length===1){let{id:H,skill:G}=V[0];return{id:H,skill:G}}if(V.length>1)return{error:`Skill "${W}" is ambiguous. Use one of: ${V.map(({id:H})=>H).join(", ")}`};if(Y.length===1){let{skill:H}=Y[0];return{error:`Skill "${H.name}" is configured but disabled.`}}if(Y.length>1)return{error:`Skill "${W}" is ambiguous, and all matches are disabled: ${Y.map(({id:H})=>H).join(", ")}`};let B=EC($,Z);return{error:B.length>0?`Skill "${W}" not found. Available skills: ${B.join(", ")}`:"No skills are currently available."}}function jj($,W=Promise.resolve(),Z){let Q=new Set,J=async(j,X)=>{await W;let Y=NC($,j,Z);if("error"in Y)return Y.error;let{id:V,skill:B}=Y;if(Q.has(V))return`Skill "${B.name}" is already running.`;Q.add(V);try{let H=X?.trim(),G=H?`
475
+ ${Q}`;return Z||Q}function uR($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function dR($,W){return $.filter((Z)=>uR(Z.name,W))}function lR($,W){return u1(dR($,W))}function pR($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return{};return{beforeRun:async(Z)=>{for(let Q of W){let J=await Q.beforeRun?.(Z);if(J?.stop)return J}return},afterRun:async(Z)=>{for(let Q of W)await Q.afterRun?.(Z)},beforeModel:async(Z)=>{let Q=Z.request,J;for(let j of W){let X=await j.beforeModel?.({...Z,request:Q});if(!X)continue;if(X.stop)return X;J={...J,...X,options:SG(J?.options,X.options)},Q={...Q,...X.messages?{messages:X.messages}:{},...X.tools?{tools:X.tools}:{},...X.options?{options:SG(Q.options,X.options)}:{}}}return J},afterModel:async(Z)=>{for(let Q of W){let J=await Q.afterModel?.(Z);if(J?.stop)return J}return},beforeTool:async(Z)=>{let Q=Z.input,J;for(let j of W){let X=await j.beforeTool?.({...Z,input:Q});if(!X)continue;if(X.stop||X.skip)return X;if(J={...J,...X},Object.hasOwn(X,"input"))Q=X.input}return J},afterTool:async(Z)=>{let Q=Z.result,J;for(let j of W){let X=await j.afterTool?.({...Z,result:Q});if(!X)continue;if(X.stop)return X;if(J={...J,...X},X.result)Q=X.result}return J},onEvent:async(Z)=>{for(let Q of W)await Q.onEvent?.(Z)}}}class P${config;agentId;parentAgentId;logger;telemetry;conversation;mistakeTracker;loopTracker;loopDetectionDisabled;messageBuilder;contributionRegistry;extensionsInitialized=!1;listeners=new Set;createAgentRuntimeImpl;activeRunId=null;running=!1;abortRequested=!1;abortReason;activeRuntime=null;activeRunPromise=null;eventAdapter=new HJ;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,W={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=W.logger??$.logger,this.telemetry=W.telemetry??$.telemetry,this.createAgentRuntimeImpl=W.createAgentRuntimeImpl??xR,this.conversation=new jJ($.initialMessages),this.messageBuilder=new ZJ(RG()),this.contributionRegistry=gR({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let Z=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new BJ({maxConsecutiveMistakes:Z,onLimitReached:$.onConsecutiveMistakeLimitReached,onLimitTelemetry:(j)=>{jW(this.telemetry,{ulid:this.config.sessionId??this.conversation.getConversationId(),model:this.config.modelId,provider:this.config.providerId,reason:j.reason,consecutiveMistakes:j.consecutiveMistakes,maxConsecutiveMistakes:j.maxConsecutiveMistakes,agentId:this.agentId,conversationId:this.conversation.getConversationId(),parentAgentId:this.parentAgentId,isSubagent:Boolean(this.parentAgentId)})},emit:(j)=>this.emitLegacyEvent(j),log:(j,X,Y)=>rR(this.logger,j,X,Y),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,X)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let J=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new VJ(J)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let W=new Set(this.config.tools.map((Q)=>Q.name)),Z=[...this.config.tools];for(let Q of $)if(!W.has(Q.name))Z.push(Q),W.add(Q.name);this.config={...this.config,tools:Z}}updateConnection($){let W=w2($),Z={...this.config};if(W.providerId!==void 0)Z.providerId=W.providerId;if(W.modelId!==void 0)Z.modelId=W.modelId;if(W.apiKey!==void 0)Z.apiKey=W.apiKey;if(W.baseUrl!==void 0)Z.baseUrl=W.baseUrl;if(W.headers!==void 0)Z.headers=W.headers;if(W.providerConfig!==void 0)Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"reasoningEffort"))Z.reasoningEffort=W.reasoningEffort??void 0;if(Object.hasOwn(W,"thinkingBudgetTokens"))Z.thinkingBudgetTokens=W.thinkingBudgetTokens??void 0;if(Object.hasOwn(W,"thinking")){if(Z.thinking=W.thinking??void 0,W.thinking===!1||W.thinking===null)Z.reasoningEffort=void 0,Z.thinkingBudgetTokens=void 0}this.config=Z}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.messageBuilder.resetConversationState(),this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let W=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=W,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(W)}async shutdown($,W){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,W,Z){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!1})}continue($,W,Z){return this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let W of this.contributionRegistry.getRegisteredRules()){let Z=await vR(W);if(Z)$.push(Z)}return cR(this.config.systemPrompt,$)}executeRun($){let W;return W=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===W)this.activeRunPromise=null}),this.activeRunPromise=W,W}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let W=new Date,Z=$.userMessage;if(Z!==void 0){let _=await nR(Z,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:_})}let Q=await this.composeSystemPrompt(),J=DG(this.config,this.logger,this.telemetry),j=new Map;for(let _ of this.contributionRegistry.getRegisteredTools())j.set(_.name,_);let X=lR([...j.values()],this.config.toolPolicies),Y=new Map;for(let _ of X)Y.set(_.name,_);for(let _ of this.config.tools)Y.set(_.name,_);let V=this.conversation.getConversationId(),B=bG(this.config),H=Array.from(Y.values()),G=XZ(this.conversation.getMessages()),K=NG({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:V,parentAgentId:this.parentAgentId,model:J,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:B?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[nW]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(B,H),initialMessages:G,systemPrompt:Q}),F=this.createAgentRuntimeImpl(K);if(this.activeRuntime=F,this.abortRequested)F.abort(this.abortReason);let A=F.subscribe((_)=>{this.handleRuntimeEvent(_)}),D,U;try{if($.isContinue)D=await F.continue(void 0);else D=await F.run("")}catch(_){U=_ instanceof Error?_:Error(String(_))}finally{A();try{await this.activeTrackerWork}catch(_){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:_})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(D&&D.messages.length>0){let _=i8(D.messages);this.conversation.replaceMessages(_)}let f=new Date;try{return this.buildLegacyResult({runResult:D,thrownError:U,startedAt:W,endedAt:f})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize({tolerateSetupErrors:this.config.hookErrorMode!=="throw"})}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=pR([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((W)=>W.hooks)]);return{...$,beforeModel:async(W)=>{let Z=await $.beforeModel?.(W);if(Z?.stop)return Z;let Q=Z?.messages??W.request.messages,J=await this.prepareMessagesForModelRequest(Q);return{...Z,messages:J}}}}createRuntimePrepareTurn($,W){let Z=this.config.prepareTurn;if(!Z)return;return async(Q)=>{let J=i8(Q.messages),j=await this.prepareProviderMessagesForApi(J),X=await Z({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:J,apiMessages:j,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:W,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!X)return;return{...X.messages?{messages:XZ(X.messages)}:{},...X.systemPrompt!==void 0?{systemPrompt:X.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let W=await this.prepareProviderMessagesForApi(YZ($));return XZ(W)}async prepareProviderMessagesForApi($){let W=$,Z=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of Z)W=await Q.build(W);return this.messageBuilder.buildForApi(W)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let W=this.toolStartedAt.get($.toolCall.toolCallId),Z=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let J=$.message.content.find((V)=>V.type==="tool-result"),j=J?.type==="tool-result"&&J.isError===!0,X=j?mR(J?.type==="tool-result"?J.output:void 0):void 0,Y={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:J?.type==="tool-result"?J.output:void 0,error:X,durationMs:W===void 0?0:Z.getTime()-W.getTime(),startedAt:W??Z,endedAt:Z};if(this.currentRunToolCalls.push(Y),j){if(this.currentTurnFailedTools+=1,X)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${X}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let W=this.currentTurnFailedTools,Z=this.currentTurnSuccessfulTools;if(W>0&&Z===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${W} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(Z>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let W of this.eventAdapter.translate($))this.emitLegacyEvent(W)}syncConversationFromRuntimeMessage($,W){if($.length>0){this.conversation.replaceMessages(i8($));return}if(W.length===0)return;let Z=new Set(this.conversation.getMessages().map((J)=>J.id).filter((J)=>typeof J==="string")),Q=i8(W).filter((J)=>!J.id||!Z.has(J.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let W of this.listeners)try{W($)}catch(Z){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Z})}}inspectLoopForToolCall($,W,Z){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:W});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:Z,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let W=await this.mistakeTracker.record($);if(W.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]}),this.activeRuntime?.abort(W.reason??W.message)})}buildLegacyResult($){let{runResult:W,thrownError:Z,startedAt:Q,endedAt:J}=$,j=J.getTime()-Q.getTime(),X=Z?"error":iR(W),Y=(W?.status==="failed"?W.error?.message:void 0)||W?.outputText||"",V=W?{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens>0?W.usage.cacheReadTokens:void 0,cacheWriteTokens:W.usage.cacheWriteTokens>0?W.usage.cacheWriteTokens:void 0,totalCost:W.usage.totalCost}:this.currentRunUsage,B=W?i8(W.messages):this.conversation.getMessages(),H=bG(this.config);if(Z)throw Z;return{text:Y,usage:V,messages:B,toolCalls:this.currentRunToolCalls,iterations:W?.iterations??0,finishReason:X,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Q,endedAt:J,durationMs:j}}}function rR($,W,Z,Q){if(!$)return;if(W==="debug"){$.debug(Z,Q);return}if(W==="error"&&$.error){$.error(Z,Q);return}let J=W==="warn"?"warn":W==="error"?"error":"info";$.log(Z,{...Q,severity:J})}function iR($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function nR($,W,Z,Q){let{buildInitialUserContent:J}=await Promise.resolve().then(() => PG);return J($,W,Z,Q)}function bG($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let W=e3($);if(W?.[$.modelId])return W[$.modelId];return}import{buildClineSystemPrompt as yG}from"@cline/shared";function hG($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return yG({ide:W.clineIdeName?.trim()||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,rules:`# Team Teammate Role
476
+ ${Z}`,platform:W.clinePlatform,metadata:W.workspaceMetadata})}function kG($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return yG({ide:W.clineIdeName||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,overridePrompt:Z,metadata:W.workspaceMetadata,platform:W.clinePlatform})}function S$($){let W={...$};return{getRuntimeConfig:()=>W,getConnectionConfig:()=>({providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,temperature:W.temperature}),updateConnectionDefaults:(Z)=>{W={...W,...Z}}}}function C2($){let W=$.configProvider.getRuntimeConfig(),Z=$.kind==="teammate"?hG($.prompt,W):kG($.prompt,W);return{...$.configProvider.getConnectionConfig(),systemPrompt:Z,tools:$.tools,maxIterations:$.maxIterations??W.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:W.hooks,extensions:W.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:W.logger,role:$.role}}function b$($){let W=C2($),Z=new P$(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);return Z}var sR=GJ.object({systemPrompt:GJ.string().describe("System prompt defining the sub-agent's behavior"),task:GJ.string().describe("Task for the sub-agent to complete")});function y$($){return aR({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:oR(sR),execute:async(W,Z)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(W,Z):$.subAgentTools??[],J=b$({kind:"subagent",prompt:W.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:Z.agentId,abortSignal:Z.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=J.getAgentId(),X=J.getConversationId(),Y=Z.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:X,parentAgentId:Y,input:W})}catch{}try{let V=await J.run(W.task),B={text:V.text,iterations:V.iterations,finishReason:V.finishReason,usage:{inputTokens:V.usage.inputTokens,outputTokens:V.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,result:B,agentResult:V})}catch{}return B}catch(V){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,error:V instanceof Error?V:Error(String(V))})}catch{}throw V}},timeoutMs:300000,retryable:!1})}import{createTool as _0,TEAM_AWAIT_TIMEOUT_MS as tR,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as eR,TEAM_RUN_TEXT_PREVIEW_LIMIT as $E,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as WE,TeamAttachOutcomeFragmentInputSchema as IG,TeamAwaitRunsInputSchema as xG,TeamBroadcastInputSchema as gG,TeamBroadcastToolResultSchema as ZE,TeamCancelRunInputSchema as mG,TeamCancelRunToolResultSchema as QE,TeamCleanupInputSchema as vG,TeamCleanupToolResultSchema as JE,TeamCreateOutcomeInputSchema as cG,TeamCreateOutcomeToolResultSchema as jE,TeamFinalizeOutcomeInputSchema as uG,TeamFinalizeOutcomeToolResultSchema as XE,TeamListOutcomesInputSchema as dG,TeamListRunsInputSchema as lG,TeamMailboxMessageToolResultSchema as YE,TeamMissionLogInputSchema as pG,TeamMissionLogToolResultSchema as VE,TeamOutcomeFragmentToolResultSchema as rG,TeamOutcomeToolResultSchema as BE,TeamReadMailboxInputSchema as iG,TeamReviewOutcomeFragmentInputSchema as nG,TeamRunTaskInputSchema as aG,TeamRunTaskToolResultSchema as KJ,TeamRunToolSummarySchema as FJ,TeamSendMessageInputSchema as oG,TeamSendMessageToolResultSchema as HE,TeamShutdownTeammateInputSchema as sG,TeamSimpleAgentStatusToolResultSchema as tG,TeamSpawnTeammateInputSchema as eG,TeamStatusInputSchema as $K,TeamStatusToolResultSchema as GE,TeamTaskInputSchema as WK,TeamTaskToolResultSchema as J5,validateWithZod as g,zodToJsonSchema as f0}from"@cline/shared";function ZK($,W){let Z=$.replace(/\s+/g," ").trim();if(Z.length<=W)return Z;return`${Z.slice(0,Math.max(0,W-3)).trimEnd()}...`}function P2($,W){if($===void 0)throw Error(`Missing required field: ${W}`);return $}function KE($){let W=$.result;if(!W)return;return{textPreview:ZK(W.text,$E),iterations:W.iterations,finishReason:W.finishReason,durationMs:W.durationMs,usage:{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens,cacheWriteTokens:W.usage.cacheWriteTokens,totalCost:W.usage.totalCost}}}function GZ($){return $?.toISOString()}function AJ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:ZK($.message,eR),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:GZ($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:GZ($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:GZ($.heartbeatAt),lastProgressAt:GZ($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:KE($)}}function FE($){if($.status==="failed")throw Error(`Run "${$.id}" failed${$.error?`: ${$.error}`:""}`);if($.status==="cancelled")throw Error(`Run "${$.id}" was cancelled${$.error?`: ${$.error}`:""}`);if($.status==="interrupted")throw Error(`Run "${$.id}" was interrupted${$.error?`: ${$.error}`:""}`)}var a8=["team_spawn_teammate","team_shutdown_teammate","team_status","team_task","team_run_task","team_cancel_run","team_list_runs","team_await_runs","team_send_message","team_broadcast","team_read_mailbox","team_mission_log","team_cleanup","team_create_outcome","team_attach_outcome_fragment","team_review_outcome_fragment","team_finalize_outcome","team_list_outcomes"];function QK($){let W=[];if($.createBaseTools)W.push(...$.createBaseTools());W.push(...S2({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:C2({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:W,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function o8($){let W=$.leadAgentId??"lead",Z=$.restoredFromPersistence===!0,Q=S2({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),J=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;QK({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),J.push(j.agentId)}return{tools:Q,restoredFromPersistence:Z,restoredTeammates:J}}function S2($){let W=$.allowSpawn??!0,Z=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,J=[];if(Z)J.push(_0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:f0(eG),execute:async(X)=>{let Y=g(eG,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!W)throw Error("Spawning teammates is disabled in this context.");let V={agentId:Y.agentId,rolePrompt:Y.rolePrompt};if(QK({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:V}),!Q)$.onLeadToolsUnlocked?.(S2({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return g(tG,{agentId:Y.agentId,status:"spawned"})}}));if(!Q)return J;J.push(_0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:f0(sG),execute:async(X)=>{let Y=g(sG,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(Y.agentId,Y.reason),g(tG,{agentId:Y.agentId,status:"stopped"})}})),J.push(_0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:f0($K),execute:async(X)=>{return g($K,X),g(GE,$.runtime.getSnapshot())}})),J.push(_0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:f0(WK),execute:async(X)=>{let Y=g(WK,X);switch(Y.action){case"create":{let V=new Set(WE.create??[]),B=Object.entries(X).filter(([G,K])=>V.has(G)&&K!=null).map(([G])=>G),H=$.runtime.createTask({title:P2(Y.title,"title"),description:P2(Y.description,"description"),dependsOn:Y.dependsOn,assignee:Y.assignee,createdBy:$.requesterId});return g(J5,{action:"create",taskId:H.id,status:H.status,...B.length>0?{ignoredFields:B,note:`Ignored fields for action=create: ${B.join(", ")}`}:{}})}case"list":return g(J5,{action:"list",tasks:$.runtime.listTaskItems({status:Y.status,assignee:Y.assignee})});case"claim":{let V=$.runtime.claimTask(P2(Y.taskId,"taskId"),$.requesterId);return g(J5,{action:"claim",taskId:V.id,status:V.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let V=$.runtime.completeTask(P2(Y.taskId,"taskId"),$.requesterId,P2(Y.summary,"summary"));return g(J5,{action:"complete",taskId:V.id,status:V.status})}case"block":{let V=$.runtime.blockTask(P2(Y.taskId,"taskId"),$.requesterId,P2(Y.reason,"reason"));return g(J5,{action:"block",taskId:V.id,status:V.status})}}}}));let j=new Map;return J.push(_0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:f0(aG),execute:async(X)=>{let Y=g(aG,X);if(Y.runMode==="async"){let H=$.runtime.startTeammateRun(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0});return g(KJ,{agentId:Y.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${Y.agentId} and queued as ${H.id}.`,runId:H.id})}let V=j.get(Y.agentId);if(V){let H=await V;return g(KJ,{...H,status:"joined",deduped:!0,message:`Task for ${Y.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let B=$.runtime.routeToTeammate(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0}).then((H)=>g(KJ,{agentId:Y.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${Y.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(Y.agentId)});return j.set(Y.agentId,B),await B}})),J.push(_0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:f0(mG),execute:async(X)=>{let Y=g(mG,X),V=$.runtime.cancelRun(Y.runId,Y.reason);return g(QE,{runId:V.id,status:V.status})}})),J.push(_0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:f0(lG),execute:async(X)=>g(FJ.array(),$.runtime.listRuns(g(lG,X)).map(AJ))})),J.push(_0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:f0(xG),timeoutMs:tR,execute:async(X)=>{let Y=g(xG,X);if(Y.runId){let H=await $.runtime.awaitRun(Y.runId);return FE(H),g(FJ,AJ(H))}let V=await $.runtime.awaitAllRuns(),B=V.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(B.length>0){let H=B.map((G)=>`${G.id}:${G.status}${G.error?`(${G.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return g(FJ.array(),V.map(AJ))}})),J.push(_0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:f0(oG),execute:async(X)=>{let Y=g(oG,X),V=$.runtime.sendMessage($.requesterId,Y.toAgentId,Y.subject,Y.body,Y.taskId??void 0);return g(HE,{id:V.id,toAgentId:V.toAgentId})}})),J.push(_0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:f0(gG),execute:async(X)=>{let Y=g(gG,X),V=$.runtime.broadcast($.requesterId,Y.subject,Y.body,{taskId:Y.taskId??void 0});return g(ZE,{delivered:V.length})}})),J.push(_0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:f0(iG),execute:async(X)=>{let Y=g(iG,X);return g(YE.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:Y.unreadOnly,markRead:!0}))}})),J.push(_0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:f0(pG),execute:async(X)=>{let Y=g(pG,X),V=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:Y.taskId||void 0,kind:Y.kind,summary:Y.summary,evidence:Y.evidence?.length?Y.evidence:void 0,nextAction:Y.nextAction||void 0});return g(VE,{id:V.id})}})),J.push(_0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:f0(vG),execute:async(X)=>{if(g(vG,X),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),g(JE,{status:"cleaned"})}})),J.push(_0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:f0(cG),execute:async(X)=>{let Y=g(cG,X),V=$.runtime.createOutcome({title:Y.title,requiredSections:Y.requiredSections,createdBy:$.requesterId});return g(jE,{outcomeId:V.id,status:V.status,requiredSections:V.requiredSections})}})),J.push(_0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:f0(IG),execute:async(X)=>{let Y=g(IG,X),V=$.runtime.attachOutcomeFragment({outcomeId:Y.outcomeId,section:Y.section,sourceAgentId:$.requesterId,sourceRunId:Y.sourceRunId||void 0,content:Y.content});return g(rG,{fragmentId:V.id,status:V.status})}})),J.push(_0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:f0(nG),execute:async(X)=>{let Y=g(nG,X),V=$.runtime.reviewOutcomeFragment({fragmentId:Y.fragmentId,reviewedBy:$.requesterId,approved:Y.approved});return g(rG,{fragmentId:V.id,status:V.status})}})),J.push(_0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:f0(uG),execute:async(X)=>{let Y=g(uG,X),V=$.runtime.finalizeOutcome(Y.outcomeId);return g(XE,{outcomeId:V.id,status:V.status})}})),J.push(_0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:f0(dG),execute:async(X)=>{return g(dG,X),g(BE.array(),$.runtime.listOutcomes())}})),J}function KZ($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}function JK($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var AE=[{id:"read_files",description:"Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Long files are windowed; page with start_line/end_line.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:y$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...a8]}],UE={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function DE($){return $==="plan"||$==="yolo"?$:"act"}function XK($){let W=DE($.mode),Z=a0[e1({mode:W})],Q=r8($.providerId??"",$.modelId??"",W,p8);return{mode:W,flags:{...Z,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function jK($,W){if(W.disabledToolIds?.has($))return!1;let{flags:Z}=XK(W);if($==="spawn_agent")return Z.enableSpawnAgent===!0;if($==="teams")return Z.enableAgentTeams===!0;if($==="editor")return Z.enableEditor===!0||Z.enableApplyPatch===!0;let Q=UE[$];return Q?Z[Q]===!0:!1}function _E($,W){if($.id==="editor"){let{flags:Z}=XK(W),Q=Z.enableApplyPatch===!0&&Z.enableEditor!==!0;return{...$,defaultEnabled:jK($.id,W),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:jK($.id,W)}}function b2($={}){return AE.map((W)=>_E(W,$))}function FZ($={}){return b2($).filter((W)=>W.defaultEnabled).map((W)=>W.id)}function AZ($){if(!$.enabled)return new Set;let W=b2($.availabilityContext),Z=new Set(W.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(W.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!Z.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${W.map((J)=>J.id).join(", ")}`);return new Set($.allowlist)}function j5($,W={}){return b2(W).filter((Z)=>$.has(Z.id)).flatMap((Z)=>Z.headlessToolNames)}function UZ($,W={}){return j5($,W)}function y2($={}){let{executorOptions:W={},executors:Z,...Q}=$,J={...l8(W),...Z??{}};return N$({...Q,executors:J})}import{mkdirSync as qE,writeFileSync as ME}from"node:fs";import{dirname as RE}from"node:path";import{normalizeUserInput as EE,stripModeNotices as NE}from"@cline/shared";import{nanoid as wE}from"nanoid";var VK={};w(VK,{sanitizeSessionToken:()=>h2,parseTeamTaskSubSessionId:()=>t8,parseSubSessionId:()=>Y5,makeTeamTaskSubSessionId:()=>X5,makeSubSessionId:()=>s8,deriveSubsessionStatus:()=>V5});import{nanoid as TE}from"nanoid";function h2($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function s8($,W){let Z=h2($),Q=h2(W),J=`${Z}__${Q}`;return J.length>180?J.slice(0,180):J}function X5($,W){let Z=h2($),Q=h2(W);return`${Z}__teamtask__${Q}__${TE(6)}`}function t8($){let Z=$.indexOf("__teamtask__");if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+12),j=J.lastIndexOf("__");if(j<=0)return null;let X=J.slice(0,j),Y=J.slice(j+2);if(!Q||!X||!Y)return null;return{rootSessionId:Q,agentId:X,teamTaskId:Y}}function Y5($){if(t8($))return null;let W="__",Z=$.indexOf(W);if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+W.length);if(!Q||!J)return null;return{rootSessionId:Q,agentId:J}}function V5($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let W=String($.reason??"").toLowerCase();if(W.includes("cancel")||W.includes("abort")||W.includes("interrupt"))return"cancelled";if(W.includes("fail")||W.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as Z0}from"zod";var GK={};w(GK,{isTerminalSessionStatus:()=>HK,isNonTerminalSessionStatus:()=>K0,SessionSource:()=>F0,SESSION_STATUSES:()=>B5,NON_TERMINAL_SESSION_STATUSES:()=>BK});import{SESSION_STATUS_VALUES as OE}from"@cline/shared";var B5=OE,BK=["idle","running","pending"];function HK($){return!BK.includes($)}function K0($){return!HK($)}var F0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var zE=Z0.enum(B5),m0=Z0.object({version:Z0.literal(1),session_id:Z0.string().min(1),source:Z0.string().min(1),pid:Z0.number().int(),started_at:Z0.string().min(1),ended_at:Z0.string().min(1).optional(),exit_code:Z0.number().int().nullable().optional(),status:zE,interactive:Z0.boolean(),provider:Z0.string().min(1),model:Z0.string().min(1),cwd:Z0.string().min(1),workspace_root:Z0.string().min(1),team_name:Z0.string().min(1).optional(),enable_tools:Z0.boolean(),enable_spawn:Z0.boolean(),enable_teams:Z0.boolean(),prompt:Z0.string().optional(),metadata:Z0.record(Z0.string(),Z0.unknown()).optional(),messages_path:Z0.string().min(1).optional(),compaction_path:Z0.string().min(1).optional()});function KK($){if(!$)return!1;return Object.values($).some((W)=>typeof W==="function")}function DJ($,W){let Z=[...$??[],...W??[]];if(Z.length===0)return;let Q=[],J=new Set;for(let j of Z){if(J.has(j.name))continue;J.add(j.name),Q.push(j)}return Q}function FK($){return JSON.stringify($,(W,Z)=>{if(Z instanceof Error)return{name:Z.name,message:Z.message,stack:Z.stack};return Z})}function $$($){return typeof $==="string"&&$.trim()?$.trim():void 0}function UJ($,W){let Z={...$};Z.id=$$(Z.id)??wE();let Q=Z.modelInfo&&typeof Z.modelInfo==="object"?{...Z.modelInfo}:void 0,J={id:$$(Q?.id)??$$(Z.modelId)??$$(W?.id),provider:$$(Q?.provider)??$$(Z.providerId)??$$(W?.provider),family:$$(Q?.family)??$$(W?.family)};if(delete Z.providerId,delete Z.modelId,J.id&&J.provider)Z.modelInfo={id:J.id,provider:J.provider,...J.family?{family:J.family}:{}};else delete Z.modelInfo;return Z}function DZ($){return $.map((W)=>UJ(W))}function _Z($,W,Z=[]){let Q=$.map((V,B)=>{let H=Z[B],K=H?.role===V.role&&JSON.stringify(H.content)===JSON.stringify(V.content)?{...H,...V}:{...V};return UJ(K)}),J=Z.length,j=[];for(let V=J;V<Q.length;V+=1)if(Q[V]?.role==="assistant")j.push(V);if(j.length===0){let V=[...Q].reverse().findIndex((B)=>B.role==="assistant");if(V===-1)return Q;j.push(Q.length-1-V)}let X=j[j.length-1],Y=j.some((V)=>Q[V]?.metrics);for(let V of j){let B=Q[V],H=B.metrics;if(!H&&V===X&&!Y){let G=W.usage;H={inputTokens:G.inputTokens,outputTokens:G.outputTokens,cacheReadTokens:G.cacheReadTokens??0,cacheWriteTokens:G.cacheWriteTokens??0,cost:G.totalCost}}Q[V]={...UJ(B,{id:W.model.id,provider:W.model.provider,family:W.model.info?.family}),...H?{metrics:H}:{},ts:B.ts??W.endedAt.getTime()}}return Q}function H5($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??void 0,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??void 0,parentAgentId:$.parentAgentId??void 0,agentId:$.agentId??void 0,conversationId:$.conversationId??void 0,isSubagent:$.isSubagent,prompt:$.prompt??void 0,metadata:$.metadata??void 0,messagesPath:$.messagesPath??void 0,updatedAt:$.updatedAt}}var CE=120;function k2($){let W=$?.trim();return W?W.slice(0,CE):void 0}function _J($){let W=NE(EE($??"")).trim();if(!W)return;return k2(W.split(`
477
+ `)[0]?.trim())}function h$($){if(!$)return;let W={...$},Z=k2(typeof W.title==="string"?W.title:void 0);if(Z)W.title=Z;else delete W.title;return Object.keys(W).length>0?W:void 0}function G5($){let W=h$($.metadata)??{},Z=$.title!==void 0?k2($.title):_J($.prompt);if(Z)W.title=Z;return Object.keys(W).length>0?W:void 0}function fJ($){let W=t8($);if(W)return{agent:"teammate",sessionId:W.rootSessionId,taskType:"team"};let Z=Y5($);if(Z)return{agent:"subagent",sessionId:Z.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function LJ($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:DZ($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function AK($,W,Z){qE(RE($),{recursive:!0}),ME($,`${JSON.stringify(LJ({updatedAt:W,context:Z,messages:[]}),null,2)}
478
+ `,"utf8")}function UK($,W){return m0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:W?.endedAt??$.endedAt??void 0,exit_code:W?.exitCode??$.exitCode??void 0,status:W?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:W?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function DK($,W,Z){let Q=0;while(!0){let J=await $();if(J===void 0)return{updated:!1};let j=await W(J);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Q+=1,Q>=Z)return j;continue}return j}}z0();var _K={};w(_K,{summarizeUsageFromMessages:()=>$6,sumUsageTotals:()=>K5,getCurrentContextSize:()=>TJ,createInitialAccumulatedUsage:()=>q0,accumulateUsageTotals:()=>L0});function q0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function L0($,W){return{inputTokens:$.inputTokens+Math.max(0,W.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,W.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,W.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,W.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,W.totalCost??0)}}function K5($){let W=q0();for(let Z of $)W=L0(W,Z);return W}function e8($){return typeof $==="number"&&Number.isFinite($)?$:0}function $6($){let W=q0();for(let Z of $){let Q=Z.metrics;if(!Q)continue;W=L0(W,{inputTokens:e8(Q.inputTokens),outputTokens:e8(Q.outputTokens),cacheReadTokens:e8(Q.cacheReadTokens),cacheWriteTokens:e8(Q.cacheWriteTokens),totalCost:e8(Q.cost)})}return W}function TJ($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z?.role!=="assistant")continue;let Q=e8(Z.metrics?.inputTokens);return Q>0?Q:void 0}return}function PE($){if(!$||typeof $!=="object")return;let W=$,Z=W.skill??W.skill_name??W.skillName;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0?Q:void 0}function OJ($){if(!$||typeof $!=="object")return{};let W=$;return{agentId:typeof W.agentId==="string"?W.agentId:void 0,conversationId:typeof W.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W.parentAgentId==="string"?W.parentAgentId:void 0}}function W$($){let W=$.agentId?.trim();if(!W)return;let Z=$.parentAgentId?.trim()||void 0,Q=$.teamRole,J="root";if(Q==="teammate")J="team_teammate";else if(Q==="lead")J="team_lead";else if(Z)J="subagent";return{agentId:W,agentKind:J,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Z,createdByAgentId:$.createdByAgentId?.trim()||Z||void 0,isSubagent:Boolean(Z),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function SE($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function bE($){let W=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Z of W){let Q=Z?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function zJ($,W,Z){let{sessionId:Q,config:J,liveSession:j,emit:X}=$,Y=J.telemetry,V=j?.runtime.teamRuntime,B=Z?.isPrimaryAgentEvent??!0,H=OJ(W),G=W$({agentId:Z?.agentId??H.agentId,conversationId:Z?.conversationId??H.conversationId,parentAgentId:Z?.parentAgentId??H.parentAgentId,createdByAgentId:Z?.createdByAgentId,teamId:Z?.teamId??V?.getTeamId(),teamName:Z?.teamName??V?.getTeamName(),teamRole:Z?.teamRole,teamAgentId:Z?.teamAgentId});if(W.type==="content_start"&&W.contentType==="tool"&&W.toolName==="skills"){let K=PE(W.input);if(K)QW(Y,{ulid:Q,skillName:K,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:J.providerId,modelId:J.modelId,...G})}if(W.type==="content_end"&&W.contentType==="tool"){let K=W.toolName??"unknown",F=!W.error;if(T8(Y,{ulid:Q,tool:K,autoApproved:void 0,success:F,modelId:J.modelId,provider:J.providerId,...G}),!F&&(K==="editor"||K==="apply_patch"))JW(Y,{ulid:Q,modelId:J.modelId,provider:J.providerId,errorType:W.error,...G})}if(W.type==="notice"&&W.reason==="api_error")V4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.message,...G});if(W.type==="error")V4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.error?.message??"unknown error",...G});if(W.type==="usage"&&j?.turnUsageBaseline){let K=SE(W);if(B){j.turnPrimaryUsage=L0(j.turnPrimaryUsage??q0(),K);let A=L0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Q,A),L8(Y,{ulid:Q,provider:J.providerId,model:J.modelId,source:"assistant",mode:J.mode,...G}),WW(Y,{ulid:Q,tokensIn:W.inputTokens,tokensOut:W.outputTokens,cacheWriteTokens:W.cacheWriteTokens,cacheReadTokens:W.cacheReadTokens,totalCost:W.cost,model:J.modelId,...G})}else{let A=bE({isPrimaryAgentEvent:B,overrides:Z,eventMetadata:H}),D=j.turnUsageByAgent??new Map;j.turnUsageByAgent=D,D.set(A,L0(D.get(A)??q0(),K))}let F=L0(j.turnPrimaryUsage??q0(),K5(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,L0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,F))}if(W.type==="iteration_end"&&B)$.persistMessages(Q,j?.agent.getMessages()??[],j?.config.systemPrompt);X({type:"agent_event",payload:{sessionId:Q,event:W,teamAgentId:Z?.teamAgentId,teamRole:Z!==void 0?Z.teamRole??(B?"lead":void 0):void 0}}),X({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:FK(W),ts:Date.now()}})}function Z$($){return $.workspaceRoot??$.cwd}import{resolveProviderRequestHeaders as vw}from"@cline/llms";import{hasRuntimeConfigExtension as cw}from"@cline/shared";X1();import{existsSync as qZ,readFileSync as LN,statSync as TN}from"node:fs";import{basename as ON,dirname as OZ,join as MZ,resolve as zZ}from"node:path";import{discoverPluginModulePaths as zN,resolveConfiguredPluginModulePaths as gK,resolvePluginConfigSearchPaths as qN,SKILLS_CONFIG_DIRECTORY_NAME as MN}from"@cline/shared/storage";import{resolve as tE}from"node:path";import{normalizePluginManifest as eE}from"@cline/shared";import{existsSync as w0,readFileSync as Z6}from"node:fs";import{builtinModules as yE,createRequire as EJ}from"node:module";import{dirname as k$,extname as A5,isAbsolute as hE,resolve as o}from"node:path";import{fileURLToPath as LK}from"node:url";import{PLUGIN_FILE_EXTENSIONS as kE}from"@cline/shared";var TK=k$(LK(import.meta.url)),IE=EJ(import.meta.url),xE=o(TK,"..","..","..","..",".."),qJ=vE(xE),gE=["@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"],NJ=new Set(yE.flatMap(($)=>[$,$.replace(/^node:/,"")])),F5=new Set(kE),mE=["development","node","import","require","default"];function vE($){let W={},Z={"@cline/sdk":o($,"packages/sdk/src/index.ts"),"@cline/agents":o($,"packages/agents/src/index.ts"),"@cline/core":o($,"packages/core/src/index.ts"),"@cline/llms":o($,"packages/llms/src/index.ts"),"@cline/shared":o($,"packages/shared/src/index.ts"),"@cline/shared/storage":o($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":o($,"packages/shared/src/db/index.ts")};for(let[Q,J]of Object.entries(Z))if(w0(J))W[Q]=J;for(let Q of["agents","core","llms","shared"]){let J=o($,"packages",Q),j=o(J,"package.json");if(!w0(j))continue;try{let X=JSON.parse(Z6(j,"utf8"));if(typeof X.name!=="string"||!X.exports)continue;if(typeof X.exports==="string"){let Y=o(J,X.exports);if(w0(Y))W[X.name]=Y;continue}if(typeof X.exports!=="object")continue;for(let[Y,V]of Object.entries(X.exports)){let B=cE(J,V);if(!B)continue;let H=Y==="."?X.name:`${X.name}/${Y.replace(/^\.\//,"")}`;W[H]=B}}catch{}}return W}function cE($,W){let Z=wJ(W);if(!Z)return null;let Q=OK($,Z);for(let J of Q)if(w0(J))return J;return null}function wJ($,W=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(W.has($))return null;W.add($);let Z=$;for(let Q of mE){let J=wJ(Z[Q],W);if(J)return J}return null}function OK($,W){let Z=W.replace(/^\.\//,""),Q=[o($,W)];if(Z.startsWith("dist/")){let J=Z.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[o($,`${J}.ts`),o($,`${J}.tsx`),o($,`${J}.mts`),o($,`${J}.cts`),...Q]}return Q}function uE($){return Object.fromEntries(Object.entries($).sort(([W],[Z])=>Z.length-W.length))}function fZ($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function W6($){if($.startsWith("@")){let[W,Z]=$.split("/",3);return Z?`${W}/${Z}`:$}return $.split("/",1)[0]??$}function dE($){let W=W6($);if($===W)return".";return`.${$.slice(W.length)}`}function zK($){return W6($).startsWith("@cline/")}function MJ($,W){let Z=W6(W),Q=k$($);while(!0){let J=o(Q,"node_modules",Z);if(w0(J)||w0(o(J,"package.json")))return!0;let j=o(Q,"..");if(j===Q)return!1;Q=j}}function fK($){return RJ($)!==null}function RJ($){try{return IE.resolve($)}catch{}return lE($)}function lE($){let W=W6($),Z=qK(W);if(!Z)return null;let Q=o(Z,"package.json");try{let J=JSON.parse(Z6(Q,"utf8")),j=dE($),X=j==="."&&typeof J.exports==="string"?J.exports:J.exports&&typeof J.exports==="object"&&Object.hasOwn(J.exports,j)?J.exports[j]:void 0,Y=wJ(X)??(j==="."&&typeof J.main==="string"?J.main:null);if(!Y)return null;let V=o(Z,Y),B=[V,...OK(Z,Y).filter((H)=>H!==V)];for(let H of B)if(w0(H))return H;return null}catch{return null}}function pE(){let $=[TK],W=process.env.CLINE_WRAPPER_PATH?.trim();if(W)$.push(k$(k$(W)));let Z=process.execPath?.trim();if(Z)$.push(k$(Z));return[...new Set($.map((Q)=>o(Q)))]}function rE($,W){let Z=$;while(!0){let Q=o(Z,"package.json");if(w0(Q))try{if(JSON.parse(Z6(Q,"utf8")).name===W)return Z}catch{}let J=o(Z,"node_modules",W,"package.json");if(w0(J))return k$(J);let j=o(Z,"..");if(j===Z)return null;Z=j}}function qK($){for(let W of pE()){let Z=rE(W,$);if(Z)return Z}return null}function iE($){let Z=k$($);for(let Q=0;Q<4;Q++){let J=o(Z,"package.json");if(w0(J))try{let X=JSON.parse(Z6(J,"utf8"));return X!=null&&typeof X==="object"&&"cline"in X}catch{return!1}let j=o(Z,"..");if(j===Z)return!1;Z=j}return!1}function MK($,W){let Z=W.startsWith("file:")?LK(W):hE(W)?W:o(k$($),W);if(w0(Z)&&F5.has(A5(Z)))return Z;for(let Q of F5){let J=`${Z}${Q}`;if(w0(J))return J}for(let Q of F5){let J=o(Z,`index${Q}`);if(w0(J))return J}return null}function RK($){let W=new Set,Z=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of Z)for(let J of $.matchAll(Q)){let j=J[1];if(j)W.add(j)}return[...W]}function nE($){return A5($)!==".ts"}function EK($,W,Z=new Set){if(Z.has($)||!w0($))return;if(Z.add($),!F5.has(A5($)))return;let Q=Z6($,"utf8"),J=nE($);for(let j of RK(Q)){if(j.startsWith("node:")||NJ.has(j))continue;if(fZ(j)){if(!J)continue;if(Object.hasOwn(qJ,j)||Object.hasOwn(qJ,W6(j))||MJ($,j)||zK(j)&&fK(j)||W&&fK(j))continue;throw Error(`Cannot find module '${W6(j)}'`)}let X=MK($,j);if(X)EK(X,W,Z)}}function NK($,W=new Set,Z=new Set){if(W.has($)||!w0($))return Z;if(W.add($),!F5.has(A5($)))return Z;let Q=Z6($,"utf8");for(let J of RK(Q)){if(Z.add(J),fZ(J))continue;let j=MK($,J);if(j)NK(j,W,Z)}return Z}function aE($,W){let Z=EJ($),Q={},J=NK($),j=new Set(gE);for(let[X,Y]of Object.entries(qJ)){try{Z.resolve(X);continue}catch{}Q[X]=Y}for(let X of J)if(fZ(X)&&(zK(X)||W))j.add(X);for(let X of j){if(Object.hasOwn(Q,X)||MJ($,X))continue;let Y=RJ(X);if(Y)Q[X]=Y}if(!W)return Q;for(let X of J){if(!fZ(X)||Object.hasOwn(Q,X)||MJ($,X)||X.startsWith("node:")||NJ.has(X))continue;let Y=RJ(X);if(Y)Q[X]=Y}return Q}function oE($){let W=A5($);return W===".ts"||W===".tsx"||W===".mts"||W===".cts"}var I2;function sE(){if(I2!==void 0)return I2;let $=qK("jiti");if(!$)return I2=null,null;let W=o($,"dist","babel.cjs");if(!w0(W))return I2=null,null;try{let Q=EJ(W)(W);I2=typeof Q==="function"?Q:null}catch{I2=null}return I2}async function wK($,W={}){let Z=!iE($);EK($,Z);let Q=aE($,Z),J=uE(Q),j=await import("jiti"),X=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!X)throw Error("Unable to load jiti");let Y=Object.entries(J).filter(([,G])=>oE(G)).map(([G])=>G),V=sE(),B=V?(G)=>V({...G,interopDefault:!0}):void 0;return await X($,{alias:J,cache:W.useCache,requireCache:W.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...NJ],transformModules:Y,tryNative:!1,...B?{transform:B}:{}}).import($,{})}function CK($,W){if(!$)return!0;if($.providerIds?.length){if(!W?.providerId||!$.providerIds.includes(W.providerId))return!1}if($.modelIds?.length){if(!W?.modelId||!$.modelIds.includes(W.modelId))return!1}return!0}function PK($){return typeof $==="object"&&$!==null}function CJ($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function $N($,W){if(!PK($.manifest))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);if(!CJ($.manifest.capabilities))throw Error(`Invalid plugin module at ${W}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${W}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!CJ($.manifest.providerIds))throw Error(`Invalid plugin module at ${W}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!CJ($.manifest.modelIds))throw Error(`Invalid plugin module at ${W}: manifest.modelIds must be a string array when provided`)}function WN($,W){if(!PK($))throw Error(`Invalid plugin module at ${W}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${W}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);$N($,W)}async function U5($,W={}){let Z=tE(W.cwd??process.cwd(),$),Q=await wK(Z,{useCache:W.useCache}),J=W.exportName??"plugin",j=Q.default??Q[J];WN(j,Z);let X=j,Y=X.setup,V=Y?(B,H)=>{let G={...W.session,...H.session},K={...H,session:Object.keys(G).length>0?G:void 0,client:W.client??H.client,user:W.user??H.user,workspaceInfo:W.workspaceInfo??H.workspaceInfo,automation:W.automation??H.automation,logger:W.logger??H.logger,telemetry:W.telemetry??H.telemetry};return Y(B,K)}:void 0;return{...X,manifest:eE(X.manifest),setup:V}}async function LZ($,W={}){return(await x2($,W)).plugins}async function x2($,W={}){let Z=[],Q=[],J=new Map,j=0;for(let Y of $)try{let V=await U5(Y,W);if(!CK(V.manifest,W))continue;let B=J.get(V.name);if(B)Q.push({type:"duplicate_plugin_override",pluginName:V.name,pluginPath:Y,overriddenPluginPath:B.pluginPath,message:`Plugin "${V.name}" from ${Y} overrides ${B.pluginPath}`});J.set(V.name,{plugin:V,pluginPath:Y,order:j++})}catch(V){let B=V instanceof Error?V.message:String(V);Z.push({pluginPath:Y,phase:"load",message:B,stack:V instanceof Error?V.stack:void 0})}let X=[...J.values()].sort((Y,V)=>Y.order-V.order);return{plugins:X.map((Y)=>Y.plugin),pluginPaths:X.map((Y)=>Y.pluginPath),failures:Z,warnings:Q}}import{existsSync as yJ}from"node:fs";import{createRequire as xK}from"node:module";import{dirname as TZ,join as J6}from"node:path";import{fileURLToPath as XN}from"node:url";var kK={};w(kK,{resolveSubprocessRuntimeExecutable:()=>PJ,buildSubprocessSandboxCommand:()=>hK,SubprocessSandbox:()=>Q6,CLINE_JS_RUNTIME_PATH_ENV:()=>yK});import{spawn as ZN}from"node:child_process";import{basename as QN}from"node:path";import{augmentNodeCommandForDebug as JN,withResolvedClineBuildEnv as jN}from"@cline/shared";function SK($){if($ instanceof Error)return $;return Error(String($))}var yK="CLINE_JS_RUNTIME_PATH";function bK($){let W=$?.trim();if(!W)return!1;let Z=QN(W).toLowerCase();return Z==="node"||Z==="node.exe"||Z==="bun"||Z==="bun.exe"}function PJ($={}){let W=$.env??process.env,Z=$.runtimeExecutable?.trim()||W[yK]?.trim();if(Z)return Z;let Q=$.execPath?.trim()||process.execPath;if(bK(Q))return Q;for(let J of[W.BUN_EXEC_PATH,W.npm_node_execpath,W.NODE]){let j=J?.trim();if(j&&bK(j))return j}return"node"}function hK($,W={}){let Z=PJ({env:W.env,execPath:W.execPath,runtimeExecutable:W.runtimeExecutable});return JN([Z,...$],{env:W.env,execArgv:W.execArgv,debugRole:W.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class Q6{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let W=this.pending.get($);if(!W)return;if(this.pending.delete($),W.timeout)clearTimeout(W.timeout);return W}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],W=hK($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Z=ZN(W[0]??PJ(this.options),W.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:jN(process.env),windowsHide:!0});this.process=Z;let Q="",J=(j)=>{let X=Q+j;Q=X.length>4000?X.slice(-4000):X};Z.stderr?.setEncoding("utf8"),Z.stderr?.on("data",(j)=>{J(j)}),Z.on("message",(j)=>{this.onMessage(j)}),Z.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${SK(j).message}`))}),Z.on("exit",(j,X)=>{this.process=null;let Y=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(X)})${Y?`: ${Y}`:""}`))})}async call($,W,Z={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let J=`req_${++this.requestCounter}`,j={type:"call",id:J,method:$,args:W};return await new Promise((X,Y)=>{let V={resolve:(B)=>X(B),reject:Y};if((Z.timeoutMs??0)>0)V.timeout=setTimeout(()=>{this.clearPendingRequest(J),this.shutdown().catch(()=>{}),Y(Error(`${this.processLabel} call timed out after ${Z.timeoutMs}ms: ${$}`))},Z.timeoutMs);this.pending.set(J,V),Q.send(j,(B)=>{if(!B)return;let H=this.clearPendingRequest(J);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${SK(B).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((W)=>{let Z=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}W()},300);$.once("exit",()=>{clearTimeout(Z),W()});try{$.kill("SIGTERM")}catch{clearTimeout(Z),W()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let W=this.clearPendingRequest($.id);if(!W)return;if($.ok){W.resolve($.result);return}W.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[W,Z]of this.pending.entries()){if(this.pending.delete(W),Z.timeout)clearTimeout(Z.timeout);Z.reject($)}}}function YN($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],mcpServers:$.contributions?.mcpServers??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function D5($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function VN(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function BN(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Z=xK($).resolve(`${VN()}/package.json`),Q=J6(TZ(Z),"extensions","plugin-sandbox-bootstrap.js");return yJ(Q)?Q:void 0}catch{return}}function HN(){let $=process.execPath?.trim();if(!$)return;let W=J6(TZ(TZ($)),"extensions","plugin-sandbox-bootstrap.js");return yJ(W)?W:void 0}function GN(){let $=TZ(XN(import.meta.url)),W=xK(import.meta.url),Z=[J6($,"plugin-sandbox-bootstrap.js"),J6($,"extensions","plugin-sandbox-bootstrap.js"),J6($,"agents","plugin-sandbox-bootstrap.js"),BN(),HN()];for(let j of Z.filter((X)=>typeof X==="string"))if(yJ(j))return{file:j};let Q=J6($,"plugin-sandbox-bootstrap.ts"),J="jiti";try{J=W.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(J)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
479
+ `)}}var SJ=GN();function bJ($,W,Z){if(typeof $==="number"&&$>0)return $;if(Z){let Q=process.env[Z];if(Q){let J=Number(Q);if(Number.isInteger(J)&&J>0)return J}}return W}async function j6($){let W=new Q6({name:"plugin-sandbox",..."file"in SJ?{bootstrapFile:SJ.file}:{bootstrapScript:SJ.script},onEvent:$.onEvent}),Z=bJ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Q=bJ($.hookTimeoutMs,3000),J=bJ($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},X,Y=()=>{return X??=W.call("initialize",j,{timeoutMs:Z}).finally(()=>{X=void 0}),X},V;try{V=await W.call("initialize",j,{timeoutMs:Z})}catch(G){throw await W.shutdown().catch(()=>{}),G}let B=V.plugins.map(YN);return{extensions:B.map((G)=>{let K={name:G.name,__clinePluginPath:G.pluginPath,manifest:G.manifest,setup:(F)=>{KN(F,W,G,J,Y),FN(F,W,G,J,Y),AN(F,W,G,J,Y),DN(F,W,G,J,Y),UN(F,G)}};return K.hooks=fN(W,G,Q,Y),K}),failures:V.failures,pluginPaths:B.map((G)=>G.pluginPath),shutdown:async()=>{await W.shutdown()},warnings:V.warnings}}function KN($,W,Z,Q,J){for(let j of Z.contributions?.tools??[]){let X={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(Y,V)=>{try{return await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}catch(B){if(!D5(B))throw B;return await J(),await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}}};$.registerTool(X)}}function FN($,W,Z,Q,J){for(let j of Z.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(X)=>{try{return await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}catch(Y){if(!D5(Y))throw Y;return await J(),await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}}})}function AN($,W,Z,Q,J){for(let j of Z.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}catch(X){if(!D5(X))throw X;return await J(),await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}}:j.content??""})}function UN($,W){for(let Z of W.contributions?.providers??[])$.registerProvider({name:Z.name,description:Z.description,metadata:Z.metadata});for(let Z of W.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Z.eventType,source:Z.source,description:Z.description,attributesSchema:Z.attributesSchema,payloadSchema:Z.payloadSchema,examples:Z.examples,metadata:Z.metadata});for(let Z of W.contributions?.mcpServers??[])$.registerMcpServer(Z)}function DN($,W,Z,Q,J){for(let j of Z.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(X){try{let Y=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return IK(Y)?Y:X}catch(Y){if(!D5(Y))throw Y;await J();let V=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return IK(V)?V:X}}})}function IK($){return Array.isArray($)&&$.every((W)=>typeof W==="object"&&W!==null&&("role"in W)&&("content"in W))}function _N($,W,Z,Q,J){return async(j)=>{try{return await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}catch(X){if(!D5(X))throw X;return await J(),await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}}}function fN($,W,Z,Q){let J={};for(let j of W.hooks??[])J[j]=_N($,W.pluginId,j,Z,Q);return Object.keys(J).length>0?J:void 0}var kJ="package.json",RN="package";function _5($){return qN($)}function f5($){return zN($)}function EN($){try{return qZ($)&&TN($).isDirectory()}catch{return!1}}function IJ($){let W=[],Z=new Set;for(let Q of $){let J=zZ(Q);if(Z.has(J))continue;Z.add(J),W.push(J)}return W}function mK($){let W=IJ($);return _W(W)}function vK($){return _5($).flatMap((W)=>f5(W)).filter((W)=>qZ(W))}function NN($,W){let Z=[];for(let Q of $)try{Z.push(...gK([Q],W))}catch{}return Z}function hJ($){return typeof $==="object"&&$!==null}function wN($){try{let W=JSON.parse(LN(MZ($,kJ),"utf8"));if(!hJ(W)||!hJ(W.cline))return[];let Z=W.cline.plugins;if(!Array.isArray(Z))return[];let Q=[];for(let J of Z){if(typeof J==="string"){Q.push(J);continue}if(!hJ(J)||!Array.isArray(J.paths))continue;for(let j of J.paths)if(typeof j==="string")Q.push(j)}return Q}catch{return[]}}function cK($,W){let Z=zZ(W);return wN($).some((Q)=>zZ($,Q)===Z)}function CN($,W){return ON($)===RN&&qZ(MZ(OZ($),kJ))&&cK(OZ($),W)}function PN($){let W=zZ($),Z=[],Q=OZ(W);while(!0){if(CN(Q,W)){Z.push(Q);break}if(qZ(MZ(Q,kJ))){if(cK(Q,W))Z.push(Q);break}let J=OZ(Q);if(J===Q)break;Q=J}return IJ(Z)}function Q$($={}){let W=$.cwd??process.cwd(),Z=vK($.workspacePath),Q=gK($.pluginPaths??[],W);return mK([...Q,...Z])}function SN($={}){let W=$.cwd??process.cwd(),Z=vK($.workspacePath),Q=NN($.pluginPaths??[],W);return mK([...Q,...Z])}function J$($){let W=[];for(let Z of $)for(let Q of PN(Z)){let J=MZ(Q,MN);if(EN(J))W.push(J)}return IJ(W)}function uK($={}){return J$(SN($))}async function X6($={}){let W=Q$($);if(W.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Q=await x2(W,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Q.plugins,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}let Z=await j6({pluginPaths:W,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:Z.extensions??[],shutdown:Z.shutdown,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}import{execFile as bN}from"node:child_process";import{promisify as yN}from"node:util";var hN=yN(bN);function xJ($,W){$?.log(W,{severity:"warn"})}function kN($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))return;let Z=W;if(!Z.latest||!Array.isArray(Z.history))return;let Q=Z.latest,J=Z.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:J}}async function g2($,W){let Z=await hN("git",["-C",$,...W],{windowsHide:!0});return{stdout:Z.stdout.trim(),stderr:Z.stderr.trim()}}async function gJ($,W){if(!$)return;let Z=`refs/cline/checkpoints/${W}/`;try{let{stdout:Q}=await g2($,["for-each-ref","--format=%(refname)",Z]),J=Q.trim().split(`
480
+ `).filter(Boolean);await Promise.allSettled(J.map((j)=>g2($,["update-ref","-d",j])))}catch{}}async function dK($,W,Z){if(!$||Z.length===0)return;await Promise.allSettled(Z.map((Q)=>g2($,["update-ref",`refs/cline/checkpoints/${W}/${Q.runCount}`,Q.ref])))}function IN($,W){let Z=$.findIndex((Q)=>Q.runCount===W.runCount);if(Z<0)return[...$,W];return $.map((Q,J)=>J===Z?W:Q)}function lK($){let W=$.initialRunCount??0,Z,Q=async()=>{if(Z!==void 0)return Z;try{Z=(await g2($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Z=!1}return Z},J=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:W});if(!await Q())return;let j=async(B)=>{try{let G=(await g2($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!G)return;return{ref:G,createdAt:Date.now(),runCount:W,kind:"commit"}}catch(H){xJ($.logger,`${B}: ${H instanceof Error?H.message:String(H)}`);return}},X=`cline checkpoint session=${$.sessionId} run=${W}`,Y="";try{Y=(await g2($.cwd,["stash","create",X])).stdout.trim()}catch(B){return xJ($.logger,`Checkpoint snapshot failed: ${B instanceof Error?B.message:String(B)}`),j("Checkpoint HEAD fallback failed")}if(!Y)return j("Checkpoint HEAD fallback failed");let V=`refs/cline/checkpoints/${$.sessionId}/${W}`;try{await g2($.cwd,["update-ref",V,Y])}catch(B){xJ($.logger,`Checkpoint store failed: ${B instanceof Error?B.message:String(B)}`);return}return{ref:Y,createdAt:Date.now(),runCount:W,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;W+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||W<1)return;let X=await J();if(!X)return;let Y=await $.readSessionMetadata(),V=kN(Y);if(V?.latest.ref===X.ref)return;let B=IN(V?.history??[],X);await $.writeSessionMetadata({...Y??{},checkpoint:{latest:X,history:B}});return}}}import{spawn as pN}from"node:child_process";import{appendFileSync as rN,readFileSync as iN}from"node:fs";import{join as nN}from"node:path";import{augmentNodeCommandForDebug as iK,withResolvedClineBuildEnv as cJ}from"@cline/shared";import{ensureHookLogDir as pK}from"@cline/shared/storage";function Y6($,W){if(!W)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:W}}import{existsSync as xN,readdirSync as gN}from"node:fs";import{basename as mN,extname as vN,join as cN}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as RZ,resolveHooksConfigSearchPaths as uN}from"@cline/shared/storage";function L5($){return uN($)}var V6;((H)=>{H.TaskStart="TaskStart";H.TaskResume="TaskResume";H.TaskCancel="TaskCancel";H.TaskComplete="TaskComplete";H.TaskError="TaskError";H.PreToolUse="PreToolUse";H.PostToolUse="PostToolUse";H.UserPromptSubmit="UserPromptSubmit";H.PreCompact="PreCompact";H.SessionShutdown="SessionShutdown"})(V6||={});var T5={["TaskStart"]:"agent_start",["TaskResume"]:"agent_resume",["TaskCancel"]:"agent_abort",["TaskComplete"]:"agent_end",["TaskError"]:"agent_error",["PreToolUse"]:"tool_call",["PostToolUse"]:"tool_result",["UserPromptSubmit"]:"prompt_submit",["PreCompact"]:void 0,["SessionShutdown"]:"session_shutdown"},dN=new Map(Object.values(V6).map(($)=>[$.toLowerCase(),$])),lN=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function O5($){let W=vN($).toLowerCase();if(!lN.has(W))return;let Z=mN($,W).trim().toLowerCase();return dN.get(Z)}function I$($){let W=[],Z=new Set,Q=L5($).filter((J)=>xN(J));for(let J of Q)try{for(let j of gN(J,{withFileTypes:!0})){if(!j.isFile())continue;let X=O5(j.name);if(!X)continue;let Y=cN(J,j.name);if(Z.has(Y))continue;Z.add(Y),W.push({fileName:X,hookEventName:T5[X],path:Y})}}catch{}return W.sort((J,j)=>J.path.localeCompare(j.path))}function NZ($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))W[Z]=typeof Q==="string"?Q:JSON.stringify(Q);return W}function EZ($,W,Z){let Q=Z instanceof Error?`: ${Z.message}`:"",J=`${W}${Q}`;if($){try{$.log(J,{severity:"warn",...Z!==void 0?{error:Z}:{}})}catch{}return}console.warn(J)}function aN($,W){if(!W)return $;if(!$)return{...W};let Z=[$.context,W.context].filter((J)=>typeof J==="string"&&J.length>0).join(`
481
+ `),Q=[...$.appendMessages??[],...W.appendMessages??[]];return{cancel:$.cancel===!0||W.cancel===!0?!0:void 0,review:$.review===!0||W.review===!0?!0:void 0,context:Z||void 0,overrideInput:W.overrideInput!==void 0?W.overrideInput:$.overrideInput,systemPrompt:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function oN($){if(!$||typeof $!=="object")return;let W=$,Z=typeof W.context==="string"?W.context:typeof W.contextModification==="string"?W.contextModification:typeof W.errorMessage==="string"?W.errorMessage:void 0;return{cancel:typeof W.cancel==="boolean"?W.cancel:void 0,review:typeof W.review==="boolean"?W.review:void 0,context:Z,overrideInput:Object.hasOwn(W,"overrideInput")?W.overrideInput:void 0}}function mJ($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function C0($,W){let Z=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:W.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:W.workspacePath?[W.workspacePath]:[],workspaceInfo:W.workspaceInfo,userId:Z,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function sN($){let W=$.trim();if(!W)return{};let Q=W.split(`
482
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse hook stdout JSON"}}}async function tN($,W){let Z=$.stdin;if(!Z)throw Error("hook command failed to create stdin");await new Promise((Q,J)=>{let j=!1,X=()=>{Z.off("error",V),Z.off("finish",B),$.off("close",H)},Y=(G)=>{if(j)return;if(j=!0,X(),G){let K=G.code;if(K==="EPIPE"||K==="ERR_STREAM_DESTROYED"){Q();return}J(G);return}Q()},V=(G)=>Y(G),B=()=>Y(),H=()=>Y();Z.on("error",V),Z.once("finish",B),$.once("close",H);try{Z.end(W)}catch(G){Y(G)}})}async function nK($,W){if(W.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await rK($,W)}catch(Z){let Q=Ww(W.command,process.platform,Z);if(!Q)throw Z;return await rK($,{...W,command:Q})}}async function rK($,W){let Z=iK(W.command,{env:W.env,debugRole:"hook"}),Q=pN(Z[0],Z.slice(1),{cwd:W.cwd,env:cJ(W.env),stdio:W.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W.detached,windowsHide:!0}),J=new Promise((K)=>{Q.once("spawn",()=>K())}),j=new Promise((K,F)=>{Q.once("error",(A)=>F(A))}),X=JSON.stringify($);if(await Promise.race([J,j]),await tN(Q,X),W.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let Y="",V="",B=!1,H;Q.stdout.on("data",(K)=>{Y+=K.toString()}),Q.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,Q.kill("SIGKILL")},W.timeoutMs);Q.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:D}=sN(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:D,timedOut:B})})});return await Promise.race([G,j])}function eN($){try{let Z=iN($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Z?.startsWith("#!"))return;let Q=Z.slice(2).trim();if(!Q)return;let J=Q.split(/\s+/).filter(Boolean);return J.length>0?J:void 0}catch{return}}function $w($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function Ww($,W=process.platform,Z){if(W!=="win32"||!$w(Z))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function aK($){if($.length===0)return;let[W,...Z]=$,Q=W.replace(/\\/g,"/").toLowerCase(),J=Q.split("/").at(-1)??Q;if(J==="env")return aK(Z);if(J==="bash"||J==="sh"||J==="zsh")return[J,...Z];if(J==="python3"||J==="python")return process.platform==="win32"?["py","-3",...Z]:[J,...Z];return $}function Zw($){let W=eN($);if(W&&W.length>0)return[...aK(W)??W,$];let Z=$.toLowerCase();if(Z.endsWith(".sh")||Z.endsWith(".bash")||Z.endsWith(".zsh"))return["bash",$];if(Z.endsWith(".js")||Z.endsWith(".mjs")||Z.endsWith(".cjs"))return iK(["node",$],{debugRole:"hook"});if(Z.endsWith(".ts")||Z.endsWith(".mts")||Z.endsWith(".cts"))return["bun","run",$];if(Z.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Z.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function Qw($){let W={};for(let Z of I$($)){if(!Z.hookEventName)continue;let Q=Z.hookEventName,J=W[Q]??[];J.push(Zw(Z.path)),W[Q]=J}return W}async function Jw($){let W;for(let Z of $.commands){let Q=Z.join(" ");try{let J=await nK($.payload,{command:Z,cwd:$.cwd,env:cJ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(J?.timedOut){EZ($.logger,`hook command timed out: ${Q}`);continue}if(J?.parseError){EZ($.logger,`hook command returned invalid JSON control output: ${Q} (${J.parseError})`);continue}W=aN(W,oN(J?.parsedJson))}catch(J){EZ($.logger,`hook command failed: ${Q}`,J)}}return W}function m2($){for(let W of $.commands){let Z=W.join(" ");nK($.payload,{command:W,cwd:$.cwd,env:cJ(process.env),detached:!0}).catch((Q)=>{EZ($.logger,`hook command failed: ${Z}`,Q)})}}function x$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function vJ($,W){return{...x$($.snapshot),userMessage:W}}function oK($){return{...x$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function sK($){return{...x$($.snapshot),iteration:$.snapshot.iteration,record:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}}function tK($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function jw($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}function B6($){let W={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Z=(Q)=>{let J=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
483
+ `,X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??nN(pK(),"hooks.jsonl");pK(X),rN(X,J,"utf8")};return{beforeRun:async(Q)=>{let J=vJ(Q,"");Z({...C0(J,W),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let J=oK(Q);Z({...C0(J,W),hookName:"tool_call",iteration:J.iteration,tool_call:{id:J.call.id,name:J.call.name,input:J.call.input},preToolUse:{toolName:J.call.name,parameters:NZ(J.call.input)}});return},afterTool:async(Q)=>{let J=sK(Q);Z({...C0(J,W),hookName:"tool_result",iteration:J.iteration,tool_result:J.record,postToolUse:{toolName:J.record.name,parameters:NZ(J.record.input),result:typeof J.record.output==="string"?J.record.output:JSON.stringify(J.record.output),success:!J.record.error,executionTimeMs:J.record.durationMs}});return},afterRun:async({snapshot:Q,result:J})=>{let j=x$(Q);if(J.status==="completed"){Z({...C0(j,W),hookName:"agent_end",iteration:J.iterations,turn:{outputText:J.outputText,status:J.status},taskComplete:{taskMetadata:{}}});return}if(J.status==="aborted"||mJ(J.error?.message)){Z({...C0(j,W),hookName:"agent_abort",reason:J.error?.message,taskCancel:{taskMetadata:{}}});return}if(J.error)Z({...C0(j,W),hookName:"agent_error",iteration:J.iterations,error:{name:J.error.name,message:J.error.message,stack:J.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let J=vJ({snapshot:Q.snapshot},tK(Q.message.content));Z({...C0(J,W),hookName:"prompt_submit",userPromptSubmit:{prompt:J.userMessage,attachments:[]}})}}}function z5($){let W=Qw($.workspacePath);if(!Object.values(W).some((G)=>G.length>0))return;let Q=async(G,K)=>{let F=W[K]??[];if(F.length===0)return;m2({commands:F,cwd:$.cwd,logger:$.logger,payload:K==="agent_resume"?{...C0(G,$),hookName:K,taskResume:{taskMetadata:{},previousState:{}}}:{...C0(G,$),hookName:K,taskStart:{taskMetadata:{}}}})},J=async(G)=>{let K=W.prompt_submit??[];if(K.length>0)m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"prompt_submit",userPromptSubmit:{prompt:G.userMessage,attachments:[]}}})},j=async(G)=>{let K=W.tool_call??[];if(K.length===0)return;return Jw({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...C0(G,$),hookName:"tool_call",iteration:G.iteration,tool_call:{id:G.call.id,name:G.call.name,input:G.call.input},preToolUse:{toolName:G.call.name,parameters:NZ(G.call.input)}}})},X=async(G)=>{let K=W.tool_result??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"tool_result",iteration:G.iteration,tool_result:G.record,postToolUse:{toolName:G.record.name,parameters:NZ(G.record.input),result:typeof G.record.output==="string"?G.record.output:JSON.stringify(G.record.output),success:!G.record.error,executionTimeMs:G.record.durationMs}}})},Y=async(G)=>{let K=W.agent_end??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"agent_end",iteration:G.iteration,turn:G.turn,taskComplete:{taskMetadata:{}}}})},V=async(G)=>{let K=W.agent_error??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"agent_error",iteration:G.iteration,error:{name:G.error.name,message:G.error.message,stack:G.error.stack}}})},B=async(G)=>{if(mJ(G.reason)){let F=W.agent_abort??[];if(F.length>0)m2({commands:F,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"agent_abort",reason:G.reason,taskCancel:{taskMetadata:{}}}})}let K=W.session_shutdown??[];if(K.length===0)return;m2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...C0(G,$),hookName:"session_shutdown",reason:G.reason}})},H={};if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0||(W.prompt_submit?.length??0)>0){if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0)H.beforeRun=async(G)=>{let K=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(x$(G.snapshot),K);return};if((W.prompt_submit?.length??0)>0)H.onEvent=async(G)=>{if(G.type!=="message-added"||G.message.role!=="user")return;await J(vJ({snapshot:G.snapshot},tK(G.message.content)))}}if((W.tool_call?.length??0)>0)H.beforeTool=async(G)=>{let K=await j(oK(G));return jw(K)};if((W.tool_result?.length??0)>0)H.afterTool=async(G)=>{await X(sK(G));return};if((W.agent_end?.length??0)>0)H.afterRun=async({snapshot:G,result:K})=>{if(K.status!=="completed")return;await Y({...x$(G),iteration:K.iterations,turn:{outputText:K.outputText,status:K.status}})};if((W.agent_error?.length??0)>0||(W.agent_abort?.length??0)>0||(W.session_shutdown?.length??0)>0){let G=H.afterRun;H.afterRun=async(K)=>{await G?.(K);let{snapshot:F,result:A}=K;if(A.status==="aborted"||mJ(A.error?.message)){await B({...x$(F),reason:A.error?.message});return}if(A.error)await V({...x$(F),iteration:A.iterations,error:A.error})}}return H}function H6($){return Y6("core.hook_config_files",z5($))}function v2($,W){let Z=$.map((Q)=>Q[W]).filter((Q)=>typeof Q==="function");if(Z.length===0)return;return async(Q)=>{let J;for(let j of Z){let X=await j(Q);if(!X||typeof X!=="object")continue;let Y=X;J={...J??{},...Y,stop:J?.stop===!0||Y.stop===!0?!0:Y.stop,options:J?.options||Y.options?{...J?.options??{},...Y.options??{}}:void 0}}return J}}function c2($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return;return{beforeRun:v2(W,"beforeRun"),afterRun:v2(W,"afterRun"),beforeModel:v2(W,"beforeModel"),afterModel:v2(W,"afterModel"),beforeTool:v2(W,"beforeTool"),afterTool:v2(W,"afterTool"),onEvent:v2(W,"onEvent")}}var eK={};w(eK,{normalizeRuntimeCapabilities:()=>P0});function P0(...$){let W,Z;for(let J of $){if(!J)continue;if(J.toolExecutors)W={...W??{},...J.toolExecutors};if(J.requestToolApproval)Z=J.requestToolApproval}let Q=W&&Object.keys(W).length>0;if(!Q&&!Z)return;return{...Q?{toolExecutors:W}:{},...Z?{requestToolApproval:Z}:{}}}var VF={};w(VF,{toProviderConfig:()=>s0,emptyStoredProviderSettings:()=>v$,StoredProviderSettingsSchema:()=>A6,StoredProviderSettingsEntrySchema:()=>oZ,ProviderSettingsSchemaTyped:()=>F6});import{z as m$}from"zod";var YF={};w(YF,{toProviderConfig:()=>s0,safeParseSettings:()=>aZ,safeCreateProviderConfig:()=>sJ,parseSettings:()=>nZ,normalizeProviderId:()=>K6,isBuiltInProviderId:()=>aJ,createProviderConfig:()=>oJ,SapSettingsSchema:()=>pZ,ReasoningSettingsSchema:()=>cZ,ProviderSettingsSchema:()=>g$,ProviderProtocolSchema:()=>gZ,ProviderIdSchema:()=>N5,ProviderClientSchema:()=>mZ,OcaSettingsSchema:()=>rZ,ModelCatalogSettingsSchema:()=>iZ,GcpSettingsSchema:()=>dZ,BUILT_IN_PROVIDER_IDS:()=>nJ,BUILT_IN_PROVIDER:()=>E5,AzureSettingsSchema:()=>lZ,AwsSettingsSchema:()=>uZ,AuthSettingsSchema:()=>vZ});import*as o0 from"@cline/llms";import{z as N}from"zod";var XF={};w(XF,{resolveProviderConfig:()=>R5,getProviderConfig:()=>xZ,getLiveModelsCatalog:()=>G6,clearPublicModelsCatalogCache:()=>ww,clearPrivateModelsCatalogCache:()=>iJ,clearLiveModelsCatalogCache:()=>rJ,OPENAI_COMPATIBLE_PROVIDERS:()=>M5,DEFAULT_MODELS_CATALOG_URL:()=>yZ});import*as $0 from"@cline/llms";function uJ($){if(!Array.isArray($))return[];return $.map((W)=>{if(typeof W==="string")return W.trim();if(W&&typeof W==="object"){let Z=W;for(let Q of[Z.id,Z.name,Z.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter((W)=>W.length>0)}function Xw($,W){let Z=uJ($);if(Z.length>0)return Z;if(!$||typeof $!=="object")return[];let Q=$,J=uJ(Q.data??Q.models);if(J.length>0)return J;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let X=Object.keys(Q.models).filter((Y)=>Y.trim().length>0);if(X.length>0)return X}let j=Q.providers?.[W];if(j&&typeof j==="object"){let Y=uJ(j.models??j);if(Y.length>0)return Y}return[]}async function wZ($,W){let Z=await fetch($,{method:"GET"});if(!Z.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Z.status}`);return Xw(await Z.json(),W)}function $F($){return $.replace(/\/+$/,"")}function CZ($,W,Z){let Q=Z?.trim();if(!Q)return;let J=$?.trim();if(!J||!W?.trim())return Q;try{let j=new URL(Q),X=new URL(W),Y=new URL(J);if(j.origin!==X.origin)return Q;let V=$F(X.pathname),B=$F(Y.pathname);if(V&&j.pathname.startsWith(`${V}/`)){let H=j.pathname.slice(V.length);Y.pathname=`${B}${H}`}else Y.pathname=j.pathname;return Y.search=j.search,Y.hash=j.hash,Y.toString()}catch{return Q}}function Yw($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{...Z}]))}function Vw($){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 Bw=Object.values($0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:Yw($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),ZF=Object.fromEntries(Bw.map(($)=>[$.id,$]));function Hw($){return ZF[$]}function Gw(){return Object.fromEntries(Object.entries(ZF).filter(([,$])=>Vw($)))}function QF($=[]){let W=$.flatMap((Z)=>{switch(Z){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Z];default:return[]}});return W.length>0?W:void 0}var yZ="https://models.dev/api.json",Kw=600000,JF=300000,Fw=5000,bZ=new Map,q5=new Map,dJ=new Map,PZ=new Map;async function Aw(){return $0.getGeneratedProviderModels()}async function Uw($,W={},Z={},Q={},J={},j={}){if($==="litellm")return $0.sortModelsByReleaseDate(Q);let X=await Aw(),Y=$0.resolveProviderModelCatalogKeys($),V=Object.assign({},...Y.map((G)=>X[G]??{}));if(Boolean($0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl))return $0.sortModelsByReleaseDate({...J,...j});if($==="openai-codex")return $0.sortModelsByReleaseDate({...W,...$0.filterOpenAICodexModels(Z),...J,...j});if($==="cline-pass"&&Object.keys(Z).length>0)return{...Z,...j};let H=$0.sortModelsByReleaseDate({...V,...W,...Z,...Q,...J});if($==="cline")return $0.sortModelsByReleaseDate({...$0.preferCanonicalModelIds(H,$0.VERCEL_OPENROUTER_MODEL_ID_ALIAS_RULES),...j});return $0.sortModelsByReleaseDate({...H,...j})}function Dw($,W){let Z=$0.resolveProviderModelCatalogKeys($);return Object.assign({},...Z.map((Q)=>W[Q]??{}))}function hZ($){let W=$?.trim();return W&&W.length>0?W:""}function pJ($){let W=$.apiKey?.trim()||$.accessToken?.trim();return W&&W.length>0?W:void 0}function _w($){let W=2166136261;for(let Z=0;Z<$.length;Z+=1)W^=$.charCodeAt(Z),W+=(W<<1)+(W<<4)+(W<<7)+(W<<8)+(W<<24);return(W>>>0).toString(16)}function fw($,W){return`${$}:${hZ(W.baseUrl)}:${_w(pJ(W)??"")}`}async function kZ($,W,Z=Fw){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await fetch($,{...W,signal:Q.signal})}finally{clearTimeout(J)}}function u2($,W,Z){if(Z&&!$.includes(W))$.push(W)}function IZ($,W){let Z=["streaming","tools"];return u2(Z,"images",Boolean(W.supportsImages)),u2(Z,"prompt-cache",Boolean(W.supportsPromptCache)),u2(Z,"reasoning",Boolean(W.supportsReasoning)),{id:$,name:W.name??$,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxTokens:W.maxTokens,capabilities:Z,releaseDate:W.releaseDate,status:"active"}}async function Lw($,W){let Z=await kZ("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"}});if(!Z.ok)throw Error(`Baseten model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;if(Y.includes("whisper")||Y.includes("tts")||Y.includes("embedding"))continue;let V=X.supported_features??[];j[Y]=IZ(Y,{name:Y,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,supportsReasoning:V.includes("reasoning")||V.includes("reasoning_effort"),supportsImages:!1})}return j}function WF($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let W=Number($);return Number.isFinite(W)?W:void 0}return}async function Tw($,W){let Z=await kZ("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":W}});if(!Z.ok)throw Error(`Hicap model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;j[Y]=IZ(Y,{name:Y,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return j}async function Ow($,W){let Q=`${(hZ($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,J=await kZ(Q,{method:"GET",headers:{Authorization:`Bearer ${W}`,accept:"application/json"}});if(!J.ok)throw Error(`Poolside model refresh failed: HTTP ${J.status}`);let X=(await J.json())?.data??[],Y={};for(let V of X){let B=V.id?.trim();if(!B)continue;let H=V.supported_features??[],G=V.supported_sampling_parameters??[],K=V.input_modalities??[],F=["streaming"];u2(F,"tools",H.includes("tools")),u2(F,"reasoning",H.includes("reasoning")),u2(F,"temperature",G.includes("temperature")),u2(F,"images",K.includes("image"));let A={input:WF(V.pricing?.prompt),output:WF(V.pricing?.completion)};Y[B]={id:B,name:V.name??B,description:V.description,contextWindow:V.context_length,maxInputTokens:V.context_length,maxTokens:V.max_completion_tokens,capabilities:F,pricing:A.input!==void 0||A.output!==void 0?A:void 0,status:"active"}}return Y}function zw($){let W=hZ($).replace(/\/+$/,"");if(!W)return"http://localhost:4000";return W.endsWith("/v1")?W.slice(0,-3):W}function qw($){return[`${$}/v1/model/info`,`${$}/model/info`]}async function Mw($){let W=(await $.text().catch(()=>"")).replace(/\s+/g," ").trim(),Z=500,Q=W?`: ${W.slice(0,500)}${W.length>500?"...":""}`:"";return`HTTP ${$.status}${Q}`}async function Rw($,W){let Z=zw($.baseUrl),Q=[],J=[["x-litellm-api-key",{"x-litellm-api-key":W}],["Authorization",{Authorization:`Bearer ${W}`}]];for(let j of qw(Z))for(let[X,Y]of J)try{let V=await kZ(j,{method:"GET",headers:{accept:"application/json",...Y}});if(V.ok){let H=(await V.json())?.data??[],G={};for(let K of H){let F=K.model_name?.trim(),D=K.litellm_params?.model?.trim()||F;if(!D)continue;let U=K.model_info,f=IZ(D,{name:F??D,maxTokens:U?.max_output_tokens??U?.max_tokens,maxInputTokens:U?.max_input_tokens??U?.max_tokens,supportsImages:U?.supports_vision,supportsPromptCache:U?.supports_prompt_caching,supportsReasoning:U?.supports_reasoning});if(G[D]=f,F)G[F]={...f,id:F,name:F}}return G}Q.push(`${new URL(j).pathname} (${X}): ${await Mw(V)}`)}catch(V){let B=V instanceof Error?V.message:String(V);Q.push(`${new URL(j).pathname} (${X}): ${B}`)}throw Error(`LiteLLM model refresh failed. Attempts: ${Q.join("; ")}`)}var jF={baseten:Lw,hicap:Tw,litellm:Rw,poolside:Ow},lJ=new Map,SZ=new Map;function Ew($,W){return`${$}:${hZ(W.baseUrl)}`}async function Nw($,W,Z){let Q=$0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],J=CZ(Z.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!J)return{};let j=W?.cacheTtlMs??JF,X=Ew($,Z),Y=Date.now(),V=lJ.get(X);if(V&&V.expiresAt>Y)return V.data;let B=SZ.get(X);if(B)return B;let H=wZ(J,$).then((G)=>{let K=Object.fromEntries(G.map((F)=>[F,IZ(F,{name:F})]));return lJ.set(X,{data:K,expiresAt:Y+j}),K}).finally(()=>{SZ.delete(X)});return SZ.set(X,H),H}function ww(){lJ.clear(),SZ.clear()}async function Cw($,W){let Z=pJ(W);if(!Z)return{};let Q=jF[$];if(!Q)return{};return Q(W,Z)}function Pw($,W,Z){if(!Z)return!1;if(!jF[$])return!1;if(W?.loadPrivateOnAuth===!1)return!1;return Boolean(pJ(Z))}async function Sw($,W,Z){let Q=W?.cacheTtlMs??JF,J=fw($,Z),j=Date.now(),X=dJ.get(J);if(X&&X.expiresAt>j)return X.data;let Y=PZ.get(J);if(Y)return Y;let V=Cw($,Z).then((B)=>{return dJ.set(J,{data:B,expiresAt:j+Q}),B}).finally(()=>{PZ.delete(J)});return PZ.set(J,V),V}async function bw($){return $0.fetchLiveProviderModels($,globalThis.fetch)}async function G6($={}){let W=$.url??yZ,Z=$.cacheTtlMs??Kw,Q=Date.now(),J=bZ.get(W);if(J&&J.expiresAt>Q)return J.data;let j=q5.get(W);if(j)return j;let X=bw(W).then((Y)=>{return bZ.set(W,{data:Y,expiresAt:Q+Z}),Y}).finally(()=>{q5.delete(W)});return q5.set(W,X),X}function rJ($){if($){bZ.delete($),q5.delete($);return}bZ.clear(),q5.clear()}function iJ(){dJ.clear(),PZ.clear()}function yw($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{baseUrl:Z.baseUrl,modelId:Z.modelId,capabilities:QF(Z.capabilities)}]))}var M5=yw(Gw());function xZ($){let W=Hw($);if(!W)return;return{baseUrl:W.baseUrl||void 0,modelId:W.modelId,knownModels:W.knownModels,capabilities:QF(W.capabilities)}}async function R5($,W,Z){let Q=xZ($);if(!Q)return;try{let J=W?.loadLatestOnInit?await G6(W):void 0,j=J?Dw($,J):{},X=Z&&Pw($,W,Z)?await Sw($,W,Z):{},V=Boolean($0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Z??{providerId:$,modelId:Q.modelId,baseUrl:Q.baseUrl}:Z,B=V?await Nw($,W,V).catch(()=>({})):{},H=await Uw($,Q.knownModels,j,X,B,Z?.knownModels);return{...Q,knownModels:H}}catch(J){if(W?.failOnError)throw J;if($==="litellm")return{...Q,knownModels:{}};return Q}}var E5=o0.BUILT_IN_PROVIDER,nJ=o0.BUILT_IN_PROVIDER_IDS,aJ=o0.isBuiltInProviderId,K6=o0.normalizeProviderId,N5=N.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),gZ=N.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),mZ=N.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),vZ=N.object({apiKey:N.string().optional(),accessToken:N.string().optional(),refreshToken:N.string().optional(),expiresAt:N.number().int().positive().optional(),accountId:N.string().optional(),organizationId:N.string().optional(),organizationName:N.string().optional(),memberId:N.string().optional(),metadata:N.record(N.string(),N.unknown()).optional()}),hw=N.enum(["none","low","medium","high","xhigh"]),cZ=N.object({enabled:N.boolean().optional(),effort:hw.optional(),budgetTokens:N.number().int().positive().optional()}),uZ=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()}),dZ=N.object({projectId:N.string().optional(),region:N.string().optional()}),lZ=N.object({apiVersion:N.string().optional(),useIdentity:N.boolean().optional()}),pZ=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()}),rZ=N.object({mode:N.enum(["internal","external"]).optional(),usePromptCache:N.boolean().optional()}),iZ=N.object({loadLatestOnInit:N.boolean().optional(),loadPrivateOnAuth:N.boolean().optional(),url:N.string().url().optional(),cacheTtlMs:N.number().int().positive().optional(),failOnError:N.boolean().optional()}),g$=N.object({provider:N5,apiKey:N.string().optional(),auth:vZ.optional(),model:N.string().optional(),protocol:gZ.optional(),client:mZ.optional(),routingProviderId:N5.optional(),maxTokens:N.number().int().positive().optional(),contextWindow:N.number().int().positive().optional(),baseUrl:N.string().url().optional(),headers:N.record(N.string(),N.string()).optional(),timeout:N.number().int().positive().optional(),reasoning:cZ.optional(),aws:uZ.optional(),gcp:dZ.optional(),azure:lZ.optional(),sap:pZ.optional(),oca:rZ.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:iZ.optional()});function nZ($){return g$.parse($)}function aZ($){return g$.safeParse($)}function kw($){return $.protocol==="openai-responses"||$.client==="openai"}function s0($,W={}){let Z=$.provider,Q=K6(Z),J=W.includeKnownModels!==!1,j=$.reasoning?.effort||"none",X=j==="none"?void 0:j,Y=M5[Q],V=Object.assign({},...o0.resolveProviderModelCatalogKeys(Q).map((D)=>o0.getGeneratedModelsForProvider(D))),B=Object.keys(V)[0],H=h8(Q,$),G=$.baseUrl??(Q==="oca"?$.oca?.mode==="internal"?gW:mW:Y?.baseUrl),K=$.routingProviderId??(kw($)&&Q!==E5.OPENAI_NATIVE?E5.OPENAI_NATIVE:void 0),F=J?Y?.knownModels??(Object.keys(V).length>0?V:void 0):void 0,A={providerId:Z,clientType:$.client,routingProviderId:K,modelId:$.model??Y?.modelId??B??"default",...J?{knownModels:F}:{},apiKey:H,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:G,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:X,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??Y?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(A).filter(([D,U])=>U!==void 0))}function oJ($){let W=nZ($);return s0(W)}function sJ($){let W=aZ($);if(W.success)return{success:!0,config:s0(W.data)};return{success:!1,error:W.error}}var F6=g$;var oZ=m$.object({settings:g$,updatedAt:m$.string().datetime(),tokenSource:m$.enum(["manual","oauth","migration"]).default("manual")}),A6=m$.object({version:m$.literal(1),lastUsedProvider:m$.string().min(1).optional(),providers:m$.record(m$.string(),oZ)});function v$(){return{version:1,providers:{}}}X1();var BF={};w(BF,{InMemoryWorkspaceManager:()=>U6});import{upsertWorkspaceInfo as Iw,WorkspaceManifestSchema as tJ}from"@cline/shared";class U6{manifest;listeners=new Set;constructor($){this.manifest=tJ.parse($??{workspaces:{}})}async addWorkspacePath($){let W=await _8($);return this.manifest=Iw(this.manifest,W),this.emit({type:"workspace_added",workspace:W}),W}async switchWorkspace($){let W=_1($),Z=this.manifest.workspaces[W];if(Z)return this.manifest=tJ.parse({...this.manifest,currentWorkspacePath:W}),this.emit({type:"workspace_switched",workspace:Z}),Z;let Q=await this.addWorkspacePath(W);return this.manifest=tJ.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let W=_1($);return this.manifest.workspaces[W]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let W of this.listeners)W($)}}z0();import{createHash as xw}from"node:crypto";var HF=new Set,GF=new Set;function gw($){return xw("sha256").update($).digest("hex")}function mw($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function KF($){if(!$.telemetry)return;let W=gw($.rootPath),Z=$.rootCount??1;if(!HF.has(W))HF.add(W),s9($.telemetry,{root_count:Z,vcs_types:mw($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!GF.has(W)){GF.add(W);let Q=Error($.initError.message);Q.name=$.initError.errorType||"Error",t9($.telemetry,Q,{fallback_to_single_root:!0,workspace_count:Z})}}function uw($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function dw($,W,Z){if(W.length>0)for(let j of W)Z?.log(j.message,{severity:"warn"});if($.length===0)return;let Q=$.slice(0,3).map(uw).join("; "),J=$.length>3?`; and ${$.length-3} more`:"";Z?.log(`Some plugins failed to initialize. ${Q}${J}. Use --verbose for more details.`,{severity:"warn"});for(let j of $)Z?.log(`Plugin initialization failed (${j.phase}) for ${j.pluginPath}`,{severity:"warn",stack:j.stack,pluginPath:j.pluginPath,pluginName:j.pluginName})}function lw($,W){let Z=typeof $.thinking==="boolean",Q=typeof $.reasoningEffort==="string";if(!Z&&!Q)return W;return{...W??{},...Z?{enabled:$.thinking}:{},...Q?{effort:$.reasoningEffort}:{}}}function FF($,W){return cw($,W)}function pw($){let W=0;for(let Z of $??[]){if(Z.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0)?.kind==="recovery_notice")continue;W+=1}return W}function rw($,W,Z,Q,J,j){let X=Q.getProviderSettings($.providerId),Y=J||X?.modelCatalog?{...J??{},...X?.modelCatalog??{}}:void 0,V=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,B=vw({providerId:$.providerId,sessionId:W,source:Z,defaultSource:F0.CLI,client:{name:$.extensionContext?.client?.name,version:$.extensionContext?.client?.version,versionHeaderFallback:$.headers?.["X-CLIENT-VERSION"],platform:$.extensionContext?.client?.platform,platformVersion:$.extensionContext?.client?.platformVersion,isMultiRoot:$.extensionContext?.client?.isMultiRoot},coreVersion:R8,openAiCodex:{accountId:V?.accountId??X?.auth?.accountId,accessToken:V?.accessToken??$.apiKey??X?.auth?.accessToken??X?.apiKey,userAgentVersion:process.env.npm_package_version},headers:{stored:X?.headers,config:$.headers,session:V?.headers}}),H={...X??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??X?.apiKey,baseUrl:$.baseUrl??X?.baseUrl,headers:void 0,reasoning:lw($,X?.reasoning),modelCatalog:Y},G={...s0(H),...V??{}};if(B)G.headers=B;if($.knownModels)G.knownModels=$.knownModels;if($.extensionContext)G.extensionContext=$.extensionContext;let F=$.fetch??G.fetch??j;if(F)G.fetch=F;return G}async function AF($){let{input:W,sessionId:Z,providerSettingsManager:Q,defaultTelemetry:J,defaultCapabilities:j,defaultToolPolicies:X,defaultFetch:Y,onPluginEvent:V,onTeamEvent:B,createSubAgentLifecycleCallbacks:H,createSpawnTool:G,localRuntime:K,readSessionMetadata:F,writeSessionMetadata:A}=$,D=Z$(W.config),{modelCatalogDefaults:U,userInstructionService:f,configExtensions:_,onTeamRestored:R,...O}=K??{},T=Object.keys(O).length>0?O:void 0,{workspaceInfo:L,workspaceMetadata:C,gitState:E,durationMs:p,vcsType:x,initError:P}=await y7(D),r=T?.extensionContext,d={...r??{},workspace:{...L,...r?.workspace??{}},session:{...r?.session??{},sessionId:Z},logger:r?.logger??T?.logger,telemetry:r?.telemetry??T?.telemetry??J};KF({telemetry:d.telemetry,rootPath:L.rootPath,workspaceInfo:L,rootCount:1,vcsType:x,durationMs:p,initError:P,featureFlagEnabled:!0});let I1=H6({cwd:W.config.cwd,workspacePath:D,rootSessionId:Z,logger:T?.logger,workspaceInfo:L}),$2=KK(T?.hooks)?void 0:B6({rootSessionId:Z,workspacePath:D,workspaceInfo:L}),A$=c2([T?.hooks,$2]),I0;if(FF(_,"plugins"))try{I0=await X6({pluginPaths:T?.pluginPaths,workspacePath:D,cwd:W.config.cwd,onEvent:V,providerId:W.config.providerId,modelId:W.config.modelId,workspaceInfo:L,session:d.session,client:d.client,user:d.user,logger:d.logger,telemetry:d.telemetry,automation:d.automation}),dw(I0.failures,I0.warnings,T?.logger)}catch(t6){let F8=t6 instanceof Error?t6.message:String(t6);T?.logger?.log?.(`plugin loading failed; continuing without plugins (${F8})`)}let D1=DJ(I1?[I1]:void 0,DJ(T?.extensions,fW(I0?.extensions))),K8=FF(_,"plugins")?J$(I0?.pluginPaths??[]):void 0,V0={...W.config,...T??{},sessionId:Z,hooks:A$,extensions:D1,extensionContext:d,telemetry:d.telemetry},d0=rw(V0,Z,W.source,Q,U,Y),J1=c2([V0.hooks,V0.checkpoint?.enabled===!0?lK({cwd:V0.cwd,sessionId:Z,logger:V0.logger,createCheckpoint:V0.checkpoint?.createCheckpoint,initialRunCount:pw(W.initialMessages),readSessionMetadata:F,writeSessionMetadata:A}):void 0]),y={...V0,providerConfig:d0,workspaceMetadata:C,hooks:J1},j1=W.toolPolicies??V0.toolPolicies??X,k=P0(j,W.capabilities),W0=k?.requestToolApproval,T0=k?.toolExecutors,M0=H?.(y),d9=new U6({currentWorkspacePath:L.rootPath,workspaces:{[L.rootPath]:L}});return{effectiveInput:W,config:y,providerConfig:d0,workspaceMetadata:C,workspaceInfo:L,gitState:E,extensions:D1,hooks:J1,toolPolicies:j1,requestToolApproval:W0,pluginSandboxShutdown:I0?.shutdown,runtimeBuilderInput:{config:y,hooks:J1,extensions:D1,onTeamEvent:B,createSpawnTool:G,onTeamRestored:R,onSubAgentEvent:M0?.onSubAgentEvent,onSubAgentStart:M0?.onSubAgentStart,onSubAgentEnd:M0?.onSubAgentEnd,userInstructionService:f,pluginSkillDirectories:K8,configExtensions:_,toolExecutors:T0,toolPolicies:j1,workspaceManager:d9,logger:y.logger,telemetry:y.telemetry,requestToolApproval:W0}}}import{existsSync as sZ,mkdirSync as iw,readdirSync as nw,rmdirSync as aw,rmSync as ow,unlinkSync as sw}from"node:fs";import{dirname as UF,join as w5}from"node:path";function X0(){return new Date().toISOString()}function C5($){if(!$||!sZ($))return;try{sw($)}catch{}}function tw($){let W=t8($);if(W)return{rootSessionId:W.rootSessionId,fileStem:`${W.agentId}__${W.teamTaskId}`};let Z=Y5($);if(Z)return{rootSessionId:Z.rootSessionId,fileStem:Z.agentId};return{rootSessionId:$,fileStem:$}}class eJ{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return w5(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let W=this.sessionArtifactsDir($);if(!sZ(W))iw(W,{recursive:!0});return W}sessionMessagesPath($){return w5(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionCompactionPath($){return w5(this.sessionArtifactsDir($),`${$}.compaction.json`)}sessionManifestPath($,W=!1){let Z=W?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return w5(Z,`${$}.json`)}removeSessionDirIfEmpty($){let W=this.sessionArtifactsDir($),Z=this.ensureSessionsDir();while(W.startsWith(Z)&&W!==Z){if(!sZ(W)){W=UF(W);continue}try{if(nw(W).length>0)break;aw(W)}catch{break}W=UF(W)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!sZ($))return;try{ow($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,W,Z){let{rootSessionId:Q,fileStem:J}=tw($),j=this.sessionArtifactsDir(Q);return{messagesPath:w5(j,`${J}.messages.json`)}}}import{resolveDocumentsExtensionPath as ew}from"@cline/shared/storage";z0();function DF($,W,Z,Q,J){if(Z)$W($.telemetry,{ulid:W,apiProvider:$.providerId,...J});else e9($.telemetry,{ulid:W,apiProvider:$.providerId,...J});$C($.telemetry,{workspacePath:Q})}function $C($,W){let Z=ew("Hooks"),Q=I$(W.workspacePath),J=new Map;for(let j of Q){let X=j.hookEventName??"unknown",Y=J.get(X)??{global:0,workspace:0};if(j.path===Z||j.path.startsWith(`${Z}/`))Y.global+=1;else Y.workspace+=1;J.set(X,Y)}for(let[j,X]of J.entries())HW($,j,X.global,X.workspace)}function _F($,W){for(let Z of W.mentions)VW($,Z,W.matchedFiles.includes(Z)?1:0,"file",!W.matchedFiles.includes(Z));for(let Z of W.matchedFiles)XW($,"file",Z.length);for(let Z of W.ignoredMentions)YW($,"file","not_found",Z)}var D_={};w(D_,{ProviderSettingsManager:()=>k1});import{chmodSync as z_,existsSync as DY,mkdirSync as kg,readFileSync as Ig,renameSync as xg,rmSync as gg,writeFileSync as mg}from"node:fs";import{basename as q_,dirname as _Y}from"node:path";import{resolveProviderSettingsPath as vg}from"@cline/shared/storage";var q={};w(q,{writeModelsFileSync:()=>w9,writeHubDiscovery:()=>zW,writeGlobalSettings:()=>f1,withHubStartupLock:()=>qW,verifyHubConnection:()=>z1,updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>T6,updateMcpServerOAuthStateAsync:()=>i5,updateMcpServerOAuthState:()=>i2,updateLocalProvider:()=>V7,uninstallPlugin:()=>T9,uninstallMarketplaceSkill:()=>iQ,uninstallMarketplacePlugin:()=>nQ,uninstallMarketplaceMcpServerFromSettings:()=>pQ,uninstallMarketplaceEntry:()=>wX,truncateNotificationBody:()=>k9,truncateCommandOutput:()=>L2,toggleDisabledTool:()=>DW,toTeamProgressLifecycleEvent:()=>S6,toProviderConfig:()=>s0,toHubStatusUrl:()=>t7,toHubHealthUrl:()=>MW,toHookConfigFileName:()=>O5,syncStoredProviderRegistration:()=>cX,syncPluginMcpServersToSettings:()=>f9,summarizeUsageFromMessages:()=>$6,stopLocalHubServerGracefully:()=>H3,startLocalOAuthServer:()=>H1,startHubWebSocketServer:()=>g9,startHubServer:()=>L_,startClineDeviceAuth:()=>z3,splitCoreSessionConfig:()=>D4,spawnDetachedHubServerWithRetry:()=>N8,spawnDetachedHubServer:()=>J3,setTelemetryOptOutGlobally:()=>PV,setSdkLogger:()=>D3,setMcpServerDisabled:()=>p2,setDisabledTools:()=>p7,setDisabledPlugin:()=>gV,setCompactionStrategyGlobally:()=>hV,setAutoUpdateEnabledGlobally:()=>bV,sendHubCommand:()=>UB,sdkDebug:()=>s,saveProviderOAuthCredentials:()=>F2,saveLocalProviderSettings:()=>nX,saveLocalProviderOAuthCredentials:()=>tX,sanitizeSessionToken:()=>h2,safeParseSettings:()=>aZ,safeCreateProviderConfig:()=>sJ,runSubprocessEvent:()=>g6,runHook:()=>v6,reviveTeamStateDates:()=>KZ,restartLocalHubIfIdleAfterStartupTimeout:()=>CW,resolveWorkspaceHubOwnerContext:()=>tV,resolveWorkflowsConfigSearchPaths:()=>v5,resolveSkillsConfigSearchPaths:()=>g5,resolveSharedHubOwnerContext:()=>V1,resolveSessionBackend:()=>sj,resolveRulesConfigSearchPaths:()=>m5,resolveProviderConfig:()=>R5,resolveProviderApiKeyFromSettings:()=>C3,resolveProductionHubOwnerContext:()=>O1,resolvePluginSkillDirectoriesFromPaths:()=>J$,resolvePluginConfigSearchPaths:()=>_5,resolveModelsRegistryPath:()=>h1,resolveMcpServerRegistrations:()=>t0,resolveMarketplaceMcpServerName:()=>z9,resolveLocalClineAuthToken:()=>$Y,resolveHubUrl:()=>G3,resolveHubOwnerContext:()=>r1,resolveHubEndpointOptions:()=>T1,resolveHubBuildId:()=>OW,resolveHooksConfigSearchPaths:()=>L5,resolveDisabledToolNames:()=>L1,resolveDisabledPluginPaths:()=>G4,resolveDefaultMcpSettingsPath:()=>J0,resolveDefaultHubPort:()=>E8,resolveDefaultHubPathname:()=>Q3,resolveDefaultHubHost:()=>Z3,resolveCoreSelectedToolIds:()=>AZ,resolveCoreDistinctId:()=>x0,resolveCompatibleLocalHubUrl:()=>T4,resolveClineDir:()=>nV,resolveClineDataDir:()=>Y2,resolveAndLoadAgentPlugins:()=>X6,resolveAgentPluginPaths:()=>Q$,requestHubShutdown:()=>L4,requestDesktopToolApproval:()=>KX,removePluginMcpServersFromSettings:()=>L9,rememberRecoverableLocalHubUrl:()=>O$,registerRemoteConfigSessionBlobUpload:()=>IQ,registerMcpServersFromSettingsFile:()=>n2,registerDisposable:()=>Sg,refreshProviderModelsFromSource:()=>aX,refreshOpenAICodexToken:()=>xW,refreshOcaToken:()=>cW,refreshClineToken:()=>kW,readSessionCheckpointHistory:()=>Z8,readRemoteConfigSessionBlobUploadMetadata:()=>QX,readModelsFileSync:()=>n6,readHubDiscovery:()=>D0,readGlobalSettings:()=>E0,readCompactionStrategyGlobally:()=>yV,readBearerToken:()=>L7,projectSessionCompactionState:()=>A2,probeHubServer:()=>i1,probeHubConnection:()=>AB,prewarmFileIndex:()=>ZZ,prewarmDetachedHubServer:()=>EW,prepareRemoteConfigCoreIntegration:()=>jX,parseWorkflowConfigFromMarkdown:()=>x5,parseUserCommandEnvelope:()=>Pg,parseSkillConfigFromMarkdown:()=>k5,parseSettings:()=>nZ,parseSessionCompactionState:()=>G1,parseRuleConfigFromMarkdown:()=>I5,parsePluginSource:()=>Q7,parseMcpInstallArgs:()=>_9,parseHookEventPayload:()=>m6,parseConfiguredAgentConfig:()=>Y9,normalizeWorkspacePath:()=>_1,normalizeUserInput:()=>Cg,normalizeSdkError:()=>wg,normalizeRuntimeCapabilities:()=>P0,normalizeProviderId:()=>K6,normalizeOAuthProvider:()=>oX,normalizeHubWebSocketUrl:()=>z$,noopBasicLogger:()=>Ng,migrateLegacyProviderSettings:()=>y9,mergeRulesForSystemPrompt:()=>D8,mergeAgentHooks:()=>c2,marketplaceEntryKey:()=>NX,markLocalProviderEnabled:()=>pX,makeTeamTaskSubSessionId:()=>X5,makeSubSessionId:()=>s8,loginOpenAICodex:()=>q4,loginOcaOAuth:()=>N4,loginLocalProvider:()=>sX,loginClineOAuth:()=>O4,loginAndSaveProviderOAuthCredentials:()=>C4,loginAndSaveLocalProviderOAuthCredentials:()=>eX,loadOpenTelemetryAdapter:()=>$g,loadMcpSettingsFile:()=>l2,loadLlmsConfigFromFile:()=>KY,loadConfiguredAgentConfigs:()=>w6,loadAgentPluginsFromPathsWithDiagnostics:()=>x2,loadAgentPluginsFromPaths:()=>LZ,loadAgentPluginFromPath:()=>U5,listSessionHistoryFromBackend:()=>Pj,listPluginToolsWithDiagnostics:()=>_Q,listPluginTools:()=>o5,listMcpServerOAuthStatuses:()=>n5,listLocalProviders:()=>rX,listHookConfigFiles:()=>I$,isToolDisabledGlobally:()=>kV,isTelemetryOptedOutGlobally:()=>UW,isSessionNotFoundError:()=>p1,isRuleEnabled:()=>l9,isPluginDisabledGlobally:()=>xV,isOfficialPluginSlug:()=>Z7,isOAuthProvider:()=>K2,isMarketplaceSkillInstalled:()=>rQ,isLocalHubOrigin:()=>UY,isLocalHubHostName:()=>T7,isHubReconnectableTransportError:()=>V3,isHubCommandTimeoutError:()=>wW,isDiscoveryFilePresent:()=>oV,isClinePassLimitMessage:()=>Ag,isClinePassLimitError:()=>Fg,isClineOrgIndividualInferenceSubscriptionMessage:()=>Kg,isClineOrgIndividualInferenceSubscriptionError:()=>Gg,isClineNotSubscribedMessage:()=>Hg,isClineNotSubscribedError:()=>Bg,isClineAccountActionRequest:()=>tZ,isBuiltInProviderId:()=>aJ,isAutoUpdateEnabledGlobally:()=>SV,installPlugin:()=>hX,installMcpServer:()=>FX,identifyAccount:()=>c1,hashSecret:()=>N0,hasMcpSettingsFile:()=>X$,getValidOpenAICodexCredentials:()=>M4,getValidOcaCredentials:()=>w4,getValidClineCredentials:()=>z4,getProviderOAuthCredentialsFromSettings:()=>P4,getProviderConfigFields:()=>WY,getProviderConfig:()=>xZ,getProviderAuthStorageId:()=>w3,getProviderAuthHandler:()=>H0,getPersistedProviderApiKey:()=>h8,getMcpServerOAuthState:()=>r2,getMarketplaceSkillCandidates:()=>q9,getLocalProviderModels:()=>iX,getLiveModelsCatalog:()=>G6,getGlobalMarketplaceSkillPaths:()=>M9,getFileIndex:()=>t1,getCurrentContextSize:()=>TJ,getCoreHeadlessToolNames:()=>j5,getCoreDefaultEnabledToolIds:()=>FZ,getCoreBuiltinToolCatalog:()=>b2,getCoreAcpToolNames:()=>UZ,getClinePassSubscriptionUrl:()=>Vg,getClineOrgIndividualInferenceSubscriptionMessage:()=>Yg,getClineNotSubscribedMessage:()=>Xg,getClineDefaultSystemPrompt:()=>Ug,generateWorkspaceInfoWithDiagnostics:()=>$4,generateWorkspaceInfo:()=>_8,formatRulesForSystemPrompt:()=>U8,formatProviderOAuthApiKey:()=>P3,formatDisplayUserInput:()=>Eg,findInstalledGlobalMarketplaceSkillName:()=>R9,findCheckpointForRun:()=>I6,filterExtensionToolRegistrations:()=>fW,filterDisabledTools:()=>u1,filterDisabledPluginPaths:()=>_W,fetchClineRecommendedModels:()=>HY,extractClinePassLimitMessage:()=>jg,executeClineAccountAction:()=>eZ,ensureHubWebSocketServer:()=>O7,ensureHubServer:()=>T_,ensureDetachedHubServer:()=>JB,ensureCustomProvidersLoadedSync:()=>S9,ensureCustomProvidersLoaded:()=>b9,ensureCompatibleLocalHubUrl:()=>H2,enrichPromptWithMentions:()=>d8,emptyWorkspaceManifest:()=>qg,emptyStoredProviderSettings:()=>v$,discoverPluginModulePaths:()=>f5,disablePluginMcpServersInSettings:()=>_X,deriveSubsessionStatus:()=>V5,deleteLocalProvider:()=>B7,defineLlmsConfig:()=>GY,createWorkflowsConfigDefinition:()=>d5,createUserInstructionConfigService:()=>c$,createToolPoliciesWithPreset:()=>JZ,createTool:()=>zg,createTeamName:()=>mQ,createSubprocessHooks:()=>bQ,createSpawnAgentTool:()=>y$,createSkillsConfigDefinition:()=>c5,createShellTool:()=>o4,createShellExecutor:()=>T2,createSessionHost:()=>h6,createSessionCompactionState:()=>k8,createRuntimeHost:()=>h6,createRulesConfigDefinition:()=>u5,createRemoteConfigSessionMessagesArtifactUploader:()=>JX,createProviderConfig:()=>oJ,createOpenTelemetryTelemetryService:()=>U4,createOAuthClientCallbacks:()=>D6,createMcpTools:()=>M6,createLocalHubScheduleRuntimeHandlers:()=>f_,createLlmsSdk:()=>AY,createInitialAccumulatedUsage:()=>q0,createInMemoryHubOwnerContext:()=>aV,createHubServerUrl:()=>Y1,createHubAuthToken:()=>TW,createHookConfigFileHooks:()=>z5,createHookConfigFileExtension:()=>H6,createHookAuditHooks:()=>B6,createEditorExecutor:()=>M2,createDisabledMcpToolPolicy:()=>a5,createDisabledMcpToolPolicies:()=>DQ,createDelegatedAgentConfigProvider:()=>S$,createDelegatedAgent:()=>b$,createDefaultToolsWithPreset:()=>jZ,createDefaultTools:()=>N$,createDefaultShellExecutor:()=>$5,createDefaultMcpServerClientFactory:()=>z6,createDefaultExecutors:()=>l8,createCoreSettingsService:()=>o2,createCoreSessionSnapshot:()=>N1,createContributionRegistry:()=>Og,createContextCompactionPrepareTurn:()=>m4,createConfiguredTelemetryService:()=>d1,createConfiguredTelemetryHandle:()=>M8,createConfiguredAgentTools:()=>C6,createCompactionStateAwarePrepareTurn:()=>v4,createClineTelemetryServiceMetadata:()=>Tg,createClineTelemetryServiceConfig:()=>Lg,createCheckpointComparePlan:()=>wQ,createBuiltinTools:()=>y2,createApplyPatchExecutor:()=>q2,createAgentTeamsTools:()=>S2,createAgentRuntime:()=>hg,createAgentHooksExtension:()=>Y6,connectToHub:()=>PW,computePatchChanges:()=>c8,completeClineDeviceAuth:()=>q3,compareCheckpointToWorkspace:()=>A9,collectPluginMcpOAuthCandidates:()=>J7,clearPrivateModelsCatalogCache:()=>iJ,clearLiveModelsCatalogCache:()=>rJ,clearHubDiscovery:()=>g0,captureWorkspacePathResolved:()=>qV,captureWorkspaceInitialized:()=>s9,captureWorkspaceInitError:()=>t9,captureToolUsage:()=>T8,captureTokenUsage:()=>WW,captureTaskRestarted:()=>$W,captureTaskCreated:()=>e9,captureTaskCompleted:()=>Y4,captureSubagentExecution:()=>B4,captureSkillUsed:()=>QW,captureSdkError:()=>fg,captureProviderConfigured:()=>MV,captureProviderApiError:()=>V4,captureModeSwitch:()=>ZW,captureMistakeLimitReached:()=>jW,captureMentionUsed:()=>XW,captureMentionSearchResults:()=>VW,captureMentionFailed:()=>YW,captureHookDiscovery:()=>HW,captureExtensionActivated:()=>zV,captureDiffEditFailure:()=>JW,captureConversationTurnEvent:()=>L8,captureCompactionSkipped:()=>KW,captureCompactionExecuted:()=>GW,captureAuthSucceeded:()=>m1,captureAuthStarted:()=>g1,captureAuthLoggedOut:()=>L$,captureAuthFailed:()=>v1,captureAgentUnexpectedReasoningTokens:()=>OV,captureAgentTeamCreated:()=>BW,captureAgentCreated:()=>T$,buildWorkspaceMetadata:()=>W4,buildTeamProgressSummary:()=>P6,buildSdkErrorProperties:()=>Dg,buildRemoteConfigSessionBlobUploadMetadata:()=>hQ,buildMcpInstallTransport:()=>vQ,buildDelegatedAgentConfig:()=>C2,buildConnectionUpdate:()=>XJ,buildConfiguredAgentToolName:()=>V9,buildConfiguredAgentToolDescriptors:()=>B9,buildCheckpointWorkspaceDiff:()=>CQ,bootstrapAgentTeams:()=>o8,authorizeMcpServerOAuth:()=>KQ,addLocalProvider:()=>lX,accumulateUsageTotals:()=>L0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>h5,UnifiedConfigFileWatcher:()=>d2,ToolPresets:()=>a0,TelemetryService:()=>z8,TelemetryLoggerSink:()=>A4,TEAM_TOOL_NAMES:()=>a8,SubprocessSandbox:()=>Q6,StructuredCommandInputSchema:()=>_2,StoredProviderSettingsSchema:()=>A6,StoredProviderSettingsEntrySchema:()=>oZ,SqliteTeamStore:()=>j8,SqliteSessionStore:()=>C1,SessionVersioningService:()=>o$,SessionVersioningError:()=>c0,SessionSource:()=>F0,SessionNotFoundError:()=>l1,SapSettingsSchema:()=>pZ,SKILLS_CONFIG_DIRECTORY_NAME:()=>y5,SESSION_STATUSES:()=>B5,SESSION_NOT_FOUND_ERROR_CODE:()=>X2,SDK_ERROR_TELEMETRY_EVENT:()=>bg,RpcClineAccountService:()=>S5,RemoteRuntimeHost:()=>N6,ReasoningSettingsSchema:()=>cZ,RULES_CONFIG_DIRECTORY_NAME:()=>XQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>kQ,ProviderSettingsSchema:()=>g$,ProviderSettingsManager:()=>k1,ProviderProtocolSchema:()=>gZ,ProviderIdSchema:()=>N5,ProviderClientSchema:()=>mZ,PatchActionType:()=>z2,OpenTelemetryProvider:()=>q8,OcaSettingsSchema:()=>rZ,OPENAI_COMPATIBLE_PROVIDERS:()=>M5,NodeHubClient:()=>B1,NoOpFeatureFlagsProvider:()=>W8,NativeHubTransportAdapter:()=>x9,ModelCatalogSettingsSchema:()=>iZ,McpSettingsUpdateSkippedError:()=>L6,McpSettingsMutatorPurityError:()=>u$,McpSettingsLockTimeoutError:()=>d$,MAX_COMMAND_OUTPUT_CHARS:()=>a1,LocalRuntimeHost:()=>b1,Llms:()=>Wg,InMemoryWorkspaceManager:()=>U6,InMemoryMcpManager:()=>a2,HubUIClient:()=>A3,HubTransportError:()=>y0,HubSessionClient:()=>F3,HubServerTransport:()=>o6,HubScheduleService:()=>f8,HubScheduleCommandService:()=>A8,HubRuntimeHost:()=>Y$,HubCommandError:()=>w8,HookEventPayloadSchema:()=>SQ,HookEventNameSchema:()=>PQ,HookConfigFileName:()=>V6,HOOK_CONFIG_FILE_EVENT_MAP:()=>T5,HOOKS_CONFIG_DIRECTORY_NAME:()=>RZ,GlobalSettingsSchema:()=>H4,GcpSettingsSchema:()=>dZ,FileTeamPersistenceStore:()=>K7,FeatureFlagsService:()=>$8,FeatureFlagDefaultValue:()=>Rg,FEATURE_FLAGS:()=>Mg,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>f7,DefaultToolNames:()=>O0,DefaultRuntimeBuilder:()=>d6,DefaultLlmsSdk:()=>h9,DEFAULT_MODELS_CATALOG_URL:()=>yZ,DEFAULT_HUB_PORT:()=>$3,DEFAULT_HUB_PATHNAME:()=>W3,DEFAULT_HUB_HOST:()=>e7,CoreSettingsService:()=>l$,CoreSessionService:()=>S1,ContributionRegistry:()=>_g,CommandExitError:()=>o1,ClinePassLimitError:()=>Jg,ClineOrgIndividualInferenceSubscriptionError:()=>Qg,ClineNotSubscribedError:()=>Zg,ClineCore:()=>U9,ClineAccountService:()=>P5,ChatViewStateSchema:()=>YY,ChatSummarySchema:()=>_7,ChatSessionStatusSchema:()=>A7,ChatSessionConfigSchema:()=>F7,ChatMessageSchema:()=>D7,ChatMessageRoleSchema:()=>U7,CORE_TELEMETRY_EVENTS:()=>v,CORE_BUILD_VERSION:()=>VY,BrowserWebSocketHubAdapter:()=>I9,BUILT_IN_PROVIDER_IDS:()=>nJ,BUILT_IN_PROVIDER:()=>E5,AzureSettingsSchema:()=>lZ,AwsSettingsSchema:()=>uZ,AuthSettingsSchema:()=>vZ,AgentTeamsRuntime:()=>e2,AgentTeam:()=>y6,Agent:()=>yg,ALL_DEFAULT_TOOL_NAMES:()=>D$});M(q,T00);import*as Wg from"@cline/llms";import{ClineNotSubscribedError as Zg,ClineOrgIndividualInferenceSubscriptionError as Qg,ClinePassLimitError as Jg,extractClinePassLimitMessage as jg,getClineNotSubscribedMessage as Xg,getClineOrgIndividualInferenceSubscriptionMessage as Yg,getClinePassSubscriptionUrl as Vg,isClineNotSubscribedError as Bg,isClineNotSubscribedMessage as Hg,isClineOrgIndividualInferenceSubscriptionError as Gg,isClineOrgIndividualInferenceSubscriptionMessage as Kg,isClinePassLimitError as Fg,isClinePassLimitMessage as Ag}from"@cline/llms";import{buildClineSystemPrompt as Ug,buildSdkErrorProperties as Dg,ContributionRegistry as _g,captureSdkError as fg,createClineTelemetryServiceConfig as Lg,createClineTelemetryServiceMetadata as Tg,createContributionRegistry as Og,createTool as zg,emptyWorkspaceManifest as qg,FEATURE_FLAGS as Mg,FeatureFlagDefaultValue as Rg,formatDisplayUserInput as Eg,noopBasicLogger as Ng,normalizeSdkError as wg,normalizeUserInput as Cg,parseUserCommandEnvelope as Pg,registerDisposable as Sg,SDK_ERROR_TELEMETRY_EVENT as bg}from"@cline/shared";import"@cline/shared/storage";var LF={};w(LF,{isClineAccountActionRequest:()=>tZ,executeClineAccountAction:()=>eZ,RpcClineAccountService:()=>S5,ClineAccountService:()=>P5});function WC($){if(typeof $!=="object"||$===null||!("error"in $))return;let W=$.error;return typeof W==="string"&&W.trim()?W:void 0}function fF($,W,Z){let Q=WC(Z);if(Q)return Q;let J=W.trim();if(J){let j=J.length>200?`${J.slice(0,200)}...`:J;return`Cline account request failed with status ${$}: ${j}`}return`Cline account request failed with status ${$}`}class P5{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let W=$.apiBaseUrl.trim();if(!W)throw Error("apiBaseUrl is required");this.apiBaseUrl=W,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let W=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(W)}/balance`)}async fetchUsageTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/usages`)).items??[]}async fetchPaymentTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchAvailableSubscriptionPlans($){let W=new URL("/api/v1/plans",this.apiBaseUrl);if($?.type)W.searchParams.set("type",$.type);return this.request(`${W.pathname}${W.search}`)}async fetchCurrentUserPlan(){return this.request("/api/v1/users/me/plan")}async fetchOrganization($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}`)}async fetchOrganizationBalance($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}/balance`)}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");let Z=await this.resolveOrganizationMemberId(W,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(W)}/members/${encodeURIComponent(Z)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let W=$?.trim();if(W)return W;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let J=await this.fetchMe();if(!J.id?.trim())throw Error("Unable to resolve current user id");return J.id}async resolveOrganizationMemberId($,W){let Z=W?.trim();if(Z)return Z;let J=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(J)return J;let X=(await this.fetchUserOrganizations()).find((Y)=>Y.organizationId===$)?.memberId;if(!X?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return X}async request($,W){let Z=(await this.getAuthTokenFn())?.trim();if(!Z)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},J=new AbortController,j=setTimeout(()=>J.abort(),this.requestTimeoutMs);try{let X=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:W?.method??"GET",headers:{Authorization:`Bearer ${Z}`,"Content-Type":"application/json",...Q??{}},body:W?.body!==void 0?JSON.stringify(W.body):void 0,signal:J.signal});if(X.status===204||W?.expectNoContent){if(!X.ok)throw Error(`Cline account request failed with status ${X.status}`);return}let Y=await X.text(),V;if(Y.trim())try{V=JSON.parse(Y)}catch{if(!X.ok)throw Error(fF(X.status,Y,void 0));throw Error("Cline account response was not valid JSON")}if(!X.ok)throw Error(fF(X.status,Y,V));if(typeof V==="object"&&V!==null){let B=V;if(typeof B.success==="boolean"){if(!B.success)throw Error(B.error||"Cline account request failed");return B.data}}if(V===void 0||V===null)throw Error("Cline account response payload was empty");return V}finally{clearTimeout(j)}}}function tZ($){return $.action==="clineAccount"}async function eZ($,W){switch($.operation){case"fetchMe":return W.fetchMe();case"fetchBalance":return W.fetchBalance($.userId);case"fetchUsageTransactions":return W.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return W.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return W.fetchUserOrganizations();case"fetchOrganizationBalance":return W.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return W.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await W.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return W.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class S5{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:W})}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:W,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var TF={};w(TF,{createOAuthClientCallbacks:()=>D6});function D6($){return{onAuth:({url:W,instructions:Z})=>{if($.onOutput?.(Z??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(W)).catch((Q)=>{$.onOpenUrlError?.({url:W,error:Q})})}catch(Q){$.onOpenUrlError?.({url:W,error:Q})}$.onOutput?.(W)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}var lU={};w(lU,{ClineCore:()=>U9});function OF($){if($===!0)return{};if(!$)return;return $}function zF($){if($==="user")return"global";return $}class $j{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let W=this.getService().ingestEvent($);return{event:W.event,duplicate:W.duplicate,matchedSpecIds:W.matchedSpecs.map((Z)=>Z.specId),queuedRuns:W.queuedRuns,suppressions:W.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function qF($){let{host:W}=$;return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||F0.CLI,interactive:!1,config:{providerId:K6(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:JC(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content),delivery:Q.delivery});if(!J)throw Error("ClineCore automation runtime returned no result");return{result:QC(J)}},async abortSession(Z){return await W.abort(Z,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}function $Q($){let W=ZC($.automationService,$.automation),Z=$.context?.client??($.clientName?{name:$.clientName}:void 0),Q=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),J=$.context?.logger??$.logger,j=$.context?.telemetry??$.telemetry;if(!W&&!Z&&!Q&&!J&&!j)return $.context;return{...$.context??{},...Z?{client:Z}:{},...Q?{user:Q}:{},...J?{logger:J}:{},...j?{telemetry:j}:{},...W?{automation:W}:{}}}function ZC($,W){if(!$)return;return{ingestEvent:(Z)=>{W.ingestEvent(Z)}}}function QC($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function JC($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var RA={};w(RA,{createCoreSettingsService:()=>o2,CoreSettingsService:()=>l$});import{existsSync as t5,readFileSync as dP}from"node:fs";import{basename as Dj,dirname as fA,extname as lP,isAbsolute as OA,join as pP,relative as zA,resolve as LA}from"node:path";var IF={};w(IF,{resolveWorkflowsConfigSearchPaths:()=>v5,resolveSkillsConfigSearchPaths:()=>g5,resolveRulesConfigSearchPaths:()=>m5,parseWorkflowConfigFromMarkdown:()=>x5,parseSkillConfigFromMarkdown:()=>k5,parseRuleConfigFromMarkdown:()=>I5,createWorkflowsConfigDefinition:()=>d5,createUserInstructionConfigService:()=>c$,createSkillsConfigDefinition:()=>c5,createRulesConfigDefinition:()=>u5,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>h5,UnifiedConfigFileWatcher:()=>d2,SKILLS_CONFIG_DIRECTORY_NAME:()=>y5,RULES_CONFIG_DIRECTORY_NAME:()=>XQ});import{createHash as jC}from"node:crypto";import{watch as XC}from"node:fs";import{readdir as YC,readFile as VC}from"node:fs/promises";import{join as BC}from"node:path";function HC($){return jC("sha1").update($).digest("hex")}function EF($){return Boolean($&&typeof $==="object"&&"code"in $)}function MF($){return EF($)&&$.code==="ENOENT"}function RF($){return EF($)&&($.code==="EACCES"||$.code==="EPERM")}class d2{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,W){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=W?.debounceMs??75,this.emitParseErrors=W?.emitParseErrors??!1;for(let Z of $){if(this.definitionsByType.has(Z.type))throw Error(`Duplicate unified config definition type '${Z.type}'.`);this.definitionsByType.set(Z.type,Z),this.recordsByType.set(Z.type,new Map),this.discoveredDirectoriesByType.set(Z.type,new Set);for(let Q of Z.directories){let J=this.baseTypesByDirectory.get(Q);if(J)J.add(Z.type);else this.baseTypesByDirectory.set(Q,new Set([Z.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let W=this.definitionsByType.get($);if(!W)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(W)})}getSnapshot($){let W=this.recordsByType.get($);return new Map([...W?.entries()??[]].map(([Z,Q])=>[Z,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[W,Z]of this.recordsByType.entries())$.set(W,new Map([...Z.entries()].map(([Q,J])=>[Q,{...J}])));return $}emit($){for(let W of this.listeners)W($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[W,Z]of this.watchersByDirectory.entries()){if($.has(W))continue;Z.close(),this.watchersByDirectory.delete(W)}this.watchedTypesByDirectory=$;for(let W of $.keys()){if(this.watchersByDirectory.has(W))continue;try{let Z=XC(W,()=>{let Q=this.watchedTypesByDirectory.get(W);if(!Q)return;for(let J of Q)this.pendingTypes.add(J);this.scheduleFlush()});this.watchersByDirectory.set(W,Z),Z.on("error",(Q)=>{let J=this.watchedTypesByDirectory.get(W);if(!J)return;for(let j of J)this.emit({kind:"error",type:j,error:Q,filePath:W})})}catch(Z){if(!MF(Z)&&!RF(Z)){let Q=$.get(W);if(!Q)continue;for(let J of Q)this.emit({kind:"error",type:J,error:Z,filePath:W})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let W of $){let Z=this.definitionsByType.get(W);if(!Z)continue;await this.refreshTypeInternal(Z)}})},this.debounceMs)}async refreshTypeInternal($){let{records:W,discoveredDirectories:Z}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[J,j]of Q.entries()){if(W.has(J))continue;this.emit({kind:"remove",type:$.type,id:J,filePath:j.filePath})}for(let[J,j]of W.entries()){let X=Q.get(J);if(X&&X.filePath===j.filePath&&X.fingerprint===j.fingerprint)continue;this.emit({kind:"upsert",record:{type:j.type,id:J,item:j.item,filePath:j.filePath}})}if(this.recordsByType.set($.type,W),this.discoveredDirectoriesByType.set($.type,Z),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let W=new Map,Z=new Set;for(let Q of $.directories){Z.add(Q);let J=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let j of J){let{fileName:X,filePath:Y}=j;if(Z.add(j.directoryPath),$.includeFile&&!$.includeFile(X,Y))continue;try{let V=await VC(Y,"utf8"),B={type:$.type,directoryPath:j.directoryPath,fileName:X,filePath:Y,content:V},H=$.parseFile(B),G=$.resolveId(H,B).trim();if(!G)continue;W.set(G,{type:$.type,id:G,item:H,filePath:Y,fingerprint:HC(V)})}catch(V){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:V,filePath:Y})}}}return{records:W,discoveredDirectories:Z}}buildDesiredTypesByDirectory(){let $=new Map;for(let[W,Z]of this.baseTypesByDirectory.entries())$.set(W,new Set(Z));for(let[W,Z]of this.discoveredDirectoriesByType.entries())for(let Q of Z){let J=$.get(Q);if(J)J.add(W);else $.set(Q,new Set([W]))}return $}async readDirectoryFileCandidates($){try{return(await YC($,{withFileTypes:!0})).filter((Z)=>Z.isFile()).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:BC($,Z.name)})).sort((Z,Q)=>Z.fileName.localeCompare(Q.fileName))}catch(W){if(MF(W)||RF(W))return[];throw W}}}import{readdir as Zj,readFile as GC,stat as Wj}from"node:fs/promises";import{basename as j$,dirname as KC,extname as ZQ,join as v0,resolve as b5}from"node:path";import{AGENTS_RULES_FILE_NAME as NF,RULES_CONFIG_DIRECTORY_NAME as XQ,resolveGlobalAgentsRulesPath as FC,resolveRulesConfigSearchPaths as AC,resolveSkillsConfigSearchPaths as UC,resolveWorkflowsConfigSearchPaths as DC,SKILLS_CONFIG_DIRECTORY_NAME as y5,WORKFLOWS_CONFIG_DIRECTORY_NAME as h5}from"@cline/shared/storage";import _C from"yaml";var WQ="SKILL.md",fC="managed.json",LC=new Set([".md",".markdown",".txt"]);function Qj($){return $.trim().toLowerCase()}function _6($){let W=$;return W?.code==="ENOENT"||W?.code==="EACCES"||W?.code==="EPERM"||W?.code==="ELOOP"}function QQ($){return LC.has(ZQ($).toLowerCase())}function wF($){let W=[],Z=new Set;for(let Q of $){let J=b5(Q);if(Z.has(J))continue;Z.add(J),W.push(Q)}return W}function TC($){let W=[...$?.directories??g5($?.workspacePath)];if($?.pluginSkillDirectories)W.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)W.push(...uK({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return wF(W)}async function Jj($){try{let W=await Zj($,{withFileTypes:!0}),Z=[];for(let Q of W){if(!Q.isDirectory())continue;let J=v0($,Q.name),j=v0(J,fC);try{let X=await GC(j,"utf8"),Y=JSON.parse(X);if(Y&&typeof Y==="object")Z.push(J)}catch(X){if(_6(X))continue;if(X?.name==="SyntaxError")continue;throw X}}return Z.sort((Q,J)=>Q.localeCompare(J))}catch(W){if(_6(W))return[];throw W}}function jj($){let W=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Z=$.match(W);if(!Z)return{data:{},body:$,hadFrontmatter:!1};let[,Q,J]=Z;try{let j=_C.parse(Q);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:J,hadFrontmatter:!0}}catch(j){let X=j instanceof Error?j.message:String(j);return{data:{},body:$,hadFrontmatter:!0,parseError:X}}}function JQ($,W,Z){if($===void 0||$===null){if(Z)throw Error(`Missing required frontmatter field '${W}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${W}' must be a string.`);let Q=$.trim();if(!Q&&Z)throw Error(`Frontmatter field '${W}' cannot be empty.`);return Q||void 0}function f6($,W){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${W}' must be a boolean.`);return $}function OC($,W){if(j$($.filePath).toLowerCase()!==NF.toLowerCase())return j$($.filePath,ZQ($.filePath));if(W&&b5($.filePath)===b5(W,NF))return"Workspace AGENTS.md";if(b5($.filePath)===b5(FC()))return"Global AGENTS.md";return j$($.filePath,ZQ($.filePath))}function k5($,W){let{data:Z,body:Q,parseError:J}=jj($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in skill file.");let Y=JQ(Z.name,"name",!1)??W.trim();if(!Y)throw Error("Missing skill name.");return{name:Y,description:JQ(Z.description,"description",!1),disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function I5($,W){let{data:Z,body:Q,parseError:J}=jj($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in rule file.");let X=JQ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing rule name.");return{name:X,disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function x5($,W){let{data:Z,body:Q,parseError:J}=jj($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in workflow file.");let X=JQ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing workflow name.");return{name:X,disabled:f6(Z.disabled,"disabled")??(f6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function g5($){return UC($)}function m5($){return AC($)}function v5($){return DC($)}async function CF($){if(j$($)===".cline"){let W=await Jj($);return(await Promise.all(W.map((Q)=>CF(v0(Q,y5))))).flat()}try{let W=await Zj($,{withFileTypes:!0}),Z=[];for(let Q of W){if(Q.isFile()&&Q.name===WQ){Z.push({directoryPath:$,fileName:Q.name,filePath:v0($,Q.name)});continue}let J=v0($,Q.name);if(Q.isDirectory()||Q.isSymbolicLink()&&await Wj(J).then((X)=>X.isDirectory()).catch((X)=>{if(_6(X))return!1;throw X}))Z.push({directoryPath:J,fileName:WQ,filePath:v0(J,WQ)})}return Z}catch(W){if(_6(W))return[];throw W}}async function jQ($){if(j$($)===".cline"){let W=await Jj($);return(await Promise.all(W.map((Q)=>jQ(v0(Q,"rules.md"))))).flat()}try{if((await Wj($)).isFile())return[{directoryPath:KC($),fileName:j$($),filePath:$}]}catch(W){if(!_6(W))throw W}try{let Z=(await Zj($,{withFileTypes:!0})).filter((J)=>J.isFile()&&QQ(J.name)).map((J)=>({directoryPath:$,fileName:J.name,filePath:v0($,J.name)})),Q=v0($,"AGENTS.md");try{if((await Wj(Q)).isFile()){if(!Z.some((X)=>X.fileName==="AGENTS.md"))Z.push({directoryPath:$,fileName:"AGENTS.md",filePath:Q})}}catch{}return Z}catch(W){if(_6(W))return[];throw W}}async function zC($){if(j$($)===".cline"){let W=await Jj($);return(await Promise.all(W.map((Q)=>jQ(v0(Q,h5))))).flat()}return jQ($)}function c5($){let W=TC($),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Z?wF([...W,Z]):W,discoverFiles:CF,includeFile:(Q)=>Q===WQ,parseFile:(Q)=>k5(Q.content,j$(Q.directoryPath)),resolveId:(Q)=>Qj(Q.name)}}function u5($){let W=$?.directories??m5($?.workspacePath),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Z?[...W,Z]:W,discoverFiles:jQ,includeFile:(Q,J)=>Q===".clinerules"||QQ(Q)||QQ(J),parseFile:(Q)=>I5(Q.content,OC(Q,$?.workspacePath)),resolveId:(Q)=>Qj(Q.name)}}function d5($){let W=$?.directories??v5($?.workspacePath),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Z?[...W,Z]:W,discoverFiles:zC,includeFile:(Q)=>QQ(Q),parseFile:(Q)=>x5(Q.content,j$(Q.filePath,ZQ(Q.filePath))),resolveId:(Q)=>Qj(Q.name)}}function PF($){let W=[c5($?.skills),u5($?.rules),d5($?.workflows)];return new d2(W,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as SF}from"@cline/shared";function qC($,W){if($.description?.trim())return SF($.description,".");if(W==="workflow")return;return SF($.instructions,".")}function MC($){return $.disabled!==!0}function bF($,W){return[...$.getSnapshot(W).entries()].map(([Z,Q])=>({id:Z,record:Q})).filter(({record:Z})=>MC(Z.item)).map(({id:Z,record:Q})=>({id:Z,name:Q.item.name,instructions:Q.item.instructions,description:qC(Q.item,W),kind:W})).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function l5($){let W=new Map;for(let Z of[...bF($,"workflow"),...bF($,"skill")])if(!W.has(Z.name))W.set(Z.name,Z);return[...W.values()].sort((Z,Q)=>Z.name.localeCompare(Q.name))}function yF($,W){if(!$.startsWith("/")||$.length<2)return $;let Z=$.match(/^\/(\S+)/);if(!Z)return $;let Q=Z[1];if(!Q)return $;let J=Q.length+1,j=$.slice(J),X=l5(W).find((Y)=>Y.name===Q);return X?`${X.instructions}${j}`:$}function YQ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function RC($){if(!$||$.length===0)return;let W=$.map(YQ).filter((Z)=>Z.length>0);return W.length>0?new Set(W):void 0}function EC($,W,Z){if(!Z)return!0;let Q=YQ($),J=YQ(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function p5($,W){let Z=RC(W);return[...$.getSnapshot("skill").entries()].map(([J,j])=>{let X=j.item;return{id:J,name:X.name.trim(),description:X.description?.trim(),disabled:X.disabled===!0,skill:X}}).filter((J)=>EC(J.id,J.name,Z))}function NC($,W){return p5($,W).filter((Z)=>!Z.disabled).map((Z)=>Z.name.trim()).filter((Z)=>Z.length>0).sort((Z,Q)=>Z.localeCompare(Q))}function wC($,W,Z){let Q=YQ(W);if(!Q)return{error:"Missing skill name."};let J=p5($,Z),j=J.find((H)=>H.id===Q);if(j){let{skill:H}=j;if(H.disabled===!0)return{error:`Skill "${H.name}" is configured but disabled.`};return{id:j.id,skill:H}}let X=Q.includes(":")?Q.split(":").at(-1)??Q:Q,Y=J.filter(({id:H})=>{if(H===X)return!0;return H.endsWith(`:${X}`)}),V=Y.filter(({skill:H})=>H.disabled!==!0);if(V.length===1){let{id:H,skill:G}=V[0];return{id:H,skill:G}}if(V.length>1)return{error:`Skill "${W}" is ambiguous. Use one of: ${V.map(({id:H})=>H).join(", ")}`};if(Y.length===1){let{skill:H}=Y[0];return{error:`Skill "${H.name}" is configured but disabled.`}}if(Y.length>1)return{error:`Skill "${W}" is ambiguous, and all matches are disabled: ${Y.map(({id:H})=>H).join(", ")}`};let B=NC($,Z);return{error:B.length>0?`Skill "${W}" not found. Available skills: ${B.join(", ")}`:"No skills are currently available."}}function Xj($,W=Promise.resolve(),Z){let Q=new Set,J=async(j,X)=>{await W;let Y=wC($,j,Z);if("error"in Y)return Y.error;let{id:V,skill:B}=Y;if(Q.has(V))return`Skill "${B.name}" is already running.`;Q.add(V);try{let H=X?.trim(),G=H?`
484
484
  <command-args>${H}</command-args>`:"",K=B.description?.trim()?`Description: ${B.description.trim()}
485
485
 
486
486
  `:"";return`<command-name>${B.name}</command-name>${G}
487
487
  <command-instructions>
488
488
  ${K}${B.instructions}
489
- </command-instructions>`}finally{Q.delete(V)}};return Object.defineProperty(J,"configuredSkills",{get:()=>p5($,Z).map(({skill:j,...X})=>X),enumerable:!0,configurable:!1}),J}function yF($){let W=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Q)=>Boolean(Q))},async setup(Q){if(await W,$.includeRules)Q.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>C7($.watcher)});if($.registerSkillsTool)Q.registerTool(O2(jj($.watcher,W,$.allowedSkillNames)));for(let J of l5($.watcher).filter((j)=>j.kind==="skill"&&$.includeSkills||j.kind==="workflow"&&$.includeWorkflows))Q.registerCommand({name:J.name,description:J.description,handler:(j)=>{let X=j.trim();return X?`${J.instructions}
489
+ </command-instructions>`}finally{Q.delete(V)}};return Object.defineProperty(J,"configuredSkills",{get:()=>p5($,Z).map(({skill:j,...X})=>X),enumerable:!0,configurable:!1}),J}function hF($){let W=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Q)=>Boolean(Q))},async setup(Q){if(await W,$.includeRules)Q.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>P7($.watcher)});if($.registerSkillsTool)Q.registerTool(O2(Xj($.watcher,W,$.allowedSkillNames)));for(let J of l5($.watcher).filter((j)=>j.kind==="skill"&&$.includeSkills||j.kind==="workflow"&&$.includeWorkflows))Q.registerCommand({name:J.name,description:J.description,handler:(j)=>{let X=j.trim();return X?`${J.instructions}
490
490
 
491
- ${X}`:J.instructions}})}}}class hF{watcher;ready;stopped=!1;constructor($){this.watcher=CF($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([W,Z])=>({type:$,id:W,filePath:Z.filePath,item:Z.item}))}listRuntimeCommands(){return l5(this.watcher)}resolveRuntimeSlashCommand($){return bF($,this.watcher)}hasConfiguredSkills($){return p5(this.watcher,$).some((W)=>!W.disabled)}createSkillsExecutor($){return jj(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return yF({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function c$($){return new hF($)}import{readFile as wC,writeFile as CC}from"node:fs/promises";import xF from"yaml";function PC($){let W=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Z=$.match(W);if(!Z)return{data:{},body:$,hadFrontmatter:!1};let[,Q,J]=Z,j=xF.parse(Q);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:J,hadFrontmatter:!0}}function IF($,W){return`---
492
- ${xF.stringify($).trimEnd()}
491
+ ${X}`:J.instructions}})}}}class kF{watcher;ready;stopped=!1;constructor($){this.watcher=PF($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([W,Z])=>({type:$,id:W,filePath:Z.filePath,item:Z.item}))}listRuntimeCommands(){return l5(this.watcher)}resolveRuntimeSlashCommand($){return yF($,this.watcher)}hasConfiguredSkills($){return p5(this.watcher,$).some((W)=>!W.disabled)}createSkillsExecutor($){return Xj(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return hF({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function c$($){return new kF($)}import{readFile as CC,writeFile as PC}from"node:fs/promises";import gF from"yaml";function SC($){let W=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Z=$.match(W);if(!Z)return{data:{},body:$,hadFrontmatter:!1};let[,Q,J]=Z,j=gF.parse(Q);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:J,hadFrontmatter:!0}}function xF($,W){return`---
492
+ ${gF.stringify($).trimEnd()}
493
493
  ---
494
- ${W}`}function SC($,W){let{data:Z,body:Q,hadFrontmatter:J}=PC($);if(!J&&W)return $;if(W){if(delete Z.disabled,Z.enabled===!1)delete Z.enabled;if(Object.keys(Z).length===0)return Q;return IF(Z,Q)}return Z.disabled=!0,IF(Z,Q)}async function gF({filePath:$,enabled:W}){let Z=await wC($,"utf8"),Q=SC(Z,W);return await CC($,Q),{filePath:$,enabled:W,disabled:!W}}var FA={};w(FA,{updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>T6,updateMcpServerOAuthStateAsync:()=>i5,updateMcpServerOAuthState:()=>i2,setMcpServerDisabled:()=>p2,resolvePluginMcpServerRegistrations:()=>FQ,resolveMcpServerRegistrations:()=>t0,resolveDefaultMcpSettingsPath:()=>J0,registerMcpServersFromSettingsFile:()=>n2,normalizePluginMcpServerRegistration:()=>Aj,loadMcpSettingsFile:()=>l2,listMcpServerOAuthStatuses:()=>n5,hasMcpSettingsFile:()=>X$,getMcpServerOAuthState:()=>r2,createMcpTools:()=>M6,createDisabledMcpToolPolicy:()=>a5,createDisabledMcpToolPolicies:()=>UQ,createDefaultMcpServerClientFactory:()=>z6,authorizeMcpServerOAuth:()=>GQ,McpSettingsUpdateSkippedError:()=>L6,McpSettingsMutatorPurityError:()=>u$,McpSettingsLockTimeoutError:()=>d$,InMemoryMcpManager:()=>a2});import{spawn as DP}from"node:child_process";import{StringDecoder as YA}from"node:string_decoder";import{UnauthorizedError as QA}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as _P}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as XP}from"node:crypto";import{UnauthorizedError as YP}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as VP}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as BP}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as HP}from"@modelcontextprotocol/sdk/client/streamableHttp.js";VQ();var GP="/mcp/oauth/callback",KP=[1456,1457,1458],FP=300000;function AP($){if($ instanceof Error){let W=$.message.trim();if(W.length>0)return W}return String($)}function UP($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function HQ($){let W={};try{W=r2($.serverName,{filePath:$.settingsPath})??{}}catch{W={}}let Z,Q,J=async(X)=>{let Y=O6(X(W))??{};try{W=i2($.serverName,()=>Y,{filePath:$.settingsPath})}catch{W=Y}};return{provider:{get redirectUrl(){return W.redirectUrl??$.redirectUrl},get clientMetadata(){return UP(W.redirectUrl??$.redirectUrl)},state:()=>{return Q=XP(),Q},clientInformation:()=>W.clientInformation,saveClientInformation:async(X)=>{await J((Y)=>({...Y,clientInformation:X,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>W.tokens,saveTokens:async(X)=>{let Y=Date.now();await J((V)=>({...V,tokens:X,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Y}))},redirectToAuthorization:async(X)=>{Z=X.toString(),await $.onAuthorizationUrl?.(Z)},saveCodeVerifier:async(X)=>{await J((Y)=>({...Y,codeVerifier:X,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!W.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return W.codeVerifier},invalidateCredentials:async(X)=>{await J((Y)=>{if(X==="all")return{lastError:Y.lastError,redirectUrl:Y.redirectUrl};return{...Y,...X==="client"?{clientInformation:void 0}:{},...X==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...X==="verifier"?{codeVerifier:void 0}:{},...X==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(X)=>{await J((Y)=>({...Y,discoveryState:X}))},discoveryState:()=>W.discoveryState},getLastAuthorizationUrl:()=>Z,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await J((X)=>({...X,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(X)=>{await J((Y)=>({...Y,lastError:X}))},clearError:async()=>{await J((X)=>({...X,lastError:void 0}))}}}function BQ($){let W=$.registration.transport;if(W.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Z=W.headers?{headers:W.headers}:void 0;if(W.type==="sse")return new BP(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch});return new HP(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch})}function ZA($){return new VP({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function GQ($){let W=$.serverName.trim();if(!W)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Z}=await Promise.resolve().then(() => (VQ(),WA)),Q=Z({filePath:$.filePath}).find((V)=>V.name===W);if(!Q)throw Error(`MCP server "${W}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${W}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${W}" uses stdio transport and does not support OAuth browser flow.`);let J=await H1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:KP,callbackPath:$.callbackPath??GP,timeoutMs:$.timeoutMs??FP,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!J.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let j=HQ({settingsPath:$.filePath,serverName:W,redirectUrl:J.callbackUrl,onAuthorizationUrl:async(V)=>{await $.openUrl?.(V)}});await j.resetInteractiveState();let X=ZA($),Y;try{let V=BQ({registration:Q,oauthProvider:j.provider,fetch:$.fetch});try{return await X.connect(V),await X.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" is already authorized.`}}catch(B){if(!(B instanceof YP))throw B;if(!j.getLastAuthorizationUrl())throw Error(`MCP server "${W}" did not provide an authorization URL.`);let G=await J.waitForCallback();if(!G)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(G.error)throw Error(`OAuth authorization failed: ${G.error}`);if(!G.code)throw Error("OAuth callback did not include an authorization code.");let K=j.getLastOAuthState();if(!K)throw Error(`MCP server "${W}" did not start an OAuth stateful authorization flow.`);if(G.state!==K)throw Error("OAuth authorization failed: state mismatch.");await V.finishAuth(G.code),Y=ZA($);let F=BQ({registration:Q,oauthProvider:j.provider,fetch:$.fetch});return await Y.connect(F),await Y.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" OAuth authorization completed.`}}}catch(V){let B=AP(V);throw await j.markError(B),Error(B)}finally{await X.close().catch(()=>{return}),await Y?.close().catch(()=>{return}),J.close()}}var fP="2024-11-05",LP=5000,TP=1500,JA="http://127.0.0.1:1456/mcp/oauth/callback";function KQ($){return $ instanceof Error?$.message:String($)}function jA($){let W=Buffer.from(JSON.stringify($),"utf8"),Z=Buffer.from(`Content-Length: ${W.byteLength}\r
494
+ ${W}`}function bC($,W){let{data:Z,body:Q,hadFrontmatter:J}=SC($);if(!J&&W)return $;if(W){if(delete Z.disabled,Z.enabled===!1)delete Z.enabled;if(Object.keys(Z).length===0)return Q;return xF(Z,Q)}return Z.disabled=!0,xF(Z,Q)}async function mF({filePath:$,enabled:W}){let Z=await CC($,"utf8"),Q=bC(Z,W);return await PC($,Q),{filePath:$,enabled:W,disabled:!W}}var AA={};w(AA,{updateMcpSettingsFileSync:()=>A1,updateMcpSettingsFile:()=>T6,updateMcpServerOAuthStateAsync:()=>i5,updateMcpServerOAuthState:()=>i2,setMcpServerDisabled:()=>p2,resolvePluginMcpServerRegistrations:()=>AQ,resolveMcpServerRegistrations:()=>t0,resolveDefaultMcpSettingsPath:()=>J0,registerMcpServersFromSettingsFile:()=>n2,normalizePluginMcpServerRegistration:()=>Uj,loadMcpSettingsFile:()=>l2,listMcpServerOAuthStatuses:()=>n5,hasMcpSettingsFile:()=>X$,getMcpServerOAuthState:()=>r2,createMcpTools:()=>M6,createDisabledMcpToolPolicy:()=>a5,createDisabledMcpToolPolicies:()=>DQ,createDefaultMcpServerClientFactory:()=>z6,authorizeMcpServerOAuth:()=>KQ,McpSettingsUpdateSkippedError:()=>L6,McpSettingsMutatorPurityError:()=>u$,McpSettingsLockTimeoutError:()=>d$,InMemoryMcpManager:()=>a2});import{spawn as _P}from"node:child_process";import{StringDecoder as VA}from"node:string_decoder";import{UnauthorizedError as JA}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as fP}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as YP}from"node:crypto";import{UnauthorizedError as VP}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as BP}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as HP}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as GP}from"@modelcontextprotocol/sdk/client/streamableHttp.js";BQ();var KP="/mcp/oauth/callback",FP=[1456,1457,1458],AP=300000;function UP($){if($ instanceof Error){let W=$.message.trim();if(W.length>0)return W}return String($)}function DP($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function GQ($){let W={};try{W=r2($.serverName,{filePath:$.settingsPath})??{}}catch{W={}}let Z,Q,J=async(X)=>{let Y=O6(X(W))??{};try{W=i2($.serverName,()=>Y,{filePath:$.settingsPath})}catch{W=Y}};return{provider:{get redirectUrl(){return W.redirectUrl??$.redirectUrl},get clientMetadata(){return DP(W.redirectUrl??$.redirectUrl)},state:()=>{return Q=YP(),Q},clientInformation:()=>W.clientInformation,saveClientInformation:async(X)=>{await J((Y)=>({...Y,clientInformation:X,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>W.tokens,saveTokens:async(X)=>{let Y=Date.now();await J((V)=>({...V,tokens:X,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Y}))},redirectToAuthorization:async(X)=>{Z=X.toString(),await $.onAuthorizationUrl?.(Z)},saveCodeVerifier:async(X)=>{await J((Y)=>({...Y,codeVerifier:X,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!W.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return W.codeVerifier},invalidateCredentials:async(X)=>{await J((Y)=>{if(X==="all")return{lastError:Y.lastError,redirectUrl:Y.redirectUrl};return{...Y,...X==="client"?{clientInformation:void 0}:{},...X==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...X==="verifier"?{codeVerifier:void 0}:{},...X==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(X)=>{await J((Y)=>({...Y,discoveryState:X}))},discoveryState:()=>W.discoveryState},getLastAuthorizationUrl:()=>Z,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await J((X)=>({...X,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(X)=>{await J((Y)=>({...Y,lastError:X}))},clearError:async()=>{await J((X)=>({...X,lastError:void 0}))}}}function HQ($){let W=$.registration.transport;if(W.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Z=W.headers?{headers:W.headers}:void 0;if(W.type==="sse")return new HP(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch});return new GP(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch})}function QA($){return new BP({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function KQ($){let W=$.serverName.trim();if(!W)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Z}=await Promise.resolve().then(() => (BQ(),ZA)),Q=Z({filePath:$.filePath}).find((V)=>V.name===W);if(!Q)throw Error(`MCP server "${W}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${W}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${W}" uses stdio transport and does not support OAuth browser flow.`);let J=await H1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:FP,callbackPath:$.callbackPath??KP,timeoutMs:$.timeoutMs??AP,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!J.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let j=GQ({settingsPath:$.filePath,serverName:W,redirectUrl:J.callbackUrl,onAuthorizationUrl:async(V)=>{await $.openUrl?.(V)}});await j.resetInteractiveState();let X=QA($),Y;try{let V=HQ({registration:Q,oauthProvider:j.provider,fetch:$.fetch});try{return await X.connect(V),await X.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" is already authorized.`}}catch(B){if(!(B instanceof VP))throw B;if(!j.getLastAuthorizationUrl())throw Error(`MCP server "${W}" did not provide an authorization URL.`);let G=await J.waitForCallback();if(!G)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(G.error)throw Error(`OAuth authorization failed: ${G.error}`);if(!G.code)throw Error("OAuth callback did not include an authorization code.");let K=j.getLastOAuthState();if(!K)throw Error(`MCP server "${W}" did not start an OAuth stateful authorization flow.`);if(G.state!==K)throw Error("OAuth authorization failed: state mismatch.");await V.finishAuth(G.code),Y=QA($);let F=HQ({registration:Q,oauthProvider:j.provider,fetch:$.fetch});return await Y.connect(F),await Y.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" OAuth authorization completed.`}}}catch(V){let B=UP(V);throw await j.markError(B),Error(B)}finally{await X.close().catch(()=>{return}),await Y?.close().catch(()=>{return}),J.close()}}var LP="2024-11-05",TP=5000,OP=1500,jA="http://127.0.0.1:1456/mcp/oauth/callback";function FQ($){return $ instanceof Error?$.message:String($)}function XA($){let W=Buffer.from(JSON.stringify($),"utf8"),Z=Buffer.from(`Content-Length: ${W.byteLength}\r
495
495
  \r
496
- `,"utf8");return Buffer.concat([Z,W])}function XA($){return Buffer.from(`${JSON.stringify($)}
497
- `,"utf8")}class Kj{buffer="";decoder=new YA("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`\r
496
+ `,"utf8");return Buffer.concat([Z,W])}function YA($){return Buffer.from(`${JSON.stringify($)}
497
+ `,"utf8")}class Fj{buffer="";decoder=new VA("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`\r
498
498
  \r
499
- `);if(Z<0)break;let J=this.buffer.slice(0,Z).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!J)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let j=Number.parseInt(J[1],10),X=Z+4,Y=X+j;if(this.buffer.length<Y)break;W.push(this.buffer.slice(X,Y)),this.buffer=this.buffer.slice(Y)}return W}}class Fj{buffer="";decoder=new YA("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`
500
- `);if(Z<0)break;let Q=this.buffer.slice(0,Z).trim();if(this.buffer=this.buffer.slice(Z+1),Q.length>0)W.push(Q)}return W}}class VA{registration;process;nextRequestId=1;pending=new Map;framedParser=new Kj;newlineParser=new Fj;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],W;for(let Z of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Z);try{await this.request("initialize",{protocolVersion:fP,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},TP),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Z;return}catch(Q){W=Q instanceof Error?Q:Error(String(Q))}}throw W??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((W)=>typeof W?.name==="string"&&typeof W.inputSchema==="object"&&W.inputSchema!==null).map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let W=this.registration.transport;if(W.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${W.type}`);this.framedParser=new Kj,this.newlineParser=new Fj,this.stderrBuffer="",this.protocolMode=$;let Z=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=DP(W.command,W.args??[],{cwd:W.cwd,env:{...process.env,...W.env??{}},stdio:["pipe","pipe","pipe"],...Z});this.process=Q,Q.stdout.on("data",(J)=>this.handleStdout(J)),Q.stderr.on("data",(J)=>{if(this.process!==Q)return;if(this.stderrBuffer+=J.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(J)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${KQ(J)}`))}),Q.once("exit",(J,j)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let X=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${J??"null"}, signal=${j??"null"}).${X}`))})}handleStdout($){try{let W=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Z of W){let Q=JSON.parse(Z);if(typeof Q.id!=="number")continue;let J=this.pending.get(Q.id);if(!J)continue;if(this.pending.delete(Q.id),clearTimeout(J.timeout),Q.error){let j=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;J.reject(Error(j));continue}J.resolve(Q.result)}}catch(W){this.handleProtocolFailure(W)}}handleProtocolFailure($){let W=this.process;if(!W)return;this.connected=!1,this.process=void 0;let Z=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${KQ($)}.${Z}`)),W.kill()}async request($,W,Z=LP){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let J=this.nextRequestId++,j={jsonrpc:"2.0",id:J,method:$,...W?{params:W}:{}},X=new Promise((Y,V)=>{let B=setTimeout(()=>{this.pending.delete(J),V(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Z);this.pending.set(J,{resolve:Y,reject:V,timeout:B})});try{Q.stdin.write(this.protocolMode==="framed"?jA(j):XA(j))}catch(Y){let V=this.pending.get(J);if(V)clearTimeout(V.timeout),this.pending.delete(J);throw Y}return X}notify($,W){let Z=this.process;if(!Z?.stdin.writable)return;let Q={jsonrpc:"2.0",method:$,...W?{params:W}:{}};Z.stdin.write(this.protocolMode==="framed"?jA(Q):XA(Q))}failAllPending($){for(let[W,Z]of this.pending)clearTimeout(Z.timeout),this.pending.delete(W),Z.reject($)}}class BA{registration;options;client;authContext;constructor($,W){this.registration=$;this.options=W}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=HQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??JA});this.authContext=$;try{let W=new _P({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Z=BQ({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await W.connect(Z),await $.clearError(),this.client=W}catch(W){let Z=W instanceof QA?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):KQ(W);throw await $.markError(Z),Error(Z)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema&&typeof Z.inputSchema==="object"&&!Array.isArray(Z.inputSchema)?Z.inputSchema:{}}))}catch(W){return await this.handleOperationError(W)}}async callTool($){let W=await this.ensureConnectedClient();try{return await W.callTool({name:$.name,arguments:$.arguments??{}})}catch(Z){return await this.handleOperationError(Z)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let W=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${W} Run authorizeMcpServerOAuth for this server.`;return`${W} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let W=this.authContext??HQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??JA}),Z=$ instanceof QA?this.formatUnauthorizedMessage(W.getLastAuthorizationUrl()):KQ($);throw await W.markError(Z),Error(Z)}}function z6($={}){return(W)=>W.transport.type==="stdio"?new VA(W):new BA(W,$)}VQ();function e0(){return Date.now()}function OP($){return $.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}class a2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let W=this.servers.get($.name);if(!W){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:e0()});return}let Z=JSON.stringify(W.registration.transport)!==JSON.stringify($.transport);if(W.registration={...$},W.updatedAt=e0(),Z)await this.disconnectState(W),W.client=void 0,W.toolCache=void 0,W.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.connectState(W)})}async disconnectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W)})}async setServerDisabled($,W){await this.runExclusive($,async()=>{let Z=this.requireServer($);if(Z.registration={...Z.registration,disabled:W},Z.updatedAt=e0(),W)await this.disconnectState(Z)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,W)=>$.name.localeCompare(W.name))}async listTools($){let W=this.requireServer($),Z=W.toolCacheUpdatedAt??0;if(W.toolCache&&e0()-Z<=this.toolsCacheTtlMs)return W.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let W=this.requireServer($),Q=await(await this.ensureConnectedClient(W)).listTools(),J=OP(Q);return W.toolCache=J,W.toolCacheUpdatedAt=e0(),W.updatedAt=e0(),J})}async callTool($){return this.runExclusive($.serverName,async()=>{let W=this.requireServer($.serverName),Z=await this.ensureConnectedClient(W);return W.updatedAt=e0(),Z.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let W of $)await this.unregisterServer(W)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=e0();try{let W=$.client??await this.clientFactory($.registration);await W.connect(),$.client=W,$.status="connected",$.lastError=void 0,$.updatedAt=e0()}catch(W){throw $.status="disconnected",$.lastError=W instanceof Error?W.message:String(W),$.updatedAt=e0(),W}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=e0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=e0()}}requireServer($){let W=this.servers.get($);if(!W)throw Error(`Unknown MCP server: ${$}`);return W}async runExclusive($,W){let Z=this.operationLocks.get($)??Promise.resolve(),Q,J=new Promise((X)=>{Q=X}),j=Z.catch(()=>{return}).then(()=>J);this.operationLocks.set($,j),await Z.catch(()=>{return});try{return await W()}finally{if(Q?.(),this.operationLocks.get($)===j)this.operationLocks.delete($)}}}function q6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function HA($){return q6($)&&Object.values($).every((W)=>typeof W==="string")}function zP($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function qP($){if(!q6($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function MP($){let W=$.env?Object.entries($.env):[];if(W.length===0)return{ok:!0};let Z={};for(let[Q,J]of W){if(typeof J==="string"){Z[Q]=J;continue}let j=J.fromEnv?.trim()||Q,X=process.env[j];if(typeof X==="string"&&X.length>0){Z[Q]=X;continue}if(typeof J.value==="string"){Z[Q]=J.value;continue}if(J.required===!0)return{ok:!1,reason:`required environment variable "${j}" is not set`}}return{ok:!0,env:Object.keys(Z).length>0?Z:void 0}}function Aj($){if(!q6($))return{name:"",loadError:"invalid MCP server registration"};let W=typeof $.name==="string"?$.name.trim():"";if(!W)return{name:W,loadError:"empty MCP server name"};let Z=$.env,Q=Z===void 0?void 0:Z;if(Q!==void 0){if(!q6(Q))return{name:W,loadError:"invalid env"};for(let[V,B]of Object.entries(Q))if(typeof B!=="string"&&!qP(B))return{name:W,loadError:`invalid env "${V}"`}}let J=$.transport;if(!q6(J))return{name:W,loadError:"invalid MCP transport"};let j=J.type;if(j!=="stdio"&&j!=="sse"&&j!=="streamableHttp")return{name:W,loadError:"invalid MCP transport type"};if(j!=="stdio"&&Q!==void 0)return{name:W,loadError:"top-level env is only supported for stdio MCP transports"};let X=q6($.metadata)?$.metadata:void 0;if(j==="stdio"){let V=J.command;if(typeof V!=="string"||!V.trim())return{name:W,loadError:"stdio MCP transport requires command"};let B=J.args;if(B!==void 0&&!zP(B))return{name:W,loadError:"stdio MCP transport args must be strings"};let H=J.cwd;if(H!==void 0&&typeof H!=="string")return{name:W,loadError:"stdio MCP transport cwd must be a string"};let G=J.env;if(G!==void 0&&!HA(G))return{name:W,loadError:"stdio MCP transport env must be strings"};let K=MP({name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:G},env:Q,metadata:X});if(!K.ok)return{name:W,loadError:K.reason};let F=G||K.env?{...G??{},...K.env??{}}:void 0;return{name:W,registration:{name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:F},metadata:X}}}if(typeof J.url!=="string"||!J.url.trim())return{name:W,loadError:`${j} MCP transport requires url`};let Y=J.headers;if(Y!==void 0&&!HA(Y))return{name:W,loadError:`${j} MCP transport headers must be strings`};return{name:W,registration:{name:W,transport:j==="sse"?{type:"sse",url:J.url,headers:Y}:{type:"streamableHttp",url:J.url,headers:Y},metadata:X}}}function FQ($){let W=new Map;return $.map(({server:Z,owner:Q,ownerLabel:J})=>{let j=Aj(Z);if(!j.registration)return{owner:Q,name:j.name,loadError:j.loadError??"invalid MCP server registration"};let X=W.get(j.registration.name);if(W.has(j.registration.name)){let Y=X?` already registered by ${X}`:"";return{owner:Q,name:j.registration.name,loadError:`duplicate MCP server name "${j.registration.name}"${Y}`}}return W.set(j.registration.name,J),{owner:Q,name:j.registration.name,registration:j.registration}})}import{createHash as RP}from"node:crypto";var GA=64,EP=/[^a-zA-Z0-9_-]+/g,KA=8,NP=1,wP="mcp_tool";function CP($){return RP("sha1").update($).digest("hex").slice(0,KA)}function PP($){return $.replace(EP,"_")}var AQ=({serverName:$,toolName:W})=>{let Z=`${$}__${W}`,Q=PP(Z);if(Q===Z&&Z.length<=GA)return Z;let J=CP(Z),j=GA-NP-KA;return`${Q.slice(0,j)||wP}_${J}`};function a5($){return{[($.nameTransform??AQ)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function UQ($){let W={};for(let Z of $.toolNames)Object.assign(W,a5({serverName:$.serverName,toolName:Z,nameTransform:$.nameTransform}));return W}import{createTool as SP}from"@cline/shared";function bP($,W){let Z=W.description?.trim();if(Z)return Z;return`Execute MCP tool "${W.name}" from server "${$}".`}async function M6($){let W=await $.provider.listTools($.serverName),Z=$.nameTransform??AQ;return W.map((Q)=>{let J=Z({serverName:$.serverName,toolName:Q.name});return SP({name:J,description:bP($.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(j,X)=>$.provider.callTool({serverName:$.serverName,toolName:Q.name,arguments:j&&typeof j==="object"&&!Array.isArray(j)?j:void 0,context:X})})})}X1();var DA={};w(DA,{listPluginToolsWithDiagnostics:()=>DQ,listPluginTools:()=>o5});import{stat as yP}from"node:fs/promises";import{isAbsolute as hP,relative as kP,resolve as AA}from"node:path";X1();function IP($,W){let Z=kP(AA($),AA(W));return Z===""||!Z.startsWith("..")&&!hP(Z)}var xP=32,R6=new Map;function gP($,W){if(!R6.has($)&&R6.size>=xP){let Z=R6.keys().next().value;if(Z)R6.delete(Z)}R6.set($,W)}async function mP($){let W=await Promise.all($.pluginPaths.map(async(Z)=>{try{let Q=await yP(Z);return`${Z}:${Q.mtimeMs}:${Q.size}`}catch{return`${Z}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:W})}function UA($,W){return $.map((Z)=>({...Z,enabled:!W.has(Z.name)}))}function vP($){return $.sort((W,Z)=>{let Q=W.name.localeCompare(Z.name);if(Q!==0)return Q;return W.path.localeCompare(Z.path)})}async function cP($,W){if(!$.setup)return{tools:[]};let Z=[],Q={registerTool:(J)=>Z.push(J),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(J)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(Q,{workspaceInfo:W}),{tools:Z}}async function DQ($){let W=Q$({workspacePath:$.workspacePath,cwd:$.cwd}),Z=L1($.disabledToolNames);if(W.length===0)return{tools:[],failures:[],warnings:[]};let Q=await mP({pluginPaths:W,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),J=R6.get(Q);if(J)return{tools:UA(J.tools,Z),failures:J.failures,warnings:J.warnings};let j=[],X=[],Y=[],V;try{V=await j6({pluginPaths:W,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),X=[...V.failures],Y=[...V.warnings];for(let H of V.extensions??[]){let G=H.__clinePluginPath;if(!G)continue;let K=IP($.workspacePath,G)?"workspace-plugin":"global-plugin",F;try{F=await cP(H,{rootPath:$.workspacePath})}catch(A){X.push({pluginPath:G,pluginName:H.name,phase:"setup",message:A instanceof Error?A.message:String(A),stack:A instanceof Error?A.stack:void 0});continue}for(let A of F.tools)j.push({name:A.name,pluginName:H.name,path:G,source:K,description:A.description?.trim()||void 0})}}catch(H){X=W.map((G)=>({pluginPath:G,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await V?.shutdown().catch(()=>{})}let B=vP(j);return gP(Q,{tools:B,failures:X,warnings:Y}),{tools:UA(B,Z),failures:X,warnings:Y}}async function o5($){return(await DQ($)).tools}function e5($,W){if(!W)return"global";let Z=OA(W,$);return!Z.startsWith("..")&&!TA(Z)?"workspace":"global"}function pP($,W){return e5($,W)==="workspace"?"workspace-plugin":"global-plugin"}function rP($,W){let Z=OA(fA($),fA(W));return Z===""||!Z.startsWith("..")&&!TA(Z)}function iP($){try{let W=JSON.parse(uP($,"utf8"));return typeof W.name==="string"&&W.name.trim()?W.name.trim():void 0}catch{return}}function nP($){let W=_A($);while(!0){let Z=lP(W,"package.json");if(t5(Z)){let J=iP(Z);if(J)return J;break}let Q=_A(W);if(Q===W)break;W=Q}return Uj($,dP($))}function aP($){let W=[];for(let Z of Q$({workspacePath:$.workspaceRoot||void 0,cwd:$.cwd}))for(let Q of J$([Z]))W.push({directory:Q,pluginName:nP(Z),pluginPath:Z,source:$.workspaceRoot?pP(Z,$.workspaceRoot):"global-plugin"});return W.sort((Z,Q)=>Q.directory.length-Z.directory.length)}function oP($,W){return W.find((Z)=>rP(Z.directory,$))}function s5($){return[...$].sort((W,Z)=>{let Q=(J)=>{switch(J){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(W.source!==Z.source)return Q(W.source)-Q(Z.source);return W.name.localeCompare(Z.name)})}function zA($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}function qA($,W){return $.cwd?.trim()||W||process.cwd()}async function LA($,W){if($.userInstructionService)return await W($.userInstructionService);let Z=zA($),Q=qA($,Z),J=c$({skills:{workspacePath:Z||void 0,includePluginSkills:!0,cwd:Q},rules:{workspacePath:Z||void 0},workflows:{workspacePath:Z||void 0}});try{return await J.start(),await W(J)}finally{J.stop()}}function sP($,W){if(!$)return;let Z=$.listRecords("skill");if(W.id){let Q=Z.find((J)=>J.id===W.id);if(Q)return Q}for(let Q of Z)if(Q.filePath===W.path||Q.item.name===W.name||Q.id===W.name)return Q;return}class l${async list($={}){return await LA($,async(W)=>{let Z=zA($),Q=aP({workspaceRoot:Z,cwd:qA($,Z)}),J=[],j=[],X=[],Y=[],V=[];if(W){for(let H of W.listRecords("workflow")){let G=H.item;J.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"workflow",source:e5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("rule")){let G=H.item;j.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"rule",source:e5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("skill")){let G=H.item,K=oP(H.filePath,Q);X.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"skill",source:K?.source??e5(H.filePath,Z),description:G.description,pluginName:K?.pluginName,pluginPath:K?.pluginPath,toggleable:!0})}}if(Z)try{for(let H of await o5({workspacePath:Z,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))Y.push({id:`${H.pluginName}:${H.name}:${H.path}`,name:H.name,path:H.path,enabled:H.enabled,kind:"tool",source:H.source,description:H.description,toggleable:!0})}catch{}let B=J0();if(X$({filePath:B}))try{for(let H of t0({filePath:B}))V.push({id:H.name,name:H.name,path:B,enabled:H.disabled!==!0,kind:"mcp",source:e5(B,Z),description:H.transport.type,toggleable:!0})}catch{}return{workflows:s5(J.filter((H)=>t5(H.path))),rules:s5(j.filter((H)=>t5(H.path))),skills:s5(X.filter((H)=>t5(H.path))),tools:s5(Y),mcp:s5(V.filter((H)=>t5(H.path)))}})}async toggle($){if($.type==="skills")return await LA($,async(W)=>{let Z=sP(W,$),Q=Z?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${$.id??$.name??Uj($.path??"")}'.`);let J=Z?.item&&"disabled"in Z.item?Z.item.disabled!==!0:void 0,j=$.enabled??(J!==void 0?!J:void 0);if(j===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??Uj($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await gF({filePath:Q,enabled:j}),await W?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:W}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)UW($.name);else kV($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let W=$.name?.trim()||$.id?.trim();if(!W)throw Error("MCP server settings toggle requires a server name.");let Z=$.path?.trim()||J0(),Q=$.enabled;if(Q===void 0){let J=t0({filePath:Z}).find((j)=>j.name===W);if(!J)throw Error(`Unknown MCP server: ${W}`);Q=J.disabled===!0}return p2({filePath:Z,name:W,disabled:!Q}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function o2(){return new l$}function RA($){return{async list(W){let Z=$;if(Z.listSettings)return await Z.listSettings(W);return await o2().list(W)},async toggle(W){let Z=$;if(Z.toggleSetting)return await Z.toggleSetting(W);return await o2().toggle(W)}}}function EA($){function W(){let Z=$.pendingPrompts;if(!Z)throw Error("Pending prompt service is not available.");return Z}return{list(Z){return W().list(Z)},update(Z){return W().update(Z)},delete(Z){return W().delete(Z)}}}function NA($){let W=$.config;return"providerId"in W?{...$,config:{...W,...tP($.localRuntime)},localRuntime:$.localRuntime}:$}function Dj($,W={}){let Z=D4($.config),Q=P0(W.defaultCapabilities,$.capabilities),J=eP(Z.localRuntime,$.localRuntime),j=W.withExtensionContext?.(J?.extensionContext);if(j)J={...J??{},extensionContext:j};return{...$,...Z,...J?{localRuntime:J}:{},...Q?{capabilities:Q}:{}}}function tP($){if(!$)return{};let{modelCatalogDefaults:W,userInstructionService:Z,configExtensions:Q,onTeamRestored:J,...j}=$;return j}function eP(...$){let W={};for(let Z of $)if(Z)Object.assign(W,Z);return Object.keys(W).length>0?W:void 0}R0();function wA($){let W=$.input.config.telemetry??$.telemetry;if(!W)return;W.capture({event:v.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??F0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function $9($){return!!$&&typeof $==="object"&&!Array.isArray($)}function _j($){let W=$?.trim();return W?W:void 0}function $S($,W){let Z=$?.trim();if(!Z)return W;let Q=Date.parse(Z);if(!Number.isFinite(Q))return W;return new Date(Q).toISOString()}function CA($,W){return new Date(new Date($).getTime()+Math.max(0,Math.floor(W))*1000).toISOString()}function PA($,W){return new Date(new Date($).getTime()-Math.max(0,Math.floor(W))*1000).toISOString()}function WS($,W){if(!$)return W;return new Date($).getTime()>=new Date(W).getTime()?$:W}function ZS($,W){let Z=$.eventId.trim(),Q=$.eventType.trim(),J=$.source.trim(),j=_j($.subject),X=_j($.dedupeKey)??`${Q}:${J}:${j??Z}`;return{eventId:Z,eventType:Q,source:J,subject:j,occurredAt:$S($.occurredAt,W),workspaceRoot:_j($.workspaceRoot),payload:$9($.payload)?$.payload:void 0,attributes:$9($.attributes)?$.attributes:void 0,dedupeKey:X}}function fj($,W){if(!W)return;let Z=W.split("."),Q=$;for(let J of Z){if(!$9(Q))return;Q=Q[J]}return Q}function QS($,W){if($.attributes&&Object.hasOwn($.attributes,W))return $.attributes[W];if($.payload&&Object.hasOwn($.payload,W))return $.payload[W];let Z={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Q=fj(Z,W);if(Q!==void 0)return Q;if($.attributes){let J=fj($.attributes,W);if(J!==void 0)return J}if($.payload)return fj($.payload,W);return}function _Q($,W){if(Array.isArray(W))return W.some((Z)=>_Q($,Z));if(Array.isArray($))return $.some((Z)=>_Q(Z,W));if($9(W)){if(!$9($))return!1;return Object.entries(W).every(([Z,Q])=>_Q($[Z],Q))}return Object.is($,W)}function JS($,W){if(!W||Object.keys(W).length===0)return!0;return Object.entries(W).every(([Z,Q])=>_Q(QS($,Z),Q))}class Lj{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let W=new Date(this.nowFn()).toISOString(),Z=ZS($,W),Q=this.store.insertEventLog(Z,{receivedAtIso:W});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let J=this.store.listEventSpecsForType(Z.eventType),j=[],X=[],Y=[];for(let H of J){if(!JS(Z,H.filters)){j.push({specId:H.specId,externalId:H.externalId,reason:"filter_mismatch",dedupeKey:Z.dedupeKey});continue}X.push(H);let G=this.materializeForSpec(H,Z,Q.record.receivedAt);if(G.run)Y.push(G.run);else j.push({specId:H.specId,externalId:H.externalId,reason:G.reason,dedupeKey:Z.dedupeKey})}let V=X.length===0?"unmatched":Y.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:V,matchedSpecCount:X.length,queuedRunCount:Y.length,suppressedCount:j.filter((H)=>H.reason!=="filter_mismatch").length});let B=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:V,matchedSpecCount:X.length,queuedRunCount:Y.length}),{event:B??Q.record,duplicate:!1,matchedSpecs:X,queuedRuns:Y,suppressions:j}}catch(J){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:J instanceof Error?J.message:String(J)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:J});throw J}}materializeForSpec($,W,Z){let Q=W.dedupeKey??W.eventId,J=$.debounceSeconds??0;if(J>0){let V=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Q});if(V){let B=WS(V.scheduledFor,CA(Z,J)),H=this.store.updateQueuedEventRunForDebounce({runId:V.runId,triggerEventId:W.eventId,scheduledFor:B});if(H)return{run:H,reason:"dedupe_window"}}}let j=$.dedupeWindowSeconds??0;if(j>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Q,sinceIso:PA(Z,j)}))return{reason:"dedupe_window"};let X=$.cooldownSeconds??0;if(X>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:PA(Z,X)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:W.eventId,scheduledFor:J>0?CA(Z,J):Z}),reason:"dedupe_window"}}}import{existsSync as TS,readdirSync as OS,readFileSync as zS,statSync as qS}from"node:fs";import{relative as MS}from"node:path";import{resolveCronSpecsDir as RS}from"@cline/shared/storage";import{createHash as jS}from"node:crypto";import XS from"yaml";function YS($){let W=$.replace(/\\/g,"/");if(W.startsWith("events/")&&W.endsWith(".event.md"))return"event";if(W.endsWith(".cron.md"))return"schedule";return"one_off"}function VS($){let W=$.replace(/\r\n/g,`
499
+ `);if(Z<0)break;let J=this.buffer.slice(0,Z).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!J)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let j=Number.parseInt(J[1],10),X=Z+4,Y=X+j;if(this.buffer.length<Y)break;W.push(this.buffer.slice(X,Y)),this.buffer=this.buffer.slice(Y)}return W}}class Aj{buffer="";decoder=new VA("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`
500
+ `);if(Z<0)break;let Q=this.buffer.slice(0,Z).trim();if(this.buffer=this.buffer.slice(Z+1),Q.length>0)W.push(Q)}return W}}class BA{registration;process;nextRequestId=1;pending=new Map;framedParser=new Fj;newlineParser=new Aj;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],W;for(let Z of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Z);try{await this.request("initialize",{protocolVersion:LP,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},OP),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Z;return}catch(Q){W=Q instanceof Error?Q:Error(String(Q))}}throw W??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((W)=>typeof W?.name==="string"&&typeof W.inputSchema==="object"&&W.inputSchema!==null).map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let W=this.registration.transport;if(W.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${W.type}`);this.framedParser=new Fj,this.newlineParser=new Aj,this.stderrBuffer="",this.protocolMode=$;let Z=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=_P(W.command,W.args??[],{cwd:W.cwd,env:{...process.env,...W.env??{}},stdio:["pipe","pipe","pipe"],...Z});this.process=Q,Q.stdout.on("data",(J)=>this.handleStdout(J)),Q.stderr.on("data",(J)=>{if(this.process!==Q)return;if(this.stderrBuffer+=J.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(J)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${FQ(J)}`))}),Q.once("exit",(J,j)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let X=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${J??"null"}, signal=${j??"null"}).${X}`))})}handleStdout($){try{let W=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Z of W){let Q=JSON.parse(Z);if(typeof Q.id!=="number")continue;let J=this.pending.get(Q.id);if(!J)continue;if(this.pending.delete(Q.id),clearTimeout(J.timeout),Q.error){let j=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;J.reject(Error(j));continue}J.resolve(Q.result)}}catch(W){this.handleProtocolFailure(W)}}handleProtocolFailure($){let W=this.process;if(!W)return;this.connected=!1,this.process=void 0;let Z=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${FQ($)}.${Z}`)),W.kill()}async request($,W,Z=TP){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let J=this.nextRequestId++,j={jsonrpc:"2.0",id:J,method:$,...W?{params:W}:{}},X=new Promise((Y,V)=>{let B=setTimeout(()=>{this.pending.delete(J),V(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Z);this.pending.set(J,{resolve:Y,reject:V,timeout:B})});try{Q.stdin.write(this.protocolMode==="framed"?XA(j):YA(j))}catch(Y){let V=this.pending.get(J);if(V)clearTimeout(V.timeout),this.pending.delete(J);throw Y}return X}notify($,W){let Z=this.process;if(!Z?.stdin.writable)return;let Q={jsonrpc:"2.0",method:$,...W?{params:W}:{}};Z.stdin.write(this.protocolMode==="framed"?XA(Q):YA(Q))}failAllPending($){for(let[W,Z]of this.pending)clearTimeout(Z.timeout),this.pending.delete(W),Z.reject($)}}class HA{registration;options;client;authContext;constructor($,W){this.registration=$;this.options=W}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=GQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??jA});this.authContext=$;try{let W=new fP({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Z=HQ({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await W.connect(Z),await $.clearError(),this.client=W}catch(W){let Z=W instanceof JA?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):FQ(W);throw await $.markError(Z),Error(Z)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema&&typeof Z.inputSchema==="object"&&!Array.isArray(Z.inputSchema)?Z.inputSchema:{}}))}catch(W){return await this.handleOperationError(W)}}async callTool($){let W=await this.ensureConnectedClient();try{return await W.callTool({name:$.name,arguments:$.arguments??{}})}catch(Z){return await this.handleOperationError(Z)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let W=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${W} Run authorizeMcpServerOAuth for this server.`;return`${W} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let W=this.authContext??GQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??jA}),Z=$ instanceof JA?this.formatUnauthorizedMessage(W.getLastAuthorizationUrl()):FQ($);throw await W.markError(Z),Error(Z)}}function z6($={}){return(W)=>W.transport.type==="stdio"?new BA(W):new HA(W,$)}BQ();function e0(){return Date.now()}function zP($){return $.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}class a2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let W=this.servers.get($.name);if(!W){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:e0()});return}let Z=JSON.stringify(W.registration.transport)!==JSON.stringify($.transport);if(W.registration={...$},W.updatedAt=e0(),Z)await this.disconnectState(W),W.client=void 0,W.toolCache=void 0,W.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.connectState(W)})}async disconnectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W)})}async setServerDisabled($,W){await this.runExclusive($,async()=>{let Z=this.requireServer($);if(Z.registration={...Z.registration,disabled:W},Z.updatedAt=e0(),W)await this.disconnectState(Z)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,W)=>$.name.localeCompare(W.name))}async listTools($){let W=this.requireServer($),Z=W.toolCacheUpdatedAt??0;if(W.toolCache&&e0()-Z<=this.toolsCacheTtlMs)return W.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let W=this.requireServer($),Q=await(await this.ensureConnectedClient(W)).listTools(),J=zP(Q);return W.toolCache=J,W.toolCacheUpdatedAt=e0(),W.updatedAt=e0(),J})}async callTool($){return this.runExclusive($.serverName,async()=>{let W=this.requireServer($.serverName),Z=await this.ensureConnectedClient(W);return W.updatedAt=e0(),Z.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let W of $)await this.unregisterServer(W)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=e0();try{let W=$.client??await this.clientFactory($.registration);await W.connect(),$.client=W,$.status="connected",$.lastError=void 0,$.updatedAt=e0()}catch(W){throw $.status="disconnected",$.lastError=W instanceof Error?W.message:String(W),$.updatedAt=e0(),W}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=e0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=e0()}}requireServer($){let W=this.servers.get($);if(!W)throw Error(`Unknown MCP server: ${$}`);return W}async runExclusive($,W){let Z=this.operationLocks.get($)??Promise.resolve(),Q,J=new Promise((X)=>{Q=X}),j=Z.catch(()=>{return}).then(()=>J);this.operationLocks.set($,j),await Z.catch(()=>{return});try{return await W()}finally{if(Q?.(),this.operationLocks.get($)===j)this.operationLocks.delete($)}}}function q6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function GA($){return q6($)&&Object.values($).every((W)=>typeof W==="string")}function qP($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function MP($){if(!q6($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function RP($){let W=$.env?Object.entries($.env):[];if(W.length===0)return{ok:!0};let Z={};for(let[Q,J]of W){if(typeof J==="string"){Z[Q]=J;continue}let j=J.fromEnv?.trim()||Q,X=process.env[j];if(typeof X==="string"&&X.length>0){Z[Q]=X;continue}if(typeof J.value==="string"){Z[Q]=J.value;continue}if(J.required===!0)return{ok:!1,reason:`required environment variable "${j}" is not set`}}return{ok:!0,env:Object.keys(Z).length>0?Z:void 0}}function Uj($){if(!q6($))return{name:"",loadError:"invalid MCP server registration"};let W=typeof $.name==="string"?$.name.trim():"";if(!W)return{name:W,loadError:"empty MCP server name"};let Z=$.env,Q=Z===void 0?void 0:Z;if(Q!==void 0){if(!q6(Q))return{name:W,loadError:"invalid env"};for(let[V,B]of Object.entries(Q))if(typeof B!=="string"&&!MP(B))return{name:W,loadError:`invalid env "${V}"`}}let J=$.transport;if(!q6(J))return{name:W,loadError:"invalid MCP transport"};let j=J.type;if(j!=="stdio"&&j!=="sse"&&j!=="streamableHttp")return{name:W,loadError:"invalid MCP transport type"};if(j!=="stdio"&&Q!==void 0)return{name:W,loadError:"top-level env is only supported for stdio MCP transports"};let X=q6($.metadata)?$.metadata:void 0;if(j==="stdio"){let V=J.command;if(typeof V!=="string"||!V.trim())return{name:W,loadError:"stdio MCP transport requires command"};let B=J.args;if(B!==void 0&&!qP(B))return{name:W,loadError:"stdio MCP transport args must be strings"};let H=J.cwd;if(H!==void 0&&typeof H!=="string")return{name:W,loadError:"stdio MCP transport cwd must be a string"};let G=J.env;if(G!==void 0&&!GA(G))return{name:W,loadError:"stdio MCP transport env must be strings"};let K=RP({name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:G},env:Q,metadata:X});if(!K.ok)return{name:W,loadError:K.reason};let F=G||K.env?{...G??{},...K.env??{}}:void 0;return{name:W,registration:{name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:F},metadata:X}}}if(typeof J.url!=="string"||!J.url.trim())return{name:W,loadError:`${j} MCP transport requires url`};let Y=J.headers;if(Y!==void 0&&!GA(Y))return{name:W,loadError:`${j} MCP transport headers must be strings`};return{name:W,registration:{name:W,transport:j==="sse"?{type:"sse",url:J.url,headers:Y}:{type:"streamableHttp",url:J.url,headers:Y},metadata:X}}}function AQ($){let W=new Map;return $.map(({server:Z,owner:Q,ownerLabel:J})=>{let j=Uj(Z);if(!j.registration)return{owner:Q,name:j.name,loadError:j.loadError??"invalid MCP server registration"};let X=W.get(j.registration.name);if(W.has(j.registration.name)){let Y=X?` already registered by ${X}`:"";return{owner:Q,name:j.registration.name,loadError:`duplicate MCP server name "${j.registration.name}"${Y}`}}return W.set(j.registration.name,J),{owner:Q,name:j.registration.name,registration:j.registration}})}import{createHash as EP}from"node:crypto";var KA=64,NP=/[^a-zA-Z0-9_-]+/g,FA=8,wP=1,CP="mcp_tool";function PP($){return EP("sha1").update($).digest("hex").slice(0,FA)}function SP($){return $.replace(NP,"_")}var UQ=({serverName:$,toolName:W})=>{let Z=`${$}__${W}`,Q=SP(Z);if(Q===Z&&Z.length<=KA)return Z;let J=PP(Z),j=KA-wP-FA;return`${Q.slice(0,j)||CP}_${J}`};function a5($){return{[($.nameTransform??UQ)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function DQ($){let W={};for(let Z of $.toolNames)Object.assign(W,a5({serverName:$.serverName,toolName:Z,nameTransform:$.nameTransform}));return W}import{createTool as bP}from"@cline/shared";function yP($,W){let Z=W.description?.trim();if(Z)return Z;return`Execute MCP tool "${W.name}" from server "${$}".`}async function M6($){let W=await $.provider.listTools($.serverName),Z=$.nameTransform??UQ;return W.map((Q)=>{let J=Z({serverName:$.serverName,toolName:Q.name});return bP({name:J,description:yP($.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(j,X)=>$.provider.callTool({serverName:$.serverName,toolName:Q.name,arguments:j&&typeof j==="object"&&!Array.isArray(j)?j:void 0,context:X})})})}X1();var _A={};w(_A,{listPluginToolsWithDiagnostics:()=>_Q,listPluginTools:()=>o5});import{stat as hP}from"node:fs/promises";import{isAbsolute as kP,relative as IP,resolve as UA}from"node:path";X1();function xP($,W){let Z=IP(UA($),UA(W));return Z===""||!Z.startsWith("..")&&!kP(Z)}var gP=32,R6=new Map;function mP($,W){if(!R6.has($)&&R6.size>=gP){let Z=R6.keys().next().value;if(Z)R6.delete(Z)}R6.set($,W)}async function vP($){let W=await Promise.all($.pluginPaths.map(async(Z)=>{try{let Q=await hP(Z);return`${Z}:${Q.mtimeMs}:${Q.size}`}catch{return`${Z}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:W})}function DA($,W){return $.map((Z)=>({...Z,enabled:!W.has(Z.name)}))}function cP($){return $.sort((W,Z)=>{let Q=W.name.localeCompare(Z.name);if(Q!==0)return Q;return W.path.localeCompare(Z.path)})}async function uP($,W){if(!$.setup)return{tools:[]};let Z=[],Q={registerTool:(J)=>Z.push(J),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(J)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(Q,{workspaceInfo:W}),{tools:Z}}async function _Q($){let W=Q$({workspacePath:$.workspacePath,cwd:$.cwd}),Z=L1($.disabledToolNames);if(W.length===0)return{tools:[],failures:[],warnings:[]};let Q=await vP({pluginPaths:W,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),J=R6.get(Q);if(J)return{tools:DA(J.tools,Z),failures:J.failures,warnings:J.warnings};let j=[],X=[],Y=[],V;try{V=await j6({pluginPaths:W,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),X=[...V.failures],Y=[...V.warnings];for(let H of V.extensions??[]){let G=H.__clinePluginPath;if(!G)continue;let K=xP($.workspacePath,G)?"workspace-plugin":"global-plugin",F;try{F=await uP(H,{rootPath:$.workspacePath})}catch(A){X.push({pluginPath:G,pluginName:H.name,phase:"setup",message:A instanceof Error?A.message:String(A),stack:A instanceof Error?A.stack:void 0});continue}for(let A of F.tools)j.push({name:A.name,pluginName:H.name,path:G,source:K,description:A.description?.trim()||void 0})}}catch(H){X=W.map((G)=>({pluginPath:G,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await V?.shutdown().catch(()=>{})}let B=cP(j);return mP(Q,{tools:B,failures:X,warnings:Y}),{tools:DA(B,Z),failures:X,warnings:Y}}async function o5($){return(await _Q($)).tools}function e5($,W){if(!W)return"global";let Z=zA(W,$);return!Z.startsWith("..")&&!OA(Z)?"workspace":"global"}function rP($,W){return e5($,W)==="workspace"?"workspace-plugin":"global-plugin"}function iP($,W){let Z=zA(LA($),LA(W));return Z===""||!Z.startsWith("..")&&!OA(Z)}function nP($){try{let W=JSON.parse(dP($,"utf8"));return typeof W.name==="string"&&W.name.trim()?W.name.trim():void 0}catch{return}}function aP($){let W=fA($);while(!0){let Z=pP(W,"package.json");if(t5(Z)){let J=nP(Z);if(J)return J;break}let Q=fA(W);if(Q===W)break;W=Q}return Dj($,lP($))}function oP($){let W=[];for(let Z of Q$({workspacePath:$.workspaceRoot||void 0,cwd:$.cwd}))for(let Q of J$([Z]))W.push({directory:Q,pluginName:aP(Z),pluginPath:Z,source:$.workspaceRoot?rP(Z,$.workspaceRoot):"global-plugin"});return W.sort((Z,Q)=>Q.directory.length-Z.directory.length)}function sP($,W){return W.find((Z)=>iP(Z.directory,$))}function s5($){return[...$].sort((W,Z)=>{let Q=(J)=>{switch(J){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(W.source!==Z.source)return Q(W.source)-Q(Z.source);return W.name.localeCompare(Z.name)})}function qA($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}function MA($,W){return $.cwd?.trim()||W||process.cwd()}async function TA($,W){if($.userInstructionService)return await W($.userInstructionService);let Z=qA($),Q=MA($,Z),J=c$({skills:{workspacePath:Z||void 0,includePluginSkills:!0,cwd:Q},rules:{workspacePath:Z||void 0},workflows:{workspacePath:Z||void 0}});try{return await J.start(),await W(J)}finally{J.stop()}}function tP($,W){if(!$)return;let Z=$.listRecords("skill");if(W.id){let Q=Z.find((J)=>J.id===W.id);if(Q)return Q}for(let Q of Z)if(Q.filePath===W.path||Q.item.name===W.name||Q.id===W.name)return Q;return}class l${async list($={}){return await TA($,async(W)=>{let Z=qA($),Q=oP({workspaceRoot:Z,cwd:MA($,Z)}),J=[],j=[],X=[],Y=[],V=[];if(W){for(let H of W.listRecords("workflow")){let G=H.item;J.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"workflow",source:e5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("rule")){let G=H.item;j.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"rule",source:e5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("skill")){let G=H.item,K=sP(H.filePath,Q);X.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"skill",source:K?.source??e5(H.filePath,Z),description:G.description,pluginName:K?.pluginName,pluginPath:K?.pluginPath,toggleable:!0})}}if(Z)try{for(let H of await o5({workspacePath:Z,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))Y.push({id:`${H.pluginName}:${H.name}:${H.path}`,name:H.name,path:H.path,enabled:H.enabled,kind:"tool",source:H.source,description:H.description,toggleable:!0})}catch{}let B=J0();if(X$({filePath:B}))try{for(let H of t0({filePath:B}))V.push({id:H.name,name:H.name,path:B,enabled:H.disabled!==!0,kind:"mcp",source:e5(B,Z),description:H.transport.type,toggleable:!0})}catch{}return{workflows:s5(J.filter((H)=>t5(H.path))),rules:s5(j.filter((H)=>t5(H.path))),skills:s5(X.filter((H)=>t5(H.path))),tools:s5(Y),mcp:s5(V.filter((H)=>t5(H.path)))}})}async toggle($){if($.type==="skills")return await TA($,async(W)=>{let Z=tP(W,$),Q=Z?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${$.id??$.name??Dj($.path??"")}'.`);let J=Z?.item&&"disabled"in Z.item?Z.item.disabled!==!0:void 0,j=$.enabled??(J!==void 0?!J:void 0);if(j===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??Dj($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await mF({filePath:Q,enabled:j}),await W?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:W}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)DW($.name);else IV($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let W=$.name?.trim()||$.id?.trim();if(!W)throw Error("MCP server settings toggle requires a server name.");let Z=$.path?.trim()||J0(),Q=$.enabled;if(Q===void 0){let J=t0({filePath:Z}).find((j)=>j.name===W);if(!J)throw Error(`Unknown MCP server: ${W}`);Q=J.disabled===!0}return p2({filePath:Z,name:W,disabled:!Q}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function o2(){return new l$}function EA($){return{async list(W){let Z=$;if(Z.listSettings)return await Z.listSettings(W);return await o2().list(W)},async toggle(W){let Z=$;if(Z.toggleSetting)return await Z.toggleSetting(W);return await o2().toggle(W)}}}function NA($){function W(){let Z=$.pendingPrompts;if(!Z)throw Error("Pending prompt service is not available.");return Z}return{list(Z){return W().list(Z)},update(Z){return W().update(Z)},delete(Z){return W().delete(Z)}}}function wA($){let W=$.config;return"providerId"in W?{...$,config:{...W,...eP($.localRuntime)},localRuntime:$.localRuntime}:$}function _j($,W={}){let Z=D4($.config),Q=P0(W.defaultCapabilities,$.capabilities),J=$S(Z.localRuntime,$.localRuntime),j=W.withExtensionContext?.(J?.extensionContext);if(j)J={...J??{},extensionContext:j};return{...$,...Z,...J?{localRuntime:J}:{},...Q?{capabilities:Q}:{}}}function eP($){if(!$)return{};let{modelCatalogDefaults:W,userInstructionService:Z,configExtensions:Q,onTeamRestored:J,...j}=$;return j}function $S(...$){let W={};for(let Z of $)if(Z)Object.assign(W,Z);return Object.keys(W).length>0?W:void 0}z0();function CA($){let W=$.input.config.telemetry??$.telemetry;if(!W)return;W.capture({event:v.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??F0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function $9($){return!!$&&typeof $==="object"&&!Array.isArray($)}function fj($){let W=$?.trim();return W?W:void 0}function WS($,W){let Z=$?.trim();if(!Z)return W;let Q=Date.parse(Z);if(!Number.isFinite(Q))return W;return new Date(Q).toISOString()}function PA($,W){return new Date(new Date($).getTime()+Math.max(0,Math.floor(W))*1000).toISOString()}function SA($,W){return new Date(new Date($).getTime()-Math.max(0,Math.floor(W))*1000).toISOString()}function ZS($,W){if(!$)return W;return new Date($).getTime()>=new Date(W).getTime()?$:W}function QS($,W){let Z=$.eventId.trim(),Q=$.eventType.trim(),J=$.source.trim(),j=fj($.subject),X=fj($.dedupeKey)??`${Q}:${J}:${j??Z}`;return{eventId:Z,eventType:Q,source:J,subject:j,occurredAt:WS($.occurredAt,W),workspaceRoot:fj($.workspaceRoot),payload:$9($.payload)?$.payload:void 0,attributes:$9($.attributes)?$.attributes:void 0,dedupeKey:X}}function Lj($,W){if(!W)return;let Z=W.split("."),Q=$;for(let J of Z){if(!$9(Q))return;Q=Q[J]}return Q}function JS($,W){if($.attributes&&Object.hasOwn($.attributes,W))return $.attributes[W];if($.payload&&Object.hasOwn($.payload,W))return $.payload[W];let Z={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Q=Lj(Z,W);if(Q!==void 0)return Q;if($.attributes){let J=Lj($.attributes,W);if(J!==void 0)return J}if($.payload)return Lj($.payload,W);return}function fQ($,W){if(Array.isArray(W))return W.some((Z)=>fQ($,Z));if(Array.isArray($))return $.some((Z)=>fQ(Z,W));if($9(W)){if(!$9($))return!1;return Object.entries(W).every(([Z,Q])=>fQ($[Z],Q))}return Object.is($,W)}function jS($,W){if(!W||Object.keys(W).length===0)return!0;return Object.entries(W).every(([Z,Q])=>fQ(JS($,Z),Q))}class Tj{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let W=new Date(this.nowFn()).toISOString(),Z=QS($,W),Q=this.store.insertEventLog(Z,{receivedAtIso:W});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let J=this.store.listEventSpecsForType(Z.eventType),j=[],X=[],Y=[];for(let H of J){if(!jS(Z,H.filters)){j.push({specId:H.specId,externalId:H.externalId,reason:"filter_mismatch",dedupeKey:Z.dedupeKey});continue}X.push(H);let G=this.materializeForSpec(H,Z,Q.record.receivedAt);if(G.run)Y.push(G.run);else j.push({specId:H.specId,externalId:H.externalId,reason:G.reason,dedupeKey:Z.dedupeKey})}let V=X.length===0?"unmatched":Y.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:V,matchedSpecCount:X.length,queuedRunCount:Y.length,suppressedCount:j.filter((H)=>H.reason!=="filter_mismatch").length});let B=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:V,matchedSpecCount:X.length,queuedRunCount:Y.length}),{event:B??Q.record,duplicate:!1,matchedSpecs:X,queuedRuns:Y,suppressions:j}}catch(J){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:J instanceof Error?J.message:String(J)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:J});throw J}}materializeForSpec($,W,Z){let Q=W.dedupeKey??W.eventId,J=$.debounceSeconds??0;if(J>0){let V=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Q});if(V){let B=ZS(V.scheduledFor,PA(Z,J)),H=this.store.updateQueuedEventRunForDebounce({runId:V.runId,triggerEventId:W.eventId,scheduledFor:B});if(H)return{run:H,reason:"dedupe_window"}}}let j=$.dedupeWindowSeconds??0;if(j>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Q,sinceIso:SA(Z,j)}))return{reason:"dedupe_window"};let X=$.cooldownSeconds??0;if(X>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:SA(Z,X)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:W.eventId,scheduledFor:J>0?PA(Z,J):Z}),reason:"dedupe_window"}}}import{existsSync as OS,readdirSync as zS,readFileSync as qS,statSync as MS}from"node:fs";import{relative as RS}from"node:path";import{resolveCronSpecsDir as ES}from"@cline/shared/storage";import{createHash as XS}from"node:crypto";import YS from"yaml";function VS($){let W=$.replace(/\\/g,"/");if(W.startsWith("events/")&&W.endsWith(".event.md"))return"event";if(W.endsWith(".cron.md"))return"schedule";return"one_off"}function BS($){let W=$.replace(/\r\n/g,`
501
501
  `);if(!W.startsWith(`---
502
502
  `))return{frontmatter:void 0,body:$};let Z=W.slice(4),Q=Z.indexOf(`
503
503
  ---`);if(Q===-1)return{frontmatter:void 0,body:$};let J=Z.slice(0,Q),j=Z.slice(Q+4);if(j.startsWith(`
504
- `))j=j.slice(1);return{frontmatter:J,body:j}}function $1($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function BS($){if(!Array.isArray($))return;let W=$.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);return W.length>0?W:void 0}function zj($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function HS($){let W=zj($);if(!W)return;let Z=$1(W.providerId),Q=$1(W.modelId);if(Z===void 0&&Q===void 0)return;return{providerId:Z,modelId:Q}}function GS($){if(typeof $!=="string")return;let W=$.trim().toLowerCase();if(W==="act"||W==="plan"||W==="yolo")return W;return}function bA($,W={}){let Z=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Z)return;let Q=[...new Set(Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0))];if(Array.isArray($)&&W.preserveEmptyArray)return Q;return Q.length>0?Q:void 0}var KS=new Set(D$);function FS($){let W=bA($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!KS.has(Q));if(Z.length>0)throw Error(`unknown tool(s): ${Z.join(", ")}`);return W}var AS=new Set(["rules","skills","plugins"]);function US($){let W=bA($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!AS.has(Q));if(Z.length>0)throw Error(`unknown extension(s): ${Z.join(", ")}`);return W}function Tj($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function Oj($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function qj($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Z)=>qj(Z)).join(",")}]`;let W=Object.entries($).filter(([,Z])=>Z!==void 0);return W.sort(([Z],[Q])=>Z<Q?-1:Z>Q?1:0),`{${W.map(([Z,Q])=>`${JSON.stringify(Z)}:${qj(Q)}`).join(",")}}`}function yA($,W){let Z=jS("sha256");return Z.update(qj($)),Z.update(`
505
- `),Z.update(W),Z.digest("hex")}function DS($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var _S=["schedule","timezone"],fS=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],LS=["cwd"];function SA($,W,Z,Q,J){return{externalId:$,relativePath:$,triggerKind:W,body:Z,contentHash:yA(Q,Z),error:J}}function E1($,W,Z,Q,J,j){return{externalId:$,relativePath:W,triggerKind:Z,body:Q,contentHash:J,error:j}}function hA($){let W=$.relativePath.replace(/\\/g,"/"),Z=YS(W),{frontmatter:Q,body:J}=VS($.raw),j={};if(Q!==void 0&&Q.trim().length>0)try{let _=XS.parse(Q);if(_&&typeof _==="object"&&!Array.isArray(_))j=_;else if(_!==null&&_!==void 0)return SA(W,Z,J,{},"frontmatter must be a YAML mapping")}catch(_){return SA(W,Z,J,{},_ instanceof Error?`failed to parse frontmatter: ${_.message}`:"failed to parse frontmatter")}let X=yA(j,J),Y=$1(j.id),V=Y??W;if(Z!=="schedule"){for(let _ of _S)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is only allowed on *.cron.md specs`)}for(let _ of LS)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Z!=="event"){for(let _ of fS)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is only allowed on .event.md specs`)}let B=$1(j.prompt),H=J.trim(),G=B??(H.length>0?H:void 0);if(!G)return E1(V,W,Z,J,X,"prompt is required (frontmatter `prompt` or markdown body)");let K=$1(j.workspaceRoot);if(!K)return E1(V,W,Z,J,X,"workspaceRoot is required");let F,A;try{F=FS(j.tools),A=US(j.extensions)}catch(_){return E1(V,W,Z,J,X,_ instanceof Error?_.message:String(_))}let D=GS(j.mode);if(j.mode!==void 0&&D===void 0)return E1(V,W,Z,J,X,"mode must be one of: act, plan, yolo");let U={id:Y,title:$1(j.title)??Y??DS(W),prompt:G,workspaceRoot:K,mode:D??"yolo",systemPrompt:$1(j.systemPrompt),modelSelection:HS(j.modelSelection),maxIterations:Tj(j.maxIterations),timeoutSeconds:Tj(j.timeoutSeconds),tools:F,notesDirectory:$1(j.notesDirectory),extensions:A,source:$1(j.source)??"user",tags:BS(j.tags),enabled:typeof j.enabled==="boolean"?j.enabled:!0,metadata:zj(j.metadata)},f;if(Z==="schedule"){let _=$1(j.schedule);if(!_)return E1(V,W,Z,J,X,"schedule is required for *.cron.md specs");let R=$1(j.timezone);try{GV(_,R)}catch(T){return E1(V,W,Z,J,X,T instanceof Error?T.message:String(T))}f={...U,triggerKind:"schedule",schedule:_,timezone:R}}else if(Z==="event"){let _=$1(j.event);if(!_)return E1(V,W,Z,J,X,"event is required for .event.md specs");f={...U,triggerKind:"event",event:_,filters:zj(j.filters),debounceSeconds:Oj(j.debounceSeconds),dedupeWindowSeconds:Oj(j.dedupeWindowSeconds),cooldownSeconds:Oj(j.cooldownSeconds),maxParallel:Tj(j.maxParallel)}}else f={...U,triggerKind:"one_off"};return{externalId:V,relativePath:W,triggerKind:Z,body:J,contentHash:X,spec:f}}function ES($,W){return MS($,W).replace(/\\/g,"/")}function NS($){if(!TS($))return[];let W=[],Z=[$];while(Z.length>0){let Q=Z.pop();if(!Q)continue;let J;try{J=OS(Q,{withFileTypes:!0})}catch{continue}for(let j of J){let X=`${Q}/${j.name}`;if(j.isDirectory()){if(j.name==="reports")continue;Z.push(X);continue}if(!j.isFile())continue;if(!j.name.endsWith(".md"))continue;W.push(X)}}return W}class Mj{store;cronDir;constructor($){this.store=$.store,this.cronDir=RS($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},W=NS(this.cronDir),Z=new Set;for(let J of W){let j=ES(this.cronDir,J);Z.add(j),$.scanned+=1;let X=await this.reconcileFile(j,J);if(X){if($.changes.push(X),$.upserted+=1,X.parse.error)$.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let J of Q)if(!Z.has(J.sourcePath))this.handleFileDeleted(J),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,W){let Z=this.store.getSpecBySourcePath($),Q,J;try{Q=zS(W,"utf8"),J=qS(W).mtimeMs}catch{return}let X=hA({relativePath:$,raw:Q}),Y=this.store.upsertSpec({externalId:X.externalId,sourcePath:$,triggerKind:X.triggerKind,sourceMtimeMs:J,sourceHash:X.contentHash,parseStatus:X.error?"invalid":"valid",parseError:X.error,spec:X.spec});if(!X.error&&X.triggerKind==="schedule"&&Y.record.enabled)this.applyScheduleNextRunAt(Y.record,{forceReset:!Z||Z.removed||!Z.enabled||Z.scheduleExpr!==Y.record.scheduleExpr||Z.timezone!==Y.record.timezone});return{relativePath:$,result:Y,parse:X}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of $)this.applyScheduleNextRunAt(W,{forceReset:!1})}applyScheduleNextRunAt($,W){if(!$.scheduleExpr)return;if(!W.forceReset&&$.nextRunAt)return;try{let Z=Date.now(),Q=$.lastRunAt?Math.max(Z,new Date($.lastRunAt).getTime()):Z,J=Q2($.scheduleExpr,Q,$.timezone),j=new Date(J).toISOString();if($.nextRunAt!==j)this.store.updateSpecNextRunAt($.specId,j)}catch{}}}import{existsSync as wS,mkdirSync as CS,watch as PS}from"node:fs";import{relative as SS,resolve as bS}from"node:path";var yS=250;class Rj{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??yS),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{CS($,{recursive:!0}),this.watcher=PS($,{recursive:!0},(W,Z)=>{if(!Z)return;let Q=String(Z).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch(W){this.onError(W)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let W=this.pending.get($);if(W)clearTimeout(W);let Z=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Z)}async reconcileNow($){try{let W=bS(this.reconciler.getCronDir(),$);if(!wS(W)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Z=SS(this.reconciler.getCronDir(),W).replace(/\\/g,"/");await this.reconciler.reconcileFile(Z,W),await this.onReconciled()}catch(W){this.onError(W)}}}class W9{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new X4({dbPath:$.dbPath});let W=$.specs;this.reconciler=new Mj({store:this.store,specs:W}),this.materializer=new e6({store:this.store}),this.eventIngress=new Lj({store:this.store,logger:$.logger}),this.runner=new Z4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:W,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new Rj({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Z)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:Z});else Q.log("cron.watcher.failed",{error:Z})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var cA={};w(cA,{manifestToSessionRecord:()=>LQ,listSessionHistoryFromBackend:()=>Cj,listSessionHistory:()=>TQ,hydrateSessionHistory:()=>vA});import{readdir as IS,readFile as xA}from"node:fs/promises";import{join as gA}from"node:path";import{formatDisplayUserInput as xS,normalizeUserInput as gS}from"@cline/shared";import{resolveSessionDataDir as mA}from"@cline/shared/storage";import{existsSync as hS}from"node:fs";import{readFile as kS}from"node:fs/promises";class Z9{listeners=new Set;subscribe($,W){let Z={listener:$,sessionId:W?.sessionId?.trim()||void 0};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}emit($){let W=$.payload.sessionId?.trim();for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==W)continue;Z.listener($)}}get size(){return this.listeners.size}}async function p$($){let W=$?.trim();if(!W||!hS(W))return[];try{let Z=(await kS(W,"utf8")).trim();if(!Z)return[];let Q=JSON.parse(Z);if(Array.isArray(Q))return Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q.messages;if(Array.isArray(J))return J}return[]}catch{return[]}}function Ej($){return $?{...$}:void 0}async function kA($,W){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await W.queueSpawnRequest($);let Q=await W.upsertSubagentSessionFromHook($);if(!Q)return;await W.appendSubagentHookAudit(Q,$),await W.applySubagentStatus(Q,$)}function Q9($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function W1($){let W=Q9($);if(!W)return;return W.toLowerCase()==="unknown"?void 0:W}function fQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function mS($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function wj($){let W=$??200;return Number.isFinite(W)?Math.max(0,Math.floor(W)):200}function vS($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function cS($){return $.isSubagent!==!0&&!Q9($.parentSessionId)}function uS($){let W=$.match(/\d{13,}/g);if(!W||W.length===0)return 0;let Z=0;for(let Q of W){let J=Number.parseInt(Q,10);if(Number.isFinite(J)&&J>Z)Z=J}return Z}function LQ($){return{sessionId:$.session_id,source:$.source,pid:$.pid,startedAt:$.started_at,endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspace_root,teamName:$.team_name,enableTools:$.enable_tools,enableSpawn:$.enable_spawn,enableTeams:$.enable_teams,isSubagent:!1,prompt:$.prompt,metadata:$.metadata,messagesPath:$.messages_path,updatedAt:$.ended_at??$.started_at}}async function dS($){let W=wj($);if(W===0)return[];let Z=mA(),J=(await IS(Z,{withFileTypes:!0}).catch(()=>[])).filter((X)=>X.isDirectory()).map((X)=>({entry:X,recency:uS(X.name.trim())})).sort((X,Y)=>Y.recency-X.recency||Y.entry.name.localeCompare(X.entry.name));return(await Promise.all(J.map(async({entry:X})=>{let Y=X.name.trim();if(!Y)return;let V=gA(Z,Y,`${Y}.json`),B=await xA(V,"utf8").catch(()=>{return});if(!B)return;let H;try{H=JSON.parse(B)}catch{return}let G=m0.safeParse(H);if(!G.success)return;return LQ(G.data)}))).filter((X)=>Boolean(X)).sort((X,Y)=>Y.startedAt.localeCompare(X.startedAt)).slice(0,W)}async function lS($,W,Z){let Q=wj(W);if(Q===0)return await $.listSessions(0),[];let J=Z.includeSubagents?Q:vS(Q),j=await $.listSessions(J);return(Z.includeSubagents?j:j.filter(cS)).slice(0,Q)}function pS($){if(typeof $==="string")return $.trim();let W=[];for(let Z of $){if(!Z||typeof Z!=="object")continue;let Q=Z;if(Q.type!=="text")continue;let J=Q.text?.trim();if(J)W.push(J)}return W.join(`
506
- `).trim()}function IA($){return $.replace(/\s+/g," ").trim()}function rS($,W){if($.length<=W)return $;return`${$.slice(0,Math.max(0,W-3)).trimEnd()}...`}function iS($){for(let W of["user","assistant"])for(let Z of $){if(Z.role!==W)continue;let Q=IA(pS(Z.content));if(!Q)continue;let J=W==="user"?IA(xS(Q)):Q,j=gS(J.split(`
507
- `)[0]??J);return rS(j,50)}return}function nS($){let W=0;for(let Z of $)W+=fQ(Z.metrics?.cost)??0;return W}function aS($){let W,Z;for(let Q=$.length-1;Q>=0;Q-=1){let J=$[Q];if(!W)W=W1(J.modelInfo?.provider);if(!Z)Z=W1(J.modelInfo?.id);if(W&&Z)break}return{provider:W,model:Z}}function oS($){return W1($?.provider)??W1($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function sS($){return W1($?.model)??W1($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function Nj($,W){let Z=mS($.metadata),Q=Q9(W?.title)??Q9(Z?.title),J=fQ(W?.totalCost)??fQ(Z?.totalCost),j=Z||Q!==void 0||J!==void 0?{...Z??{},...Q!==void 0?{title:Q}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...$,provider:W1(W?.provider)??W1($.provider)??oS(Z)??"",model:W1(W?.model)??W1($.model)??sS(Z)??"",metadata:j}}function tS($){let W=$.content;if(!Array.isArray(W))return!1;return W.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function eS($,W){if($.status!=="running"||$.interactive!==!0)return!1;let Z=W.at(-1);return Z?.role==="assistant"&&!tS(Z)}async function $b($,W){return await Promise.all(W.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let Q=await $.readSessionMessages(Z.sessionId);return eS(Z,Q)?{...Z,status:"idle"}:Z}))}async function vA($,W){return await Promise.all(W.map(async(Z)=>{let Q=Nj(Z),J=Boolean(Q9(Q.metadata?.title)),j=Boolean(W1(Q.provider)),X=Boolean(W1(Q.model)),Y=fQ(Q.metadata?.totalCost),V=Y!==void 0&&Y>0;if(J&&j&&X&&V)return Q;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return Q;let H=aS(B),G=nS(B);return Nj(Z,{title:J?void 0:iS(B),provider:j?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function TQ($,W={}){let Z=wj(W.limit),Q=W.includeSubagents===!0,J=await lS($,Z,{includeSubagents:Q}),j=W.includeManifestFallback===!0&&J.length<Z?await dS(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...J,...j]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let Y=j.length===0?J:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await $b($,Y);if(W.hydrate===!1)return V.map((B)=>Nj(B));return await vA($,V)}async function Wb($){let W=$.trim();if(!W)return;let Z=gA(mA(),W,`${W}.json`),Q=await xA(Z,"utf8").catch(()=>{return});if(!Q)return;try{let J=m0.safeParse(JSON.parse(Q));return J.success?J.data.messages_path:void 0}catch{return}}async function Cj($,W={}){let Z=new Map;return await TQ({listSessions:async(J)=>{let j=await $.listSessions(J);Z.clear();for(let X of j)Z.set(X.sessionId,X);return j.map(H5)},readSessionMessages:async(J)=>{let j=Z.get(J)?.messagesPath??await Wb(J);return await p$(j)}},W)}var bU={};w(bU,{resolveSessionBackend:()=>oj,createRuntimeHost:()=>h6});import{captureSdkError as PU}from"@cline/shared";var $U={};w($U,{HubRuntimeHost:()=>Y$});import{resolveProviderRequestHeaders as jb}from"@cline/llms";import{captureSdkError as Pj,createSessionId as dA,HUB_CHECKPOINT_CAPABILITY as Xb,HUB_COMPACTION_CAPABILITY as Yb,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Vb,HUB_HOOK_CAPABILITY_PREFIX as Bb,HUB_MISTAKE_LIMIT_CAPABILITY as Hb,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Gb,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Kb,isHubToolExecutorName as Fb}from"@cline/shared";var uA={};w(uA,{createCoreSessionSnapshot:()=>N1,coreSessionSnapshotToRecord:()=>OQ});function Zb($){return $?JSON.parse(JSON.stringify($)):void 0}function Qb($){return $?JSON.parse(JSON.stringify($)):void 0}function Jb($){let W=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(W?.history)?W.history:[]).filter((X)=>!!X&&typeof X==="object"&&!Array.isArray(X)).flatMap((X)=>{let Y=typeof X.ref==="string"?X.ref.trim():"",V=Number(X.createdAt),B=Number(X.runCount);if(!Y||!Number.isFinite(V)||!Number.isInteger(B))return[];return[{ref:Y,createdAt:V,runCount:B,...X.kind==="stash"||X.kind==="commit"?{kind:X.kind}:{}}]}),J=Q.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Q.length===0)return;return{...j?{enabled:j}:{},...J?{latest:J}:{},history:Q}}function N1($){let{session:W}=$,Z=Zb(W.metadata);return{version:1,sessionId:W.sessionId,source:W.source,status:W.status,createdAt:W.startedAt,updatedAt:W.updatedAt,endedAt:W.endedAt??null,exitCode:W.exitCode??null,interactive:W.interactive,workspace:{cwd:W.cwd,root:W.workspaceRoot},model:{providerId:W.provider,modelId:W.model},capabilities:{enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams},lineage:{...W.parentSessionId?{parentSessionId:W.parentSessionId}:{},...W.parentAgentId?{parentAgentId:W.parentAgentId}:{},...W.agentId?{agentId:W.agentId}:{},...W.conversationId?{conversationId:W.conversationId}:{},isSubagent:W.isSubagent},...W.teamName?{team:{name:W.teamName}}:{},...W.prompt?{prompt:W.prompt}:{},...Z?{metadata:Z}:{},...W.messagesPath?{artifacts:{messagesPath:W.messagesPath}}:{},...$.messages?{messages:Qb($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=Jb(Z);return Q?{checkpoint:Q}:{}})()}}function OQ($){return{sessionId:$.sessionId,parentSessionId:$.lineage.parentSessionId,agentId:$.lineage.agentId,parentAgentId:$.lineage.parentAgentId,conversationId:$.lineage.conversationId,isSubagent:$.lineage.isSubagent,source:$.source,startedAt:$.createdAt,endedAt:$.endedAt??void 0,exitCode:$.exitCode??void 0,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspaceRoot:$.workspace.root,teamName:$.team?.name,enableTools:$.capabilities.enableTools,enableSpawn:$.capabilities.enableSpawn,enableTeams:$.capabilities.enableTeams,prompt:$.prompt,metadata:$.metadata,updatedAt:$.updatedAt,messagesPath:$.artifacts?.messagesPath}}function E6($){if(!$)return;return JSON.parse(JSON.stringify($))}var Ab=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function lA($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function pA($){if(!$)return;let{userInstructionService:W,...Z}=$;return JSON.parse(JSON.stringify(Z))}function rA($,W){let Z={...$.config,sessionId:W},Q=jb({providerId:$.config.providerId,sessionId:W,source:$.source,defaultSource:F0.CORE,client:{name:$.localRuntime?.extensionContext?.client?.name,version:$.localRuntime?.extensionContext?.client?.version,versionHeaderFallback:$.config.headers?.["X-CLIENT-VERSION"],platform:$.localRuntime?.extensionContext?.client?.platform,platformVersion:$.localRuntime?.extensionContext?.client?.platformVersion,isMultiRoot:$.localRuntime?.extensionContext?.client?.isMultiRoot},coreVersion:R8,openAiCodex:{accessToken:$.config.apiKey,userAgentVersion:process.env.npm_package_version},headers:{config:$.config.headers}});if(Q)Z.headers=Q;return Z}function iA($){let W=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof W.agentId==="string"?W.agentId:"",conversationId:typeof W.conversationId==="string"?W.conversationId:"",iteration:typeof W.iteration==="number"?W.iteration:0,metadata:W.metadata&&typeof W.metadata==="object"&&!Array.isArray(W.metadata)?W.metadata:void 0}}function s2($,W,Z){$.manifest.push(W),$.handlers.set(W.capabilityName,Z)}function nA($,W){let Z={manifest:[],handlers:new Map};for(let J of Object.keys(W.toolExecutors??{}).filter(Fb)){let j=W.toolExecutors?.[J];if(typeof j!=="function")continue;s2(Z,{kind:"toolExecutor",executor:J,capabilityName:`${Gb}${J}`},async({payload:X,abortSignal:Y})=>{let V=Array.isArray(X.args)?[...X.args]:[],B={...iA(X.context),signal:Y};return{result:await j(...V,B)}})}for(let J of $?.extraTools??[])s2(Z,{kind:"tool",name:J.name,description:J.description,inputSchema:E6(J.inputSchema)??{},...J.lifecycle?{lifecycle:E6(J.lifecycle)}:{},capabilityName:`${Vb}${J.name}`},async({payload:j,abortSignal:X,progress:Y})=>{let V={...iA(j.context),signal:X};return{result:await J.execute(j.input,{...V,emitUpdate:(H)=>{Y({update:H})}})}});let Q=$?.hooks;if(Q)for(let J of Ab){let j=Q[J];if(typeof j!=="function")continue;s2(Z,{kind:"hook",name:J,capabilityName:`${Bb}${J}`},async({payload:X})=>({control:await j(X.context)}))}if($?.compaction?.compact){let J=$.compaction.compact;s2(Z,{kind:"compaction",capabilityName:Yb,config:lA($.compaction)},async({payload:j})=>({result:await J(j.context)}))}if($?.checkpoint?.createCheckpoint){let J=$.checkpoint.createCheckpoint;s2(Z,{kind:"checkpoint",capabilityName:Xb,config:lA($.checkpoint)},async({payload:j})=>({result:await J(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let J=$.onConsecutiveMistakeLimitReached;s2(Z,{kind:"mistakeLimit",capabilityName:Hb},async({payload:j})=>({result:await J(j.context)}))}if($?.userInstructionService){let J=$.userInstructionService;s2(Z,{kind:"userInstructionService",capabilityName:Kb},async()=>{return await J.start().catch(()=>{}),{snapshot:{records:{skill:J.listRecords("skill"),rule:J.listRecords("rule"),workflow:J.listRecords("workflow")},runtimeCommands:J.listRuntimeCommands()}}})}return Z}function tA($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let W=$.message;if(typeof W==="string"&&W.trim())return W.trim()}return}function Ub($){return tA($)??"Capability request was cancelled."}function Db($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function _b($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function fb($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=typeof W.inputTokens==="number"?W.inputTokens:void 0,Q=typeof W.outputTokens==="number"?W.outputTokens:void 0;if(Z===void 0||Q===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:typeof W.cacheReadTokens==="number"?W.cacheReadTokens:0,cacheWriteTokens:typeof W.cacheWriteTokens==="number"?W.cacheWriteTokens:0,totalCost:typeof W.totalCost==="number"?W.totalCost:0}}function aA($){if(!$)return;return{inputTokens:typeof $.inputTokens==="number"?$.inputTokens:0,outputTokens:typeof $.outputTokens==="number"?$.outputTokens:0,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function Sj($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function r$($,W){return Sj($?.[W])??0}function Lb($){let W=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Z=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,J=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:r$(W,"inputTokens"),outputTokens:r$(W,"outputTokens"),cacheReadTokens:r$(W,"cacheReadTokens"),cacheWriteTokens:r$(W,"cacheWriteTokens"),cost:Sj(W?.totalCost),totalInputTokens:r$(Z,"inputTokens"),totalOutputTokens:r$(Z,"outputTokens"),totalCacheReadTokens:r$(Z,"cacheReadTokens"),totalCacheWriteTokens:r$(Z,"cacheWriteTokens"),totalCost:Sj(Z?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:J}}function Tb($){let W=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Z=$?.reason??W?.finishReason,Q=_b(Z)?Z:Z==="failed"?"error":"completed",J=fb($?.usage??W?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof W?.text==="string"?W.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof W?.iterations==="number"?W.iterations:0,usage:J}}function t2($,W){return $.error?.message??`hub command failed: ${W}`}function J9($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function eA($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof W?.parentSessionId==="string"?W.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof W?.agentId==="string"?W.agentId:void 0),parentAgentId:typeof W?.parentAgentId==="string"?W.parentAgentId:void 0,conversationId:typeof W?.conversationId==="string"?W.conversationId:void 0,isSubagent:typeof W?.isSubagent==="boolean"?W.isSubagent:!1,source:typeof W?.source==="string"?W.source:F0.CORE,pid:typeof W?.pid==="number"?W.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:J9($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:J9($.status)==="completed"?0:J9($.status)==="failed"?1:void 0,status:J9($.status),interactive:W?.interactive===!0,provider:typeof W?.provider==="string"?W.provider:"hub",model:typeof W?.model==="string"?W.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof W?.teamName==="string"?W.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??W?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??W?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??W?.enableTeams===!0,prompt:typeof W?.prompt==="string"?W.prompt:void 0,metadata:W,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof W?.messagesPath==="string"?W.messagesPath:void 0,hookPath:typeof W?.hookPath==="string"?W.hookPath:void 0}}function i$($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$;return W.version===1&&typeof W.sessionId==="string"?JSON.parse(JSON.stringify(W)):void 0}function Ob($){let W=i$($?.snapshot);if(W)return OQ(W);let Z=$?.session;return Z?eA(Z):void 0}function oA($,W,Z){let Q=Z?.workspaceRoot?.trim()||W.config.workspaceRoot||W.config.cwd;return m0.parse({version:1,session_id:$,source:W.source??F0.CORE,pid:process.pid,started_at:new Date(Z?.createdAt??Date.now()).toISOString(),status:J9(Z?.status),interactive:W.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:Z?.cwd?.trim()||W.config.cwd,workspace_root:Q,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,metadata:W.sessionMetadata&&Object.keys(W.sessionMetadata).length>0?W.sessionMetadata:void 0})}function sA($,W){return m0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??W.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class Y${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new Z9;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,W){this.clientContext=W,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd},this.defaultCapabilities=P0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Z)=>this.requestPendingPromptsList(Z),update:(Z)=>this.requestPendingPromptUpdate(Z),delete:(Z)=>this.requestPendingPromptDelete(Z)},this.client=this.createClient($.url)}createClient($){return new B1({...this.clientOptions,url:$})}async replaceClient($){let W=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(W.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!NW($,"session.create"))return!1;let W=await wW({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!W)return!1;return await this.replaceClient(W),!0}registerPlannedSession($,W,Z){if(this.sessionCapabilities.set($,W),Z.size>0)this.sessionClientContributionHandlers.set($,Z);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let W=this.resolveCapabilities($),Z=nA($.localRuntime,W),Q=$.config.sessionId?.trim()||dA(),J=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:E6(rA($,Q)),metadata:{...$.sessionMetadata??{},source:$.source??F0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Z.manifest.length>0?{clientContributions:Z.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:E6($.toolPolicies),initialMessages:$.initialMessages,...$.initialCompactionState?{initialCompactionState:$.initialCompactionState}:{}});this.registerPlannedSession(Q,W,Z.handlers);let j;try{j=await J()}catch(B){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(B)){this.registerPlannedSession(Q,W,Z.handlers);try{j=await J()}catch(H){throw this.cleanupPlannedSession(Q),H}}else throw B}let X=i$(j.payload?.snapshot),Y=j.payload?.session,V=(X?.sessionId??Y?.sessionId)?.trim();if(!V)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(V!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(V,W,Z.handlers);return{sessionId:V,manifest:X?sA(X,$):oA(V,$,Y),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,J=Q?this.resolveCapabilities(Q):void 0,j=Q?nA(Q.localRuntime,J??{}):{manifest:[],handlers:new Map},X,Y;if(Q)X=Q.config.sessionId?.trim()||dA(),Y=rA(Q,X);if(X&&J)this.sessionCapabilities.set(X,J);if(X&&j.handlers.size>0)this.sessionClientContributionHandlers.set(X,j.handlers),this.ensureSessionSubscription(X);let V;try{V=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:E6(Y),metadata:{...Q.sessionMetadata??{},source:Q.source??F0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:E6(Q.toolPolicies),...Q.initialCompactionState?{initialCompactionState:Q.initialCompactionState}:{}}:{}},W)}catch(A){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw A}if(!V.ok){let A=typeof V.payload?.error==="string"?V.payload.error:"session.restore failed";if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error(A)}let B=i$(V.payload?.snapshot),H=V.payload?.session,G=(B?.sessionId??H?.sessionId)?.trim();if(Z&&!G){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error("Hub checkpoint restore returned no session id")}if(G&&X&&G!==X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);if(G&&J)this.sessionCapabilities.set(G,J);if(G&&j.handlers.size>0)this.sessionClientContributionHandlers.set(G,j.handlers);if(G)this.ensureSessionSubscription(G);let K=Array.isArray(V.payload?.messages)?V.payload.messages:void 0,F=V.payload?.checkpoint;if(!F)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:G,startResult:G?{sessionId:G,manifest:B?sA(B,Q??{}):oA(G,Q??{},H),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:K,checkpoint:F}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(W.payload?.prompts)?W.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,updated:W.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,removed:W.payload?.removed===!0}}async getAccumulatedUsage($){let W=await this.client.command("session.get",{includeSnapshot:!0},$),Z=i$(W.payload?.snapshot);if(Z){let X=Z.usage?{...Z.usage}:void 0,Y=Z.aggregateUsage?{...Z.aggregateUsage}:void 0;return X||Y?{usage:X,aggregateUsage:Y}:void 0}let Q=W.payload?.session,J=aA(Q?.usage),j=aA(Q?.aggregateUsage);return J||j?{usage:J,aggregateUsage:j}:void 0}async abort($,W){await this.client.command("run.abort",{sessionId:$,reason:tA(W)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,W]of this.sessionSubscriptions){W();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(p1(Z))return;throw Z}return Ob(W.payload)}async listSessions($=100){let W=await this.client.command("session.list",{limit:$}),Z=Array.isArray(W.payload?.snapshots)?W.payload.snapshots.flatMap((J)=>{let j=i$(J);return j?[OQ(j)]:[]}):[];if(Z.length>0)return Z;return(W.payload?.sessions??[]).map(eA)}async listSettings($){let W=await this.client.command("settings.list",pA($));if(!W.ok)throw Error(t2(W,"settings.list"));return W.payload?.snapshot}async toggleSetting($){let W=await this.client.command("settings.toggle",pA($));if(!W.ok)throw Error(t2(W,"settings.toggle"));return{snapshot:W.payload?.snapshot,changedTypes:Array.isArray(W.payload?.changedTypes)?W.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,W){let Z={...W.metadata??{}};if(typeof W.prompt==="string")Z.prompt=W.prompt;if(typeof W.title==="string")Z.title=W.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Z})).ok}}async updateSessionConnection($,W){let Z=$.trim();if(!Z)return;let Q=await this.client.command("session.update_connection",{sessionId:Z,updates:W},Z);if(!Q.ok)throw Error(t2(Q,"session.update_connection"))}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=await this.client.command("session.compaction.update",{sessionId:Z,state:W},Z);if(!Q.ok)Pj(this.telemetry,{component:"core",operation:"hub.runtime_host.update_session_compaction_state",error:Error(t2(Q,"session.compaction.update")),severity:"warn",handled:!0,context:{command:"session.compaction.update",sessionId:Z,errorCode:Q.error?.code}});return{updated:Q.ok&&Q.payload?.updated===!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=await this.client.command("session.compaction.get",{sessionId:W},W);if(!Z.ok)throw Error(t2(Z,"session.compaction.get"));return G1(Z.payload?.state)}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Pj(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(t2(Z,"session.messages")),severity:Z.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:W,errorCode:Z.error?.code,runtimeAddress:this.runtimeAddress}}),Error(t2(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,W){return this.events.subscribe($,W)}ensureSessionSubscription($){let W=$.trim();if(!W||this.sessionSubscriptions.has(W))return;let Z=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:W});this.sessionSubscriptions.set(W,typeof Z==="function"?Z:()=>{})}disposeSessionSubscription($){let W=$.trim();if(!W)return;this.sessionSubscriptions.get(W)?.(),this.sessionSubscriptions.delete(W),this.agentDoneEmittedForCurrentRunBySession.delete(W)}resolveCapabilities($){return P0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:Tb($.payload)}})}handleHubEvent($){let W=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Z,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Z,$)});return}if(!W)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(W);let Z=i$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"session.notice":{let Z=$.payload?.noticeType,Q=$.payload?.displayRole,J=$.payload?.reason,j=$.payload?.agent&&typeof $.payload.agent==="object"?$.payload.agent:void 0,X=j?.teamRole==="lead"||j?.teamRole==="teammate"?j.teamRole:void 0;this.events.emit({type:"agent_event",payload:{sessionId:W,...X?{teamRole:X}:{},...typeof j?.teamAgentId==="string"?{teamAgentId:j.teamAgentId}:{},event:{type:"notice",...typeof j?.agentId==="string"?{agentId:j.agentId}:{},...typeof j?.conversationId==="string"?{conversationId:j.conversationId}:{},...typeof j?.parentAgentId==="string"?{parentAgentId:j.parentAgentId}:{},noticeType:Z==="recovery"||Z==="stop"?Z:"status",message:typeof $.payload?.message==="string"?$.payload.message:"",...Q==="system"||Q==="status"?{displayRole:Q}:{},...typeof J==="string"?{reason:J}:{},...$.payload?.metadata&&typeof $.payload.metadata==="object"?{metadata:$.payload.metadata}:{}}}});return}case"assistant.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"";if(!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"text",text:Z}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!Z&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"reasoning",reasoning:Z,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:W,payload:$.payload});return}case"usage.updated":{let Z=Lb($.payload);this.events.emit({type:"agent_event",payload:{sessionId:W,event:Z.event,teamAgentId:Z.teamAgentId,teamRole:Z.teamRole}});return}case"tool.started":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z&&this.pendingApprovalToolCallIds.delete(Z))return;this.emitToolCallContentStart({sessionId:W,toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z)this.pendingApprovalToolCallIds.delete(Z);this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"tool",toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Z=i$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:W,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Z=$.payload?.prompt;if(!Z)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:W,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}});return}case"run.completed":case"run.failed":case"run.aborted":{let Z=i$($.payload?.snapshot),Q=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:W,payload:{...$.payload,reason:Q}}),Z?.interactive===!0&&K0(Z.status))return;this.events.emit({type:"ended",payload:{sessionId:W,reason:Q,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,W,Z){try{Pj(this.telemetry,{component:"core",operation:$,error:W,severity:"warn",handled:!0,context:{event:Z.event,sessionId:Z.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let W=$.sessionId?.trim();if(!W)return;let Z=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Z&&Z!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",J=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let j=this.sessionClientContributionHandlers.get(W)?.get(J);if(!j){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${J} in session ${W}.`},W).catch(()=>{});return}let X=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},Y=new AbortController;this.activeCapabilityAbortControllers.set(Q,Y);let V=(B)=>{this.client.command("capability.progress",{requestId:Q,payload:B},W).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let B=await j({payload:X,abortSignal:Y.signal,progress:V});if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:B},W)}catch(B){if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:B instanceof Error?B.message:String(B)},W)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let W=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!W)return;let Z=this.activeCapabilityAbortControllers.get(W);if(!Z)return;Z.abort(Ub($.payload.error))}async handleApprovalRequested($){let W=$.sessionId?.trim();if(!W)return;let Z=this.sessionCapabilities.get(W)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Z)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!J||!j)return;let X=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},Y=Db($.payload?.inputJson);this.pendingApprovalToolCallIds.add(J),this.emitToolCallContentStart({sessionId:W,toolCallId:J,toolName:j,toolInput:Y});let V=await Promise.resolve(Z({sessionId:W,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:W,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:J,toolName:j,input:Y,policy:X})).catch((B)=>({approved:!1,reason:B instanceof Error?B.message:`Tool approval request failed: ${String(B)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:V.approved,reason:V.reason},W).catch(()=>{})}}var WU={};w(WU,{RemoteRuntimeHost:()=>N6});class N6 extends Y${constructor($){super({url:z$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var ZU={};w(ZU,{SqliteSessionStore:()=>C1});import{existsSync as zb,mkdirSync as qb}from"node:fs";import{join as Mb}from"node:path";import{asBool as j9,asOptionalString as w1,asString as V$,ensureSessionSchema as Rb,loadSqliteDb as Eb,nowIso as zQ,toBoolInt as X9}from"@cline/shared/db";import{resolveDbDataDir as Nb}from"@cline/shared/storage";class C1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??Nb()}init(){this.getRawDb()}ensureSessionsDir(){if(!zb(this.sessionsDirPath))qb(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return Mb(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=Eb(this.sessionDbPath());return Rb($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}create($){let W=zQ();this.run(`INSERT OR REPLACE INTO sessions (
504
+ `))j=j.slice(1);return{frontmatter:J,body:j}}function $1($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function HS($){if(!Array.isArray($))return;let W=$.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);return W.length>0?W:void 0}function qj($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function GS($){let W=qj($);if(!W)return;let Z=$1(W.providerId),Q=$1(W.modelId);if(Z===void 0&&Q===void 0)return;return{providerId:Z,modelId:Q}}function KS($){if(typeof $!=="string")return;let W=$.trim().toLowerCase();if(W==="act"||W==="plan"||W==="yolo")return W;return}function yA($,W={}){let Z=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Z)return;let Q=[...new Set(Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0))];if(Array.isArray($)&&W.preserveEmptyArray)return Q;return Q.length>0?Q:void 0}var FS=new Set(D$);function AS($){let W=yA($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!FS.has(Q));if(Z.length>0)throw Error(`unknown tool(s): ${Z.join(", ")}`);return W}var US=new Set(["rules","skills","plugins"]);function DS($){let W=yA($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!US.has(Q));if(Z.length>0)throw Error(`unknown extension(s): ${Z.join(", ")}`);return W}function Oj($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function zj($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function Mj($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Z)=>Mj(Z)).join(",")}]`;let W=Object.entries($).filter(([,Z])=>Z!==void 0);return W.sort(([Z],[Q])=>Z<Q?-1:Z>Q?1:0),`{${W.map(([Z,Q])=>`${JSON.stringify(Z)}:${Mj(Q)}`).join(",")}}`}function hA($,W){let Z=XS("sha256");return Z.update(Mj($)),Z.update(`
505
+ `),Z.update(W),Z.digest("hex")}function _S($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var fS=["schedule","timezone"],LS=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],TS=["cwd"];function bA($,W,Z,Q,J){return{externalId:$,relativePath:$,triggerKind:W,body:Z,contentHash:hA(Q,Z),error:J}}function E1($,W,Z,Q,J,j){return{externalId:$,relativePath:W,triggerKind:Z,body:Q,contentHash:J,error:j}}function kA($){let W=$.relativePath.replace(/\\/g,"/"),Z=VS(W),{frontmatter:Q,body:J}=BS($.raw),j={};if(Q!==void 0&&Q.trim().length>0)try{let _=YS.parse(Q);if(_&&typeof _==="object"&&!Array.isArray(_))j=_;else if(_!==null&&_!==void 0)return bA(W,Z,J,{},"frontmatter must be a YAML mapping")}catch(_){return bA(W,Z,J,{},_ instanceof Error?`failed to parse frontmatter: ${_.message}`:"failed to parse frontmatter")}let X=hA(j,J),Y=$1(j.id),V=Y??W;if(Z!=="schedule"){for(let _ of fS)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is only allowed on *.cron.md specs`)}for(let _ of TS)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Z!=="event"){for(let _ of LS)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is only allowed on .event.md specs`)}let B=$1(j.prompt),H=J.trim(),G=B??(H.length>0?H:void 0);if(!G)return E1(V,W,Z,J,X,"prompt is required (frontmatter `prompt` or markdown body)");let K=$1(j.workspaceRoot);if(!K)return E1(V,W,Z,J,X,"workspaceRoot is required");let F,A;try{F=AS(j.tools),A=DS(j.extensions)}catch(_){return E1(V,W,Z,J,X,_ instanceof Error?_.message:String(_))}let D=KS(j.mode);if(j.mode!==void 0&&D===void 0)return E1(V,W,Z,J,X,"mode must be one of: act, plan, yolo");let U={id:Y,title:$1(j.title)??Y??_S(W),prompt:G,workspaceRoot:K,mode:D??"yolo",systemPrompt:$1(j.systemPrompt),modelSelection:GS(j.modelSelection),maxIterations:Oj(j.maxIterations),timeoutSeconds:Oj(j.timeoutSeconds),tools:F,notesDirectory:$1(j.notesDirectory),extensions:A,source:$1(j.source)??"user",tags:HS(j.tags),enabled:typeof j.enabled==="boolean"?j.enabled:!0,metadata:qj(j.metadata)},f;if(Z==="schedule"){let _=$1(j.schedule);if(!_)return E1(V,W,Z,J,X,"schedule is required for *.cron.md specs");let R=$1(j.timezone);try{KV(_,R)}catch(T){return E1(V,W,Z,J,X,T instanceof Error?T.message:String(T))}f={...U,triggerKind:"schedule",schedule:_,timezone:R}}else if(Z==="event"){let _=$1(j.event);if(!_)return E1(V,W,Z,J,X,"event is required for .event.md specs");f={...U,triggerKind:"event",event:_,filters:qj(j.filters),debounceSeconds:zj(j.debounceSeconds),dedupeWindowSeconds:zj(j.dedupeWindowSeconds),cooldownSeconds:zj(j.cooldownSeconds),maxParallel:Oj(j.maxParallel)}}else f={...U,triggerKind:"one_off"};return{externalId:V,relativePath:W,triggerKind:Z,body:J,contentHash:X,spec:f}}function NS($,W){return RS($,W).replace(/\\/g,"/")}function wS($){if(!OS($))return[];let W=[],Z=[$];while(Z.length>0){let Q=Z.pop();if(!Q)continue;let J;try{J=zS(Q,{withFileTypes:!0})}catch{continue}for(let j of J){let X=`${Q}/${j.name}`;if(j.isDirectory()){if(j.name==="reports")continue;Z.push(X);continue}if(!j.isFile())continue;if(!j.name.endsWith(".md"))continue;W.push(X)}}return W}class Rj{store;cronDir;constructor($){this.store=$.store,this.cronDir=ES($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},W=wS(this.cronDir),Z=new Set;for(let J of W){let j=NS(this.cronDir,J);Z.add(j),$.scanned+=1;let X=await this.reconcileFile(j,J);if(X){if($.changes.push(X),$.upserted+=1,X.parse.error)$.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let J of Q)if(!Z.has(J.sourcePath))this.handleFileDeleted(J),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,W){let Z=this.store.getSpecBySourcePath($),Q,J;try{Q=qS(W,"utf8"),J=MS(W).mtimeMs}catch{return}let X=kA({relativePath:$,raw:Q}),Y=this.store.upsertSpec({externalId:X.externalId,sourcePath:$,triggerKind:X.triggerKind,sourceMtimeMs:J,sourceHash:X.contentHash,parseStatus:X.error?"invalid":"valid",parseError:X.error,spec:X.spec});if(!X.error&&X.triggerKind==="schedule"&&Y.record.enabled)this.applyScheduleNextRunAt(Y.record,{forceReset:!Z||Z.removed||!Z.enabled||Z.scheduleExpr!==Y.record.scheduleExpr||Z.timezone!==Y.record.timezone});return{relativePath:$,result:Y,parse:X}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of $)this.applyScheduleNextRunAt(W,{forceReset:!1})}applyScheduleNextRunAt($,W){if(!$.scheduleExpr)return;if(!W.forceReset&&$.nextRunAt)return;try{let Z=Date.now(),Q=$.lastRunAt?Math.max(Z,new Date($.lastRunAt).getTime()):Z,J=Q2($.scheduleExpr,Q,$.timezone),j=new Date(J).toISOString();if($.nextRunAt!==j)this.store.updateSpecNextRunAt($.specId,j)}catch{}}}import{existsSync as CS,mkdirSync as PS,watch as SS}from"node:fs";import{relative as bS,resolve as yS}from"node:path";var hS=250;class Ej{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??hS),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{PS($,{recursive:!0}),this.watcher=SS($,{recursive:!0},(W,Z)=>{if(!Z)return;let Q=String(Z).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch(W){this.onError(W)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let W=this.pending.get($);if(W)clearTimeout(W);let Z=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Z)}async reconcileNow($){try{let W=yS(this.reconciler.getCronDir(),$);if(!CS(W)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Z=bS(this.reconciler.getCronDir(),W).replace(/\\/g,"/");await this.reconciler.reconcileFile(Z,W),await this.onReconciled()}catch(W){this.onError(W)}}}class W9{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new X4({dbPath:$.dbPath});let W=$.specs;this.reconciler=new Rj({store:this.store,specs:W}),this.materializer=new e6({store:this.store}),this.eventIngress=new Tj({store:this.store,logger:$.logger}),this.runner=new Z4({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:W,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new Ej({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Z)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:Z});else Q.log("cron.watcher.failed",{error:Z})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var uA={};w(uA,{manifestToSessionRecord:()=>TQ,listSessionHistoryFromBackend:()=>Pj,listSessionHistory:()=>OQ,hydrateSessionHistory:()=>cA});import{readdir as xS,readFile as gA}from"node:fs/promises";import{join as mA}from"node:path";import{formatDisplayUserInput as gS,normalizeUserInput as mS}from"@cline/shared";import{resolveSessionDataDir as vA}from"@cline/shared/storage";import{existsSync as kS}from"node:fs";import{readFile as IS}from"node:fs/promises";class Z9{listeners=new Set;subscribe($,W){let Z={listener:$,sessionId:W?.sessionId?.trim()||void 0};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}emit($){let W=$.payload.sessionId?.trim();for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==W)continue;Z.listener($)}}get size(){return this.listeners.size}}async function p$($){let W=$?.trim();if(!W||!kS(W))return[];try{let Z=(await IS(W,"utf8")).trim();if(!Z)return[];let Q=JSON.parse(Z);if(Array.isArray(Q))return Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q.messages;if(Array.isArray(J))return J}return[]}catch{return[]}}function Nj($){return $?{...$}:void 0}async function IA($,W){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await W.queueSpawnRequest($);let Q=await W.upsertSubagentSessionFromHook($);if(!Q)return;await W.appendSubagentHookAudit(Q,$),await W.applySubagentStatus(Q,$)}function Q9($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function W1($){let W=Q9($);if(!W)return;return W.toLowerCase()==="unknown"?void 0:W}function LQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function vS($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function Cj($){let W=$??200;return Number.isFinite(W)?Math.max(0,Math.floor(W)):200}function cS($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function uS($){return $.isSubagent!==!0&&!Q9($.parentSessionId)}function dS($){let W=$.match(/\d{13,}/g);if(!W||W.length===0)return 0;let Z=0;for(let Q of W){let J=Number.parseInt(Q,10);if(Number.isFinite(J)&&J>Z)Z=J}return Z}function TQ($){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 lS($){let W=Cj($);if(W===0)return[];let Z=vA(),J=(await xS(Z,{withFileTypes:!0}).catch(()=>[])).filter((X)=>X.isDirectory()).map((X)=>({entry:X,recency:dS(X.name.trim())})).sort((X,Y)=>Y.recency-X.recency||Y.entry.name.localeCompare(X.entry.name));return(await Promise.all(J.map(async({entry:X})=>{let Y=X.name.trim();if(!Y)return;let V=mA(Z,Y,`${Y}.json`),B=await gA(V,"utf8").catch(()=>{return});if(!B)return;let H;try{H=JSON.parse(B)}catch{return}let G=m0.safeParse(H);if(!G.success)return;return TQ(G.data)}))).filter((X)=>Boolean(X)).sort((X,Y)=>Y.startedAt.localeCompare(X.startedAt)).slice(0,W)}async function pS($,W,Z){let Q=Cj(W);if(Q===0)return await $.listSessions(0),[];let J=Z.includeSubagents?Q:cS(Q),j=await $.listSessions(J);return(Z.includeSubagents?j:j.filter(uS)).slice(0,Q)}function rS($){if(typeof $==="string")return $.trim();let W=[];for(let Z of $){if(!Z||typeof Z!=="object")continue;let Q=Z;if(Q.type!=="text")continue;let J=Q.text?.trim();if(J)W.push(J)}return W.join(`
506
+ `).trim()}function xA($){return $.replace(/\s+/g," ").trim()}function iS($,W){if($.length<=W)return $;return`${$.slice(0,Math.max(0,W-3)).trimEnd()}...`}function nS($){for(let W of["user","assistant"])for(let Z of $){if(Z.role!==W)continue;let Q=xA(rS(Z.content));if(!Q)continue;let J=W==="user"?xA(gS(Q)):Q,j=mS(J.split(`
507
+ `)[0]??J);return iS(j,50)}return}function aS($){let W=0;for(let Z of $)W+=LQ(Z.metrics?.cost)??0;return W}function oS($){let W,Z;for(let Q=$.length-1;Q>=0;Q-=1){let J=$[Q];if(!W)W=W1(J.modelInfo?.provider);if(!Z)Z=W1(J.modelInfo?.id);if(W&&Z)break}return{provider:W,model:Z}}function sS($){return W1($?.provider)??W1($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function tS($){return W1($?.model)??W1($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function wj($,W){let Z=vS($.metadata),Q=Q9(W?.title)??Q9(Z?.title),J=LQ(W?.totalCost)??LQ(Z?.totalCost),j=Z||Q!==void 0||J!==void 0?{...Z??{},...Q!==void 0?{title:Q}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...$,provider:W1(W?.provider)??W1($.provider)??sS(Z)??"",model:W1(W?.model)??W1($.model)??tS(Z)??"",metadata:j}}function eS($){let W=$.content;if(!Array.isArray(W))return!1;return W.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function $b($,W){if($.status!=="running"||$.interactive!==!0)return!1;let Z=W.at(-1);return Z?.role==="assistant"&&!eS(Z)}async function Wb($,W){return await Promise.all(W.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let Q=await $.readSessionMessages(Z.sessionId);return $b(Z,Q)?{...Z,status:"idle"}:Z}))}async function cA($,W){return await Promise.all(W.map(async(Z)=>{let Q=wj(Z),J=Boolean(Q9(Q.metadata?.title)),j=Boolean(W1(Q.provider)),X=Boolean(W1(Q.model)),Y=LQ(Q.metadata?.totalCost),V=Y!==void 0&&Y>0;if(J&&j&&X&&V)return Q;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return Q;let H=oS(B),G=aS(B);return wj(Z,{title:J?void 0:nS(B),provider:j?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function OQ($,W={}){let Z=Cj(W.limit),Q=W.includeSubagents===!0,J=await pS($,Z,{includeSubagents:Q}),j=W.includeManifestFallback===!0&&J.length<Z?await lS(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...J,...j]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let Y=j.length===0?J:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await Wb($,Y);if(W.hydrate===!1)return V.map((B)=>wj(B));return await cA($,V)}async function Zb($){let W=$.trim();if(!W)return;let Z=mA(vA(),W,`${W}.json`),Q=await gA(Z,"utf8").catch(()=>{return});if(!Q)return;try{let J=m0.safeParse(JSON.parse(Q));return J.success?J.data.messages_path:void 0}catch{return}}async function Pj($,W={}){let Z=new Map;return await OQ({listSessions:async(J)=>{let j=await $.listSessions(J);Z.clear();for(let X of j)Z.set(X.sessionId,X);return j.map(H5)},readSessionMessages:async(J)=>{let j=Z.get(J)?.messagesPath??await Zb(J);return await p$(j)}},W)}var yU={};w(yU,{resolveSessionBackend:()=>sj,createRuntimeHost:()=>h6});import{captureSdkError as SU}from"@cline/shared";var WU={};w(WU,{HubRuntimeHost:()=>Y$});import{resolveProviderRequestHeaders as Xb}from"@cline/llms";import{captureSdkError as Sj,createSessionId as lA,HUB_CHECKPOINT_CAPABILITY as Yb,HUB_COMPACTION_CAPABILITY as Vb,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Bb,HUB_HOOK_CAPABILITY_PREFIX as Hb,HUB_MISTAKE_LIMIT_CAPABILITY as Gb,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Kb,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Fb,isHubToolExecutorName as Ab}from"@cline/shared";var dA={};w(dA,{createCoreSessionSnapshot:()=>N1,coreSessionSnapshotToRecord:()=>zQ});function Qb($){return $?JSON.parse(JSON.stringify($)):void 0}function Jb($){return $?JSON.parse(JSON.stringify($)):void 0}function jb($){let W=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(W?.history)?W.history:[]).filter((X)=>!!X&&typeof X==="object"&&!Array.isArray(X)).flatMap((X)=>{let Y=typeof X.ref==="string"?X.ref.trim():"",V=Number(X.createdAt),B=Number(X.runCount);if(!Y||!Number.isFinite(V)||!Number.isInteger(B))return[];return[{ref:Y,createdAt:V,runCount:B,...X.kind==="stash"||X.kind==="commit"?{kind:X.kind}:{}}]}),J=Q.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Q.length===0)return;return{...j?{enabled:j}:{},...J?{latest:J}:{},history:Q}}function N1($){let{session:W}=$,Z=Qb(W.metadata);return{version:1,sessionId:W.sessionId,source:W.source,status:W.status,createdAt:W.startedAt,updatedAt:W.updatedAt,endedAt:W.endedAt??null,exitCode:W.exitCode??null,interactive:W.interactive,workspace:{cwd:W.cwd,root:W.workspaceRoot},model:{providerId:W.provider,modelId:W.model},capabilities:{enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams},lineage:{...W.parentSessionId?{parentSessionId:W.parentSessionId}:{},...W.parentAgentId?{parentAgentId:W.parentAgentId}:{},...W.agentId?{agentId:W.agentId}:{},...W.conversationId?{conversationId:W.conversationId}:{},isSubagent:W.isSubagent},...W.teamName?{team:{name:W.teamName}}:{},...W.prompt?{prompt:W.prompt}:{},...Z?{metadata:Z}:{},...W.messagesPath?{artifacts:{messagesPath:W.messagesPath}}:{},...$.messages?{messages:Jb($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=jb(Z);return Q?{checkpoint:Q}:{}})()}}function zQ($){return{sessionId:$.sessionId,parentSessionId:$.lineage.parentSessionId,agentId:$.lineage.agentId,parentAgentId:$.lineage.parentAgentId,conversationId:$.lineage.conversationId,isSubagent:$.lineage.isSubagent,source:$.source,startedAt:$.createdAt,endedAt:$.endedAt??void 0,exitCode:$.exitCode??void 0,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspaceRoot:$.workspace.root,teamName:$.team?.name,enableTools:$.capabilities.enableTools,enableSpawn:$.capabilities.enableSpawn,enableTeams:$.capabilities.enableTeams,prompt:$.prompt,metadata:$.metadata,updatedAt:$.updatedAt,messagesPath:$.artifacts?.messagesPath}}function E6($){if(!$)return;return JSON.parse(JSON.stringify($))}var Ub=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function pA($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function rA($){if(!$)return;let{userInstructionService:W,...Z}=$;return JSON.parse(JSON.stringify(Z))}function iA($,W){let Z={...$.config,sessionId:W},Q=Xb({providerId:$.config.providerId,sessionId:W,source:$.source,defaultSource:F0.CORE,client:{name:$.localRuntime?.extensionContext?.client?.name,version:$.localRuntime?.extensionContext?.client?.version,versionHeaderFallback:$.config.headers?.["X-CLIENT-VERSION"],platform:$.localRuntime?.extensionContext?.client?.platform,platformVersion:$.localRuntime?.extensionContext?.client?.platformVersion,isMultiRoot:$.localRuntime?.extensionContext?.client?.isMultiRoot},coreVersion:R8,openAiCodex:{accessToken:$.config.apiKey,userAgentVersion:process.env.npm_package_version},headers:{config:$.config.headers}});if(Q)Z.headers=Q;return Z}function nA($){let W=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof W.agentId==="string"?W.agentId:"",conversationId:typeof W.conversationId==="string"?W.conversationId:"",iteration:typeof W.iteration==="number"?W.iteration:0,metadata:W.metadata&&typeof W.metadata==="object"&&!Array.isArray(W.metadata)?W.metadata:void 0}}function s2($,W,Z){$.manifest.push(W),$.handlers.set(W.capabilityName,Z)}function aA($,W){let Z={manifest:[],handlers:new Map};for(let J of Object.keys(W.toolExecutors??{}).filter(Ab)){let j=W.toolExecutors?.[J];if(typeof j!=="function")continue;s2(Z,{kind:"toolExecutor",executor:J,capabilityName:`${Kb}${J}`},async({payload:X,abortSignal:Y})=>{let V=Array.isArray(X.args)?[...X.args]:[],B={...nA(X.context),signal:Y};return{result:await j(...V,B)}})}for(let J of $?.extraTools??[])s2(Z,{kind:"tool",name:J.name,description:J.description,inputSchema:E6(J.inputSchema)??{},...J.lifecycle?{lifecycle:E6(J.lifecycle)}:{},capabilityName:`${Bb}${J.name}`},async({payload:j,abortSignal:X,progress:Y})=>{let V={...nA(j.context),signal:X};return{result:await J.execute(j.input,{...V,emitUpdate:(H)=>{Y({update:H})}})}});let Q=$?.hooks;if(Q)for(let J of Ub){let j=Q[J];if(typeof j!=="function")continue;s2(Z,{kind:"hook",name:J,capabilityName:`${Hb}${J}`},async({payload:X})=>({control:await j(X.context)}))}if($?.compaction?.compact){let J=$.compaction.compact;s2(Z,{kind:"compaction",capabilityName:Vb,config:pA($.compaction)},async({payload:j})=>({result:await J(j.context)}))}if($?.checkpoint?.createCheckpoint){let J=$.checkpoint.createCheckpoint;s2(Z,{kind:"checkpoint",capabilityName:Yb,config:pA($.checkpoint)},async({payload:j})=>({result:await J(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let J=$.onConsecutiveMistakeLimitReached;s2(Z,{kind:"mistakeLimit",capabilityName:Gb},async({payload:j})=>({result:await J(j.context)}))}if($?.userInstructionService){let J=$.userInstructionService;s2(Z,{kind:"userInstructionService",capabilityName:Fb},async()=>{return await J.start().catch(()=>{}),{snapshot:{records:{skill:J.listRecords("skill"),rule:J.listRecords("rule"),workflow:J.listRecords("workflow")},runtimeCommands:J.listRuntimeCommands()}}})}return Z}function eA($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let W=$.message;if(typeof W==="string"&&W.trim())return W.trim()}return}function Db($){return eA($)??"Capability request was cancelled."}function _b($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function fb($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function Lb($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=typeof W.inputTokens==="number"?W.inputTokens:void 0,Q=typeof W.outputTokens==="number"?W.outputTokens:void 0;if(Z===void 0||Q===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:typeof W.cacheReadTokens==="number"?W.cacheReadTokens:0,cacheWriteTokens:typeof W.cacheWriteTokens==="number"?W.cacheWriteTokens:0,totalCost:typeof W.totalCost==="number"?W.totalCost:0}}function oA($){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 bj($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function r$($,W){return bj($?.[W])??0}function Tb($){let W=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Z=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,J=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:r$(W,"inputTokens"),outputTokens:r$(W,"outputTokens"),cacheReadTokens:r$(W,"cacheReadTokens"),cacheWriteTokens:r$(W,"cacheWriteTokens"),cost:bj(W?.totalCost),totalInputTokens:r$(Z,"inputTokens"),totalOutputTokens:r$(Z,"outputTokens"),totalCacheReadTokens:r$(Z,"cacheReadTokens"),totalCacheWriteTokens:r$(Z,"cacheWriteTokens"),totalCost:bj(Z?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:J}}function Ob($){let W=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Z=$?.reason??W?.finishReason,Q=fb(Z)?Z:Z==="failed"?"error":"completed",J=Lb($?.usage??W?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof W?.text==="string"?W.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof W?.iterations==="number"?W.iterations:0,usage:J}}function t2($,W){return $.error?.message??`hub command failed: ${W}`}function J9($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function $U($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof W?.parentSessionId==="string"?W.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof W?.agentId==="string"?W.agentId:void 0),parentAgentId:typeof W?.parentAgentId==="string"?W.parentAgentId:void 0,conversationId:typeof W?.conversationId==="string"?W.conversationId:void 0,isSubagent:typeof W?.isSubagent==="boolean"?W.isSubagent:!1,source:typeof W?.source==="string"?W.source:F0.CORE,pid:typeof W?.pid==="number"?W.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:J9($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:J9($.status)==="completed"?0:J9($.status)==="failed"?1:void 0,status:J9($.status),interactive:W?.interactive===!0,provider:typeof W?.provider==="string"?W.provider:"hub",model:typeof W?.model==="string"?W.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof W?.teamName==="string"?W.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??W?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??W?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??W?.enableTeams===!0,prompt:typeof W?.prompt==="string"?W.prompt:void 0,metadata:W,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof W?.messagesPath==="string"?W.messagesPath:void 0,hookPath:typeof W?.hookPath==="string"?W.hookPath:void 0}}function i$($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$;return W.version===1&&typeof W.sessionId==="string"?JSON.parse(JSON.stringify(W)):void 0}function zb($){let W=i$($?.snapshot);if(W)return zQ(W);let Z=$?.session;return Z?$U(Z):void 0}function sA($,W,Z){let Q=Z?.workspaceRoot?.trim()||W.config.workspaceRoot||W.config.cwd;return m0.parse({version:1,session_id:$,source:W.source??F0.CORE,pid:process.pid,started_at:new Date(Z?.createdAt??Date.now()).toISOString(),status:J9(Z?.status),interactive:W.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:Z?.cwd?.trim()||W.config.cwd,workspace_root:Q,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,metadata:W.sessionMetadata&&Object.keys(W.sessionMetadata).length>0?W.sessionMetadata:void 0})}function tA($,W){return m0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??W.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class Y${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new Z9;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,W){this.clientContext=W,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd},this.defaultCapabilities=P0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Z)=>this.requestPendingPromptsList(Z),update:(Z)=>this.requestPendingPromptUpdate(Z),delete:(Z)=>this.requestPendingPromptDelete(Z)},this.client=this.createClient($.url)}createClient($){return new B1({...this.clientOptions,url:$})}async replaceClient($){let W=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(W.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!wW($,"session.create"))return!1;let W=await CW({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!W)return!1;return await this.replaceClient(W),!0}registerPlannedSession($,W,Z){if(this.sessionCapabilities.set($,W),Z.size>0)this.sessionClientContributionHandlers.set($,Z);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let W=this.resolveCapabilities($),Z=aA($.localRuntime,W),Q=$.config.sessionId?.trim()||lA(),J=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:E6(iA($,Q)),metadata:{...$.sessionMetadata??{},source:$.source??F0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Z.manifest.length>0?{clientContributions:Z.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:E6($.toolPolicies),initialMessages:$.initialMessages,...$.initialCompactionState?{initialCompactionState:$.initialCompactionState}:{}});this.registerPlannedSession(Q,W,Z.handlers);let j;try{j=await J()}catch(B){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(B)){this.registerPlannedSession(Q,W,Z.handlers);try{j=await J()}catch(H){throw this.cleanupPlannedSession(Q),H}}else throw B}let X=i$(j.payload?.snapshot),Y=j.payload?.session,V=(X?.sessionId??Y?.sessionId)?.trim();if(!V)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(V!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(V,W,Z.handlers);return{sessionId:V,manifest:X?tA(X,$):sA(V,$,Y),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,J=Q?this.resolveCapabilities(Q):void 0,j=Q?aA(Q.localRuntime,J??{}):{manifest:[],handlers:new Map},X,Y;if(Q)X=Q.config.sessionId?.trim()||lA(),Y=iA(Q,X);if(X&&J)this.sessionCapabilities.set(X,J);if(X&&j.handlers.size>0)this.sessionClientContributionHandlers.set(X,j.handlers),this.ensureSessionSubscription(X);let V;try{V=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:E6(Y),metadata:{...Q.sessionMetadata??{},source:Q.source??F0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:E6(Q.toolPolicies),...Q.initialCompactionState?{initialCompactionState:Q.initialCompactionState}:{}}:{}},W)}catch(A){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw A}if(!V.ok){let A=typeof V.payload?.error==="string"?V.payload.error:"session.restore failed";if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error(A)}let B=i$(V.payload?.snapshot),H=V.payload?.session,G=(B?.sessionId??H?.sessionId)?.trim();if(Z&&!G){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error("Hub checkpoint restore returned no session id")}if(G&&X&&G!==X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);if(G&&J)this.sessionCapabilities.set(G,J);if(G&&j.handlers.size>0)this.sessionClientContributionHandlers.set(G,j.handlers);if(G)this.ensureSessionSubscription(G);let K=Array.isArray(V.payload?.messages)?V.payload.messages:void 0,F=V.payload?.checkpoint;if(!F)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:G,startResult:G?{sessionId:G,manifest:B?tA(B,Q??{}):sA(G,Q??{},H),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:K,checkpoint:F}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(W.payload?.prompts)?W.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,updated:W.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,removed:W.payload?.removed===!0}}async getAccumulatedUsage($){let W=await this.client.command("session.get",{includeSnapshot:!0},$),Z=i$(W.payload?.snapshot);if(Z){let X=Z.usage?{...Z.usage}:void 0,Y=Z.aggregateUsage?{...Z.aggregateUsage}:void 0;return X||Y?{usage:X,aggregateUsage:Y}:void 0}let Q=W.payload?.session,J=oA(Q?.usage),j=oA(Q?.aggregateUsage);return J||j?{usage:J,aggregateUsage:j}:void 0}async abort($,W){await this.client.command("run.abort",{sessionId:$,reason:eA(W)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,W]of this.sessionSubscriptions){W();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(p1(Z))return;throw Z}return zb(W.payload)}async listSessions($=100){let W=await this.client.command("session.list",{limit:$}),Z=Array.isArray(W.payload?.snapshots)?W.payload.snapshots.flatMap((J)=>{let j=i$(J);return j?[zQ(j)]:[]}):[];if(Z.length>0)return Z;return(W.payload?.sessions??[]).map($U)}async listSettings($){let W=await this.client.command("settings.list",rA($));if(!W.ok)throw Error(t2(W,"settings.list"));return W.payload?.snapshot}async toggleSetting($){let W=await this.client.command("settings.toggle",rA($));if(!W.ok)throw Error(t2(W,"settings.toggle"));return{snapshot:W.payload?.snapshot,changedTypes:Array.isArray(W.payload?.changedTypes)?W.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,W){let Z={...W.metadata??{}};if(typeof W.prompt==="string")Z.prompt=W.prompt;if(typeof W.title==="string")Z.title=W.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Z})).ok}}async updateSessionConnection($,W){let Z=$.trim();if(!Z)return;let Q=await this.client.command("session.update_connection",{sessionId:Z,updates:W},Z);if(!Q.ok)throw Error(t2(Q,"session.update_connection"))}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=await this.client.command("session.compaction.update",{sessionId:Z,state:W},Z);if(!Q.ok)Sj(this.telemetry,{component:"core",operation:"hub.runtime_host.update_session_compaction_state",error:Error(t2(Q,"session.compaction.update")),severity:"warn",handled:!0,context:{command:"session.compaction.update",sessionId:Z,errorCode:Q.error?.code}});return{updated:Q.ok&&Q.payload?.updated===!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=await this.client.command("session.compaction.get",{sessionId:W},W);if(!Z.ok)throw Error(t2(Z,"session.compaction.get"));return G1(Z.payload?.state)}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Sj(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(t2(Z,"session.messages")),severity:Z.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:W,errorCode:Z.error?.code,runtimeAddress:this.runtimeAddress}}),Error(t2(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,W){return this.events.subscribe($,W)}ensureSessionSubscription($){let W=$.trim();if(!W||this.sessionSubscriptions.has(W))return;let Z=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:W});this.sessionSubscriptions.set(W,typeof Z==="function"?Z:()=>{})}disposeSessionSubscription($){let W=$.trim();if(!W)return;this.sessionSubscriptions.get(W)?.(),this.sessionSubscriptions.delete(W),this.agentDoneEmittedForCurrentRunBySession.delete(W)}resolveCapabilities($){return P0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:Ob($.payload)}})}handleHubEvent($){let W=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Z,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Z,$)});return}if(!W)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(W);let Z=i$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"session.notice":{let Z=$.payload?.noticeType,Q=$.payload?.displayRole,J=$.payload?.reason,j=$.payload?.agent&&typeof $.payload.agent==="object"?$.payload.agent:void 0,X=j?.teamRole==="lead"||j?.teamRole==="teammate"?j.teamRole:void 0;this.events.emit({type:"agent_event",payload:{sessionId:W,...X?{teamRole:X}:{},...typeof j?.teamAgentId==="string"?{teamAgentId:j.teamAgentId}:{},event:{type:"notice",...typeof j?.agentId==="string"?{agentId:j.agentId}:{},...typeof j?.conversationId==="string"?{conversationId:j.conversationId}:{},...typeof j?.parentAgentId==="string"?{parentAgentId:j.parentAgentId}:{},noticeType:Z==="recovery"||Z==="stop"?Z:"status",message:typeof $.payload?.message==="string"?$.payload.message:"",...Q==="system"||Q==="status"?{displayRole:Q}:{},...typeof J==="string"?{reason:J}:{},...$.payload?.metadata&&typeof $.payload.metadata==="object"?{metadata:$.payload.metadata}:{}}}});return}case"assistant.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"";if(!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"text",text:Z}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!Z&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"reasoning",reasoning:Z,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:W,payload:$.payload});return}case"usage.updated":{let Z=Tb($.payload);this.events.emit({type:"agent_event",payload:{sessionId:W,event:Z.event,teamAgentId:Z.teamAgentId,teamRole:Z.teamRole}});return}case"tool.started":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z&&this.pendingApprovalToolCallIds.delete(Z))return;this.emitToolCallContentStart({sessionId:W,toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z)this.pendingApprovalToolCallIds.delete(Z);this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"tool",toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Z=i$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:W,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Z=$.payload?.prompt;if(!Z)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:W,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}});return}case"run.completed":case"run.failed":case"run.aborted":{let Z=i$($.payload?.snapshot),Q=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:W,payload:{...$.payload,reason:Q}}),Z?.interactive===!0&&K0(Z.status))return;this.events.emit({type:"ended",payload:{sessionId:W,reason:Q,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,W,Z){try{Sj(this.telemetry,{component:"core",operation:$,error:W,severity:"warn",handled:!0,context:{event:Z.event,sessionId:Z.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let W=$.sessionId?.trim();if(!W)return;let Z=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Z&&Z!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",J=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let j=this.sessionClientContributionHandlers.get(W)?.get(J);if(!j){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${J} in session ${W}.`},W).catch(()=>{});return}let X=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},Y=new AbortController;this.activeCapabilityAbortControllers.set(Q,Y);let V=(B)=>{this.client.command("capability.progress",{requestId:Q,payload:B},W).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let B=await j({payload:X,abortSignal:Y.signal,progress:V});if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:B},W)}catch(B){if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:B instanceof Error?B.message:String(B)},W)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let W=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!W)return;let Z=this.activeCapabilityAbortControllers.get(W);if(!Z)return;Z.abort(Db($.payload.error))}async handleApprovalRequested($){let W=$.sessionId?.trim();if(!W)return;let Z=this.sessionCapabilities.get(W)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Z)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!J||!j)return;let X=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},Y=_b($.payload?.inputJson);this.pendingApprovalToolCallIds.add(J),this.emitToolCallContentStart({sessionId:W,toolCallId:J,toolName:j,toolInput:Y});let V=await Promise.resolve(Z({sessionId:W,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:W,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:J,toolName:j,input:Y,policy:X})).catch((B)=>({approved:!1,reason:B instanceof Error?B.message:`Tool approval request failed: ${String(B)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:V.approved,reason:V.reason},W).catch(()=>{})}}var ZU={};w(ZU,{RemoteRuntimeHost:()=>N6});class N6 extends Y${constructor($){super({url:z$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var QU={};w(QU,{SqliteSessionStore:()=>C1});import{existsSync as qb,mkdirSync as Mb}from"node:fs";import{join as Rb}from"node:path";import{asBool as j9,asOptionalString as w1,asString as V$,ensureSessionSchema as Eb,loadSqliteDb as Nb,nowIso as qQ,toBoolInt as X9}from"@cline/shared/db";import{resolveDbDataDir as wb}from"@cline/shared/storage";class C1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??wb()}init(){this.getRawDb()}ensureSessionsDir(){if(!qb(this.sessionsDirPath))Mb(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return Rb(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=Nb(this.sessionDbPath());return Eb($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}create($){let W=qQ();this.run(`INSERT OR REPLACE INTO sessions (
508
508
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
509
509
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
510
510
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
511
511
  metadata_json, transcript_path, hook_path, messages_path, updated_at
512
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,X9($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,X9($.enableTools),X9($.enableSpawn),X9($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,X9($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,W])}update($){let W=[],Z=[];if($.endedAt!==void 0)W.push("ended_at = ?"),Z.push($.endedAt);if($.exitCode!==void 0)W.push("exit_code = ?"),Z.push($.exitCode);if($.status!==void 0)W.push("status = ?"),Z.push($.status);if($.prompt!==void 0)W.push("prompt = ?"),Z.push($.prompt);if($.metadata!==void 0)W.push("metadata_json = ?"),Z.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)W.push("parent_session_id = ?"),Z.push($.parentSessionId);if($.parentAgentId!==void 0)W.push("parent_agent_id = ?"),Z.push($.parentAgentId);if($.agentId!==void 0)W.push("agent_id = ?"),Z.push($.agentId);if($.conversationId!==void 0)W.push("conversation_id = ?"),Z.push($.conversationId);if(W.length===0)return;W.push("updated_at = ?"),Z.push(zQ()),Z.push($.sessionId),this.run(`UPDATE sessions SET ${W.join(", ")} WHERE session_id = ?`,Z)}updateStatus($,W,Z){this.update({sessionId:$,status:W,endedAt:K0(W)?null:zQ(),exitCode:K0(W)?null:Z??(W==="failed"?1:0)})}get($){let W=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
512
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,X9($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,X9($.enableTools),X9($.enableSpawn),X9($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,X9($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,W])}update($){let W=[],Z=[];if($.endedAt!==void 0)W.push("ended_at = ?"),Z.push($.endedAt);if($.exitCode!==void 0)W.push("exit_code = ?"),Z.push($.exitCode);if($.status!==void 0)W.push("status = ?"),Z.push($.status);if($.prompt!==void 0)W.push("prompt = ?"),Z.push($.prompt);if($.metadata!==void 0)W.push("metadata_json = ?"),Z.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)W.push("parent_session_id = ?"),Z.push($.parentSessionId);if($.parentAgentId!==void 0)W.push("parent_agent_id = ?"),Z.push($.parentAgentId);if($.agentId!==void 0)W.push("agent_id = ?"),Z.push($.agentId);if($.conversationId!==void 0)W.push("conversation_id = ?"),Z.push($.conversationId);if(W.length===0)return;W.push("updated_at = ?"),Z.push(qQ()),Z.push($.sessionId),this.run(`UPDATE sessions SET ${W.join(", ")} WHERE session_id = ?`,Z)}updateStatus($,W,Z){this.update({sessionId:$,status:W,endedAt:K0(W)?null:qQ(),exitCode:K0(W)?null:Z??(W==="failed"?1:0)})}get($){let W=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
513
513
  provider, model, cwd, workspace_root, team_name,
514
514
  enable_tools, enable_spawn, enable_teams,
515
515
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
516
516
  prompt, metadata_json, hook_path, messages_path, updated_at
517
- FROM sessions WHERE session_id = ?`,[$]);if(!W)return;return{sessionId:V$(W.session_id),source:V$(W.source),pid:Number(W.pid??0),startedAt:V$(W.started_at),endedAt:W.ended_at??null,exitCode:W.exit_code??null,status:V$(W.status),interactive:j9(W.interactive),provider:V$(W.provider),model:V$(W.model),cwd:V$(W.cwd),workspaceRoot:V$(W.workspace_root),teamName:w1(W.team_name),enableTools:j9(W.enable_tools),enableSpawn:j9(W.enable_spawn),enableTeams:j9(W.enable_teams),parentSessionId:w1(W.parent_session_id),parentAgentId:w1(W.parent_agent_id),agentId:w1(W.agent_id),conversationId:w1(W.conversation_id),isSubagent:j9(W.is_subagent),prompt:w1(W.prompt),metadata:(()=>{let Z=w1(W.metadata_json);if(!Z)return;try{let Q=JSON.parse(Z);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:w1(W.hook_path),messagesPath:w1(W.messages_path),updatedAt:w1(W.updated_at)??zQ()}}list($=200){let W=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Z=[];for(let Q of W){let J=this.get(V$(Q.session_id));if(J)Z.push(J)}return Z}delete($,W=!1){let Z=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(W)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Z>0}}O8();import{existsSync as lj,mkdirSync as Ay,readFileSync as zU,renameSync as Uy,writeFileSync as Dy}from"node:fs";import{join as qU}from"node:path";import{resolveSessionDataDir as _y}from"@cline/shared/storage";import{dirname as Ky}from"node:path";import{nanoid as Fy}from"nanoid";import{appendFileSync as yb,existsSync as hb,mkdirSync as XU,readFileSync as kb,writeFileSync as YU}from"node:fs";import{readFile as VU,rm as Ib}from"node:fs/promises";import{dirname as BU,join as xb}from"node:path";import{ensureHookLogDir as gb}from"@cline/shared/storage";import{randomUUID as wb}from"node:crypto";import{mkdir as Cb,open as JU,rename as Pb,rm as Sb}from"node:fs/promises";import{dirname as QU}from"node:path";async function bb($){let W;try{W=await JU($,"r"),await W.sync()}catch{}finally{if(W!==void 0)try{await W.close()}catch{}}}async function jU($,W){await Cb(QU($),{recursive:!0});let Z=`${$}.${process.pid}.${wb()}.tmp`,Q;try{Q=await JU(Z,"wx"),await Q.writeFile(W,"utf8"),await Q.sync(),await Q.close(),Q=void 0,await Pb(Z,$),await bb(QU($))}catch(J){if(Q!==void 0)try{await Q.close()}catch{}try{await Sb(Z,{force:!0})}catch{}throw J}}function mb($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}class bj{adapter;messagesArtifactUploader;logger;artifacts;constructor($,W,Z){this.adapter=$;this.messagesArtifactUploader=W;this.logger=Z;this.artifacts=new tJ(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,W,Z){FK(W,Z,_J($))}writeSessionManifest($,W){XU(BU($),{recursive:!0}),YU($,`${JSON.stringify(m0.parse(W),null,2)}
518
- `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}async readSessionManifestTitle($){let W=this.artifacts.sessionManifestPath($,!1),Z;try{Z=await VU(W,"utf8")}catch{return}try{let Q=JSON.parse(Z);if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J=Q.metadata;if(!J||typeof J!=="object"||Array.isArray(J))return;let j=J.title;return typeof j==="string"?j:void 0}catch{return}}readManifestFile($){let W=this.artifacts.sessionManifestPath($,!1);if(!hb(W))return{path:W};try{return{path:W,manifest:m0.parse(JSON.parse(kb(W,"utf8")))}}catch{return{path:W}}}async resolveArtifactPath($,W,Z){let J=(await this.adapter.getSession($))?.[W];return typeof J==="string"&&J.trim().length>0?J:Z($)}async persistSessionMessages($,W,Z){let Q=await this.resolveArtifactPath($,"messagesPath",(X)=>this.artifacts.sessionMessagesPath(X)),J=fJ({updatedAt:X0(),context:_J($),messages:W,systemPrompt:Z}),j=`${JSON.stringify(J,null,2)}
519
- `;if(XU(BU(Q),{recursive:!0}),YU(Q,j,"utf8"),!this.messagesArtifactUploader)return;try{let X=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Q,contents:j,row:X})}catch(X){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:X})}}resolveCompactionPath($){let{manifest:W}=this.readManifestFile($);return W?.compaction_path?.trim()||this.artifacts.sessionCompactionPath($)}updateCompactionPath($,W){let Z=this.readManifestFile($);if(!Z.manifest)return;if(Z.manifest.compaction_path===W)return;this.writeSessionManifest(Z.path,{...Z.manifest,compaction_path:W})}async readSessionCompactionState($){let W=this.resolveCompactionPath($);try{return G1(JSON.parse(await VU(W,"utf8")))}catch(Z){if(mb(Z))return;this.logger?.debug("Ignoring invalid session compaction state",{sessionId:$,path:W,error:Z,recovery:"Canonical history is unchanged; deleting the sidecar is safe."});return}}async persistSessionCompactionState($,W){let Z=this.resolveCompactionPath($),Q=S4.parse(W);await jU(Z,`${JSON.stringify(Q,null,2)}
520
- `),this.updateCompactionPath($,Z)}async deleteSessionCompactionState($){await Ib(this.resolveCompactionPath($),{force:!0}),this.updateCompactionPath($,void 0)}appendStaleSessionHookLog($,W,Z,Q,J){let X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??xb(gb(),"hooks.jsonl");yb(X,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Q,sessionId:W,pid:Z,source:J})}
521
- `,"utf8")}}import{appendFileSync as vb}from"node:fs";import{join as cb}from"node:path";import{resolveRootSessionId as HU}from"@cline/shared";import{ensureHookLogDir as ub}from"@cline/shared/storage";import{z as yj}from"zod";var db="subagent",lb=yj.looseObject({task:yj.string().optional(),systemPrompt:yj.string().optional()});class qQ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,W,Z,Q){this.adapter=$;this.manifestStore=W;this.toPersistedMessages=Z;this.heartbeatLogIntervalMs=Q}teamTaskQueueKey($,W){return`${$}::${W}`}activeTeamTaskSessionId($,W){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,W))?.at(-1)}buildSubsessionRow($,W){return{sessionId:W.sessionId,source:db,pid:process.ppid,startedAt:W.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:W.parentSessionId,parentAgentId:W.parentAgentId,agentId:W.agentId,conversationId:W.conversationId??null,isSubagent:!0,prompt:W.prompt,metadata:G5({prompt:W.prompt}),hookPath:"",messagesPath:W.messagesPath,updatedAt:W.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let W=HU($.sessionContext);if(!W)return;let Z=lb.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:W,parentAgentId:$.agent_id,task:Z.success?Z.data.task:void 0,systemPrompt:Z.success?Z.data.systemPrompt:void 0})}async upsertSubagentSession($){let W=$.rootSessionId;if(!W)return;let Z=await this.adapter.getSession(W);if(!Z)return;let Q=s8(W,$.agentId),J=await this.adapter.getSession(Q),j=X0(),X=this.manifestStore.artifacts.subagentArtifactPaths(Q,$.agentId,this.activeTeamTaskSessionId(W,$.parentAgentId)),Y=$.prompt??J?.prompt??void 0;if(!Y)Y=await this.adapter.claimSpawnRequest(W,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!J)return await this.adapter.upsertSession(this.buildSubsessionRow(Z,{sessionId:Q,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Y,startedAt:j,...X})),this.manifestStore.initializeMessagesFile(Q,X.messagesPath,j),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:J.prompt??Y??null,metadata:G5({metadata:J.metadata??void 0,prompt:J.prompt??Y??null}),expectedStatusLock:J.statusLock}),Q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let W=HU($.sessionContext);if(!W)return;if($.hookName==="session_shutdown"){let Z=s8(W,$.agent_id);return await this.adapter.getSession(Z)?Z:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:W})}async applySubagentStatus($,W){await this.applySubagentStatusBySessionId($,V5(W))}async applySubagentStatusBySessionId($,W){let Z=await this.adapter.getSession($);if(!Z)return;let Q=K0(W)?null:X0(),J=K0(W)?null:W==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:W,endedAt:Q,exitCode:J,expectedStatusLock:Z.statusLock})}async applyStatusToRunningChildSessions($,W){if(!$)return;let Z=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Q of Z)await this.applySubagentStatusBySessionId(Q.sessionId,W)}async onTeamTaskStart($,W,Z){let Q=await this.adapter.getSession($);if(!Q)return;let J=X5($,W),j=X0(),{messagesPath:X}=this.manifestStore.artifacts.subagentArtifactPaths(J,W);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:J,parentSessionId:$,parentAgentId:"lead",agentId:W,prompt:Z||`Team task for ${W}`,startedAt:j,messagesPath:X})),this.manifestStore.initializeMessagesFile(J,X,j);let Y=this.teamTaskQueueKey($,W),V=this.teamTaskSessionsByAgent.get(Y)??[];V.push(J),this.teamTaskSessionsByAgent.set(Y,V)}async onTeamTaskEnd($,W,Z,Q,J,j){let X=this.teamTaskQueueKey($,W),Y=this.teamTaskSessionsByAgent.get(X);if(!Y||Y.length===0)return;let V=Y.shift();if(Y.length===0)this.teamTaskSessionsByAgent.delete(X);if(!V)return;let B=J?.messages??j,H=this.toPersistedMessages(B,J,j);if(H)await this.manifestStore.persistSessionMessages(V,H);await this.applySubagentStatusBySessionId(V,Z),this.teamTaskLastHeartbeatBySession.delete(V),this.teamTaskLastProgressLineBySession.delete(V)}async onTeamTaskProgress($,W,Z,Q){let J=this.teamTaskQueueKey($,W),j=this.teamTaskSessionsByAgent.get(J)?.[0];if(!j)return;let X=Z.trim();if(!X)return;let Y=Q?.kind??"progress";if(Y==="heartbeat"){let B=Date.now(),H=this.teamTaskLastHeartbeatBySession.get(j)??0;if(B-H<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(j,B)}let V=Y==="heartbeat"?"[progress] heartbeat":Y==="text"?`[progress] text: ${X}`:`[progress] ${X}`;if(this.teamTaskLastProgressLineBySession.get(j)===V)return;this.teamTaskLastProgressLineBySession.set(j,V)}async handleSubAgentStart($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;await this.applySubagentStatusBySessionId(Z,"running")}async handleSubAgentEnd($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;if(W.error){await this.applySubagentStatusBySessionId(Z,"failed");return}let Q=this.toPersistedMessages(W.agentResult?.messages,W.agentResult);if(Q)await this.manifestStore.persistSessionMessages(Z,Q);let J=W.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Z,J==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??cb(ub(),"hooks.jsonl");vb(Z,`${JSON.stringify({ts:X0(),...$})}
522
- `,"utf8")}}import{formatUserInputBlock as Gy}from"@cline/shared";var OU={};w(OU,{toTeamProgressLifecycleEvent:()=>S6,sanitizeTeamName:()=>QK,reviveTeamStateDates:()=>GZ,parseConfiguredAgentConfig:()=>Y9,loadConfiguredAgentConfigs:()=>w6,createWorkerReviewerTeam:()=>TU,createSpawnAgentTool:()=>y$,createDelegatedAgentConfigProvider:()=>S$,createDelegatedAgent:()=>b$,createConfiguredAgentTools:()=>C6,createAgentTeamsTools:()=>S2,createAgentTeam:()=>Ij,buildTeamProgressSummary:()=>P6,buildDelegatedAgentConfig:()=>C2,buildConfiguredAgentToolName:()=>V9,buildConfiguredAgentToolDescriptors:()=>B9,bootstrapAgentTeams:()=>o8,AgentTeamsRuntime:()=>e2,AgentTeam:()=>y6});import{existsSync as pb,readdirSync as rb,readFileSync as ib}from"node:fs";import{basename as GU,extname as nb,join as ab}from"node:path";import{resolveAgentConfigSearchPaths as ob}from"@cline/shared/storage";import FU from"yaml";import{z as h0}from"zod";var AU=h0.object({name:h0.string().trim().min(1),description:h0.string().trim().min(1),tools:h0.union([h0.string(),h0.array(h0.string())]).optional(),skills:h0.union([h0.string(),h0.array(h0.string())]).optional(),providerId:h0.string().trim().min(1).optional(),modelId:h0.string().trim().min(1).optional(),maxIterations:h0.number().int().positive().optional()});function sb($){let W=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!W)throw Error("Missing YAML frontmatter block in agent config file.");let Z=W[0].length,Q=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Q.lastIndex=Z;let J,j=Array.from($.matchAll(Q)).filter((X)=>X.index>=Z);for(let X of j){let Y=X.index,V=$.slice(Z,Y);try{let B=FU.parse(V);if(!B||typeof B!=="object"||Array.isArray(B))continue;AU.parse(B);let H=$.slice(Y+X[0].length);J={frontmatter:V,body:H}}catch{}}if(J)return J;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function KU($){if($===void 0)return;let W=Array.isArray($)?$:$.split(",");return Array.from(new Set(W.map((Z)=>Z.trim()).filter((Z)=>Z.length>0)))}function tb($){return $.trim().toLowerCase()}function eb($){let W=nb($).toLowerCase();return W===".yml"||W===".yaml"}function Y9($,W={}){let{frontmatter:Z,body:Q}=sb($),J=FU.parse(Z);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Agent config frontmatter must be a YAML mapping.");let j=AU.parse(J),X=Q.trim();if(!X)throw Error("Missing system prompt body in agent config file.");return{name:j.name,description:j.description,tools:KU(j.tools),skills:KU(j.skills),providerId:j.providerId,modelId:j.modelId,maxIterations:j.maxIterations,systemPrompt:X,path:W.path}}function w6($){let W=$.searchPaths??ob($.workspaceRoot),Z=new Map,Q=[];for(let j of W.filter(Boolean)){if(!pb(j))continue;let X;try{X=rb(j,{withFileTypes:!0})}catch(Y){Q.push({path:j,error:Y instanceof Error?Y:Error(String(Y))});continue}for(let Y of X){if(!Y.isFile()||!eb(Y.name))continue;let V=ab(j,Y.name);try{let B=ib(V,"utf8"),H=Y9(B,{path:V}),G=tb(H.name);if(!Z.has(G))Z.set(G,H)}catch(B){Q.push({path:V,error:B instanceof Error?B:Error(String(B))})}}}return{configs:Array.from(Z.values()).sort((j,X)=>(j.path?GU(j.path):j.name).localeCompare(X.path?GU(X.path):X.name)),errors:Q}}import{createTool as $y,zodToJsonSchema as Wy}from"@cline/shared";import{z as UU}from"zod";var hj="subagent_",MQ=64,Zy=UU.object({prompt:UU.string().trim().min(1).describe("Task for the subagent to perform")});function Qy($){let W="",Z=!0;for(let Q of $.trim().toLowerCase()){let J=Q.charCodeAt(0);if(!(J>=97&&J<=122||J>=48&&J<=57||Q==="_")||Q==="_"){if(!Z)W+="_",Z=!0;continue}W+=Q,Z=!1}return Z?W.slice(0,-1):W}function Jy($){let W=2166136261;for(let Z=0;Z<$.length;Z++)W^=$.charCodeAt(Z),W=Math.imul(W,16777619);return(W>>>0).toString(36)}function V9($){let W=Qy($)||"agent",Z=Jy($).slice(0,6),Q=`${hj}${W}`;if(Q.length<=MQ)return Q;let J=MQ-hj.length-Z.length-1,j=W.slice(0,Math.max(1,J));return`${hj}${j}_${Z}`.slice(0,MQ)}function B9($){let W=new Set,Z=[];for(let Q of[...$].sort((J,j)=>J.name.localeCompare(j.name))){let J=V9(Q.name),j=J,X=2;while(W.has(j)){let Y=`_${X++}`,V=Math.max(1,MQ-Y.length);j=`${J.slice(0,V)}${Y}`}W.add(j),Z.push({toolName:j,config:Q})}return Z}function jy($,W){return{...$,providerId:W.providerId??$.providerId,modelId:W.modelId??$.modelId,maxIterations:W.maxIterations??$.maxIterations}}function C6($){return B9($.agents).map(({toolName:W,config:Z})=>{return $y({name:W,description:`Use the "${Z.name}" subagent: ${Z.description}`,inputSchema:Wy(Zy),execute:async(J,j)=>{let X=$.configProvider.getRuntimeConfig(),Y=S$(jy(X,Z)),V=$.createSubAgentTools?await $.createSubAgentTools(Z,J,j):[],B=b$({kind:"subagent",prompt:Z.systemPrompt,configProvider:Y,tools:V,maxIterations:Z.maxIterations,parentAgentId:j.agentId,abortSignal:j.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),H=B.getAgentId(),G=B.getConversationId(),K=j.agentId,F={systemPrompt:Z.systemPrompt,task:J.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:H,conversationId:G,parentAgentId:K,input:F})}catch{}try{let A=await B.run(J.prompt),D={text:A.text,iterations:A.iterations,finishReason:A.finishReason,usage:{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,result:D,agentResult:A})}catch{}return D}catch(A){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,error:A instanceof Error?A:Error(String(A))})}catch{}throw A}},timeoutMs:300000,retryable:!1})})}function P1(){return new Date().toISOString()}function DU($,W){if(W<=0)return 0;return Math.round($/W*100)}function Xy($,W){let Z=new Set;for(let J of W)if(J.status==="reviewed")Z.add(`${J.outcomeId}:${J.section}`);let Q=new Set;for(let J of $){if(J.status==="finalized")continue;for(let j of J.requiredSections)if(!Z.has(`${J.id}:${j}`))Q.add(`${J.id}:${j}`)}return[...Q].sort((J,j)=>J.localeCompare(j))}function P6($,W){let Z={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},J={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},j={draft:0,in_review:0,finalized:0},X={draft:0,reviewed:0,rejected:0},Y=0,V=0;for(let U of W.members)if(Z[U.status]+=1,U.role==="lead")Y+=1;else V+=1;let B=[],H=[],G=W.tasks.filter((U)=>U.status==="completed").length,K=new Map(W.tasks.map((U)=>[U.id,U]));for(let U of W.tasks){if(Q[U.status]+=1,U.status==="blocked"){B.push(U.id);continue}if(U.status!=="pending")continue;if(U.dependsOn.every((_)=>{return K.get(_)?.status==="completed"}))H.push(U.id)}let F=[],A,D=0;for(let U of W.runs){if(J[U.status]+=1,U.status==="queued"||U.status==="running")F.push(U.id);let f=U.startedAt.getTime();if(f>=D)D=f,A=U.id}for(let U of W.outcomes)j[U.status]+=1;for(let U of W.outcomeFragments)X[U.status]+=1;return{teamName:$,updatedAt:P1(),members:{total:W.members.length,byStatus:Z,leadCount:Y,teammateCount:V},tasks:{total:W.tasks.length,byStatus:Q,blockedTaskIds:B,readyTaskIds:H,completionPct:DU(G,W.tasks.length)},runs:{total:W.runs.length,byStatus:J,activeRunIds:F,latestRunId:A},outcomes:{total:W.outcomes.length,byStatus:j,finalizedPct:DU(j.finalized,W.outcomes.length),missingRequiredSections:Xy(W.outcomes,W.outcomeFragments)},fragments:{total:W.outcomeFragments.length,byStatus:X}}}function S6($){let{event:W}=$;switch(W.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.task.id,agentId:W.task.assignee??W.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),outcomeId:W.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),outcomeId:W.fragment.outcomeId,fragmentId:W.fragment.id,agentId:W.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.message.taskId,agentId:W.message.fromAgentId,message:W.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.entry.taskId,agentId:W.entry.agentId,message:W.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),agentId:W.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1()}}import{sanitizeFileName as Yy,TeamMessageType as m}from"@cline/shared";import{nanoid as Vy}from"nanoid";import{TeamMessageType as Zs}from"@cline/shared";function kj($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function _U($,W){return $?.status==="stopped"&&kj(W)}var By=600000,fU="recovered_queued";function Hy($){return`This is an automatic recovery of interrupted team run ${$.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
517
+ FROM sessions WHERE session_id = ?`,[$]);if(!W)return;return{sessionId:V$(W.session_id),source:V$(W.source),pid:Number(W.pid??0),startedAt:V$(W.started_at),endedAt:W.ended_at??null,exitCode:W.exit_code??null,status:V$(W.status),interactive:j9(W.interactive),provider:V$(W.provider),model:V$(W.model),cwd:V$(W.cwd),workspaceRoot:V$(W.workspace_root),teamName:w1(W.team_name),enableTools:j9(W.enable_tools),enableSpawn:j9(W.enable_spawn),enableTeams:j9(W.enable_teams),parentSessionId:w1(W.parent_session_id),parentAgentId:w1(W.parent_agent_id),agentId:w1(W.agent_id),conversationId:w1(W.conversation_id),isSubagent:j9(W.is_subagent),prompt:w1(W.prompt),metadata:(()=>{let Z=w1(W.metadata_json);if(!Z)return;try{let Q=JSON.parse(Z);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:w1(W.hook_path),messagesPath:w1(W.messages_path),updatedAt:w1(W.updated_at)??qQ()}}list($=200){let W=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Z=[];for(let Q of W){let J=this.get(V$(Q.session_id));if(J)Z.push(J)}return Z}delete($,W=!1){let Z=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(W)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Z>0}}O8();import{existsSync as pj,mkdirSync as Uy,readFileSync as qU,renameSync as Dy,writeFileSync as _y}from"node:fs";import{join as MU}from"node:path";import{resolveSessionDataDir as fy}from"@cline/shared/storage";import{dirname as Fy}from"node:path";import{nanoid as Ay}from"nanoid";import{appendFileSync as hb,existsSync as kb,mkdirSync as YU,readFileSync as Ib,writeFileSync as VU}from"node:fs";import{readFile as BU,rm as xb}from"node:fs/promises";import{dirname as HU,join as gb}from"node:path";import{ensureHookLogDir as mb}from"@cline/shared/storage";import{randomUUID as Cb}from"node:crypto";import{mkdir as Pb,open as jU,rename as Sb,rm as bb}from"node:fs/promises";import{dirname as JU}from"node:path";async function yb($){let W;try{W=await jU($,"r"),await W.sync()}catch{}finally{if(W!==void 0)try{await W.close()}catch{}}}async function XU($,W){await Pb(JU($),{recursive:!0});let Z=`${$}.${process.pid}.${Cb()}.tmp`,Q;try{Q=await jU(Z,"wx"),await Q.writeFile(W,"utf8"),await Q.sync(),await Q.close(),Q=void 0,await Sb(Z,$),await yb(JU($))}catch(J){if(Q!==void 0)try{await Q.close()}catch{}try{await bb(Z,{force:!0})}catch{}throw J}}function vb($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}class yj{adapter;messagesArtifactUploader;logger;artifacts;constructor($,W,Z){this.adapter=$;this.messagesArtifactUploader=W;this.logger=Z;this.artifacts=new eJ(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,W,Z){AK(W,Z,fJ($))}writeSessionManifest($,W){YU(HU($),{recursive:!0}),VU($,`${JSON.stringify(m0.parse(W),null,2)}
518
+ `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}async readSessionManifestTitle($){let W=this.artifacts.sessionManifestPath($,!1),Z;try{Z=await BU(W,"utf8")}catch{return}try{let Q=JSON.parse(Z);if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J=Q.metadata;if(!J||typeof J!=="object"||Array.isArray(J))return;let j=J.title;return typeof j==="string"?j:void 0}catch{return}}readManifestFile($){let W=this.artifacts.sessionManifestPath($,!1);if(!kb(W))return{path:W};try{return{path:W,manifest:m0.parse(JSON.parse(Ib(W,"utf8")))}}catch{return{path:W}}}async resolveArtifactPath($,W,Z){let J=(await this.adapter.getSession($))?.[W];return typeof J==="string"&&J.trim().length>0?J:Z($)}async persistSessionMessages($,W,Z){let Q=await this.resolveArtifactPath($,"messagesPath",(X)=>this.artifacts.sessionMessagesPath(X)),J=LJ({updatedAt:X0(),context:fJ($),messages:W,systemPrompt:Z}),j=`${JSON.stringify(J,null,2)}
519
+ `;if(YU(HU(Q),{recursive:!0}),VU(Q,j,"utf8"),!this.messagesArtifactUploader)return;try{let X=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Q,contents:j,row:X})}catch(X){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:X})}}resolveCompactionPath($){let{manifest:W}=this.readManifestFile($);return W?.compaction_path?.trim()||this.artifacts.sessionCompactionPath($)}updateCompactionPath($,W){let Z=this.readManifestFile($);if(!Z.manifest)return;if(Z.manifest.compaction_path===W)return;this.writeSessionManifest(Z.path,{...Z.manifest,compaction_path:W})}async readSessionCompactionState($){let W=this.resolveCompactionPath($);try{return G1(JSON.parse(await BU(W,"utf8")))}catch(Z){if(vb(Z))return;this.logger?.debug("Ignoring invalid session compaction state",{sessionId:$,path:W,error:Z,recovery:"Canonical history is unchanged; deleting the sidecar is safe."});return}}async persistSessionCompactionState($,W){let Z=this.resolveCompactionPath($),Q=S4.parse(W);await XU(Z,`${JSON.stringify(Q,null,2)}
520
+ `),this.updateCompactionPath($,Z)}async deleteSessionCompactionState($){await xb(this.resolveCompactionPath($),{force:!0}),this.updateCompactionPath($,void 0)}appendStaleSessionHookLog($,W,Z,Q,J){let X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??gb(mb(),"hooks.jsonl");hb(X,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Q,sessionId:W,pid:Z,source:J})}
521
+ `,"utf8")}}import{appendFileSync as cb}from"node:fs";import{join as ub}from"node:path";import{resolveRootSessionId as GU}from"@cline/shared";import{ensureHookLogDir as db}from"@cline/shared/storage";import{z as hj}from"zod";var lb="subagent",pb=hj.looseObject({task:hj.string().optional(),systemPrompt:hj.string().optional()});class MQ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,W,Z,Q){this.adapter=$;this.manifestStore=W;this.toPersistedMessages=Z;this.heartbeatLogIntervalMs=Q}teamTaskQueueKey($,W){return`${$}::${W}`}activeTeamTaskSessionId($,W){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,W))?.at(-1)}buildSubsessionRow($,W){return{sessionId:W.sessionId,source:lb,pid:process.ppid,startedAt:W.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:W.parentSessionId,parentAgentId:W.parentAgentId,agentId:W.agentId,conversationId:W.conversationId??null,isSubagent:!0,prompt:W.prompt,metadata:G5({prompt:W.prompt}),hookPath:"",messagesPath:W.messagesPath,updatedAt:W.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let W=GU($.sessionContext);if(!W)return;let Z=pb.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:W,parentAgentId:$.agent_id,task:Z.success?Z.data.task:void 0,systemPrompt:Z.success?Z.data.systemPrompt:void 0})}async upsertSubagentSession($){let W=$.rootSessionId;if(!W)return;let Z=await this.adapter.getSession(W);if(!Z)return;let Q=s8(W,$.agentId),J=await this.adapter.getSession(Q),j=X0(),X=this.manifestStore.artifacts.subagentArtifactPaths(Q,$.agentId,this.activeTeamTaskSessionId(W,$.parentAgentId)),Y=$.prompt??J?.prompt??void 0;if(!Y)Y=await this.adapter.claimSpawnRequest(W,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!J)return await this.adapter.upsertSession(this.buildSubsessionRow(Z,{sessionId:Q,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Y,startedAt:j,...X})),this.manifestStore.initializeMessagesFile(Q,X.messagesPath,j),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:J.prompt??Y??null,metadata:G5({metadata:J.metadata??void 0,prompt:J.prompt??Y??null}),expectedStatusLock:J.statusLock}),Q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let W=GU($.sessionContext);if(!W)return;if($.hookName==="session_shutdown"){let Z=s8(W,$.agent_id);return await this.adapter.getSession(Z)?Z:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:W})}async applySubagentStatus($,W){await this.applySubagentStatusBySessionId($,V5(W))}async applySubagentStatusBySessionId($,W){let Z=await this.adapter.getSession($);if(!Z)return;let Q=K0(W)?null:X0(),J=K0(W)?null:W==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:W,endedAt:Q,exitCode:J,expectedStatusLock:Z.statusLock})}async applyStatusToRunningChildSessions($,W){if(!$)return;let Z=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Q of Z)await this.applySubagentStatusBySessionId(Q.sessionId,W)}async onTeamTaskStart($,W,Z){let Q=await this.adapter.getSession($);if(!Q)return;let J=X5($,W),j=X0(),{messagesPath:X}=this.manifestStore.artifacts.subagentArtifactPaths(J,W);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:J,parentSessionId:$,parentAgentId:"lead",agentId:W,prompt:Z||`Team task for ${W}`,startedAt:j,messagesPath:X})),this.manifestStore.initializeMessagesFile(J,X,j);let Y=this.teamTaskQueueKey($,W),V=this.teamTaskSessionsByAgent.get(Y)??[];V.push(J),this.teamTaskSessionsByAgent.set(Y,V)}async onTeamTaskEnd($,W,Z,Q,J,j){let X=this.teamTaskQueueKey($,W),Y=this.teamTaskSessionsByAgent.get(X);if(!Y||Y.length===0)return;let V=Y.shift();if(Y.length===0)this.teamTaskSessionsByAgent.delete(X);if(!V)return;let B=J?.messages??j,H=this.toPersistedMessages(B,J,j);if(H)await this.manifestStore.persistSessionMessages(V,H);await this.applySubagentStatusBySessionId(V,Z),this.teamTaskLastHeartbeatBySession.delete(V),this.teamTaskLastProgressLineBySession.delete(V)}async onTeamTaskProgress($,W,Z,Q){let J=this.teamTaskQueueKey($,W),j=this.teamTaskSessionsByAgent.get(J)?.[0];if(!j)return;let X=Z.trim();if(!X)return;let Y=Q?.kind??"progress";if(Y==="heartbeat"){let B=Date.now(),H=this.teamTaskLastHeartbeatBySession.get(j)??0;if(B-H<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(j,B)}let V=Y==="heartbeat"?"[progress] heartbeat":Y==="text"?`[progress] text: ${X}`:`[progress] ${X}`;if(this.teamTaskLastProgressLineBySession.get(j)===V)return;this.teamTaskLastProgressLineBySession.set(j,V)}async handleSubAgentStart($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;await this.applySubagentStatusBySessionId(Z,"running")}async handleSubAgentEnd($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;if(W.error){await this.applySubagentStatusBySessionId(Z,"failed");return}let Q=this.toPersistedMessages(W.agentResult?.messages,W.agentResult);if(Q)await this.manifestStore.persistSessionMessages(Z,Q);let J=W.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Z,J==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??ub(db(),"hooks.jsonl");cb(Z,`${JSON.stringify({ts:X0(),...$})}
522
+ `,"utf8")}}import{formatUserInputBlock as Ky}from"@cline/shared";var zU={};w(zU,{toTeamProgressLifecycleEvent:()=>S6,sanitizeTeamName:()=>JK,reviveTeamStateDates:()=>KZ,parseConfiguredAgentConfig:()=>Y9,loadConfiguredAgentConfigs:()=>w6,createWorkerReviewerTeam:()=>OU,createSpawnAgentTool:()=>y$,createDelegatedAgentConfigProvider:()=>S$,createDelegatedAgent:()=>b$,createConfiguredAgentTools:()=>C6,createAgentTeamsTools:()=>S2,createAgentTeam:()=>xj,buildTeamProgressSummary:()=>P6,buildDelegatedAgentConfig:()=>C2,buildConfiguredAgentToolName:()=>V9,buildConfiguredAgentToolDescriptors:()=>B9,bootstrapAgentTeams:()=>o8,AgentTeamsRuntime:()=>e2,AgentTeam:()=>y6});import{existsSync as rb,readdirSync as ib,readFileSync as nb}from"node:fs";import{basename as KU,extname as ab,join as ob}from"node:path";import{resolveAgentConfigSearchPaths as sb}from"@cline/shared/storage";import AU from"yaml";import{z as h0}from"zod";var UU=h0.object({name:h0.string().trim().min(1),description:h0.string().trim().min(1),tools:h0.union([h0.string(),h0.array(h0.string())]).optional(),skills:h0.union([h0.string(),h0.array(h0.string())]).optional(),providerId:h0.string().trim().min(1).optional(),modelId:h0.string().trim().min(1).optional(),maxIterations:h0.number().int().positive().optional()});function tb($){let W=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!W)throw Error("Missing YAML frontmatter block in agent config file.");let Z=W[0].length,Q=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Q.lastIndex=Z;let J,j=Array.from($.matchAll(Q)).filter((X)=>X.index>=Z);for(let X of j){let Y=X.index,V=$.slice(Z,Y);try{let B=AU.parse(V);if(!B||typeof B!=="object"||Array.isArray(B))continue;UU.parse(B);let H=$.slice(Y+X[0].length);J={frontmatter:V,body:H}}catch{}}if(J)return J;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function FU($){if($===void 0)return;let W=Array.isArray($)?$:$.split(",");return Array.from(new Set(W.map((Z)=>Z.trim()).filter((Z)=>Z.length>0)))}function eb($){return $.trim().toLowerCase()}function $y($){let W=ab($).toLowerCase();return W===".yml"||W===".yaml"}function Y9($,W={}){let{frontmatter:Z,body:Q}=tb($),J=AU.parse(Z);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Agent config frontmatter must be a YAML mapping.");let j=UU.parse(J),X=Q.trim();if(!X)throw Error("Missing system prompt body in agent config file.");return{name:j.name,description:j.description,tools:FU(j.tools),skills:FU(j.skills),providerId:j.providerId,modelId:j.modelId,maxIterations:j.maxIterations,systemPrompt:X,path:W.path}}function w6($){let W=$.searchPaths??sb($.workspaceRoot),Z=new Map,Q=[];for(let j of W.filter(Boolean)){if(!rb(j))continue;let X;try{X=ib(j,{withFileTypes:!0})}catch(Y){Q.push({path:j,error:Y instanceof Error?Y:Error(String(Y))});continue}for(let Y of X){if(!Y.isFile()||!$y(Y.name))continue;let V=ob(j,Y.name);try{let B=nb(V,"utf8"),H=Y9(B,{path:V}),G=eb(H.name);if(!Z.has(G))Z.set(G,H)}catch(B){Q.push({path:V,error:B instanceof Error?B:Error(String(B))})}}}return{configs:Array.from(Z.values()).sort((j,X)=>(j.path?KU(j.path):j.name).localeCompare(X.path?KU(X.path):X.name)),errors:Q}}import{createTool as Wy,zodToJsonSchema as Zy}from"@cline/shared";import{z as DU}from"zod";var kj="subagent_",RQ=64,Qy=DU.object({prompt:DU.string().trim().min(1).describe("Task for the subagent to perform")});function Jy($){let W="",Z=!0;for(let Q of $.trim().toLowerCase()){let J=Q.charCodeAt(0);if(!(J>=97&&J<=122||J>=48&&J<=57||Q==="_")||Q==="_"){if(!Z)W+="_",Z=!0;continue}W+=Q,Z=!1}return Z?W.slice(0,-1):W}function jy($){let W=2166136261;for(let Z=0;Z<$.length;Z++)W^=$.charCodeAt(Z),W=Math.imul(W,16777619);return(W>>>0).toString(36)}function V9($){let W=Jy($)||"agent",Z=jy($).slice(0,6),Q=`${kj}${W}`;if(Q.length<=RQ)return Q;let J=RQ-kj.length-Z.length-1,j=W.slice(0,Math.max(1,J));return`${kj}${j}_${Z}`.slice(0,RQ)}function B9($){let W=new Set,Z=[];for(let Q of[...$].sort((J,j)=>J.name.localeCompare(j.name))){let J=V9(Q.name),j=J,X=2;while(W.has(j)){let Y=`_${X++}`,V=Math.max(1,RQ-Y.length);j=`${J.slice(0,V)}${Y}`}W.add(j),Z.push({toolName:j,config:Q})}return Z}function Xy($,W){return{...$,providerId:W.providerId??$.providerId,modelId:W.modelId??$.modelId,maxIterations:W.maxIterations??$.maxIterations}}function C6($){return B9($.agents).map(({toolName:W,config:Z})=>{return Wy({name:W,description:`Use the "${Z.name}" subagent: ${Z.description}`,inputSchema:Zy(Qy),execute:async(J,j)=>{let X=$.configProvider.getRuntimeConfig(),Y=S$(Xy(X,Z)),V=$.createSubAgentTools?await $.createSubAgentTools(Z,J,j):[],B=b$({kind:"subagent",prompt:Z.systemPrompt,configProvider:Y,tools:V,maxIterations:Z.maxIterations,parentAgentId:j.agentId,abortSignal:j.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),H=B.getAgentId(),G=B.getConversationId(),K=j.agentId,F={systemPrompt:Z.systemPrompt,task:J.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:H,conversationId:G,parentAgentId:K,input:F})}catch{}try{let A=await B.run(J.prompt),D={text:A.text,iterations:A.iterations,finishReason:A.finishReason,usage:{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,result:D,agentResult:A})}catch{}return D}catch(A){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,error:A instanceof Error?A:Error(String(A))})}catch{}throw A}},timeoutMs:300000,retryable:!1})})}function P1(){return new Date().toISOString()}function _U($,W){if(W<=0)return 0;return Math.round($/W*100)}function Yy($,W){let Z=new Set;for(let J of W)if(J.status==="reviewed")Z.add(`${J.outcomeId}:${J.section}`);let Q=new Set;for(let J of $){if(J.status==="finalized")continue;for(let j of J.requiredSections)if(!Z.has(`${J.id}:${j}`))Q.add(`${J.id}:${j}`)}return[...Q].sort((J,j)=>J.localeCompare(j))}function P6($,W){let Z={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},J={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},j={draft:0,in_review:0,finalized:0},X={draft:0,reviewed:0,rejected:0},Y=0,V=0;for(let U of W.members)if(Z[U.status]+=1,U.role==="lead")Y+=1;else V+=1;let B=[],H=[],G=W.tasks.filter((U)=>U.status==="completed").length,K=new Map(W.tasks.map((U)=>[U.id,U]));for(let U of W.tasks){if(Q[U.status]+=1,U.status==="blocked"){B.push(U.id);continue}if(U.status!=="pending")continue;if(U.dependsOn.every((_)=>{return K.get(_)?.status==="completed"}))H.push(U.id)}let F=[],A,D=0;for(let U of W.runs){if(J[U.status]+=1,U.status==="queued"||U.status==="running")F.push(U.id);let f=U.startedAt.getTime();if(f>=D)D=f,A=U.id}for(let U of W.outcomes)j[U.status]+=1;for(let U of W.outcomeFragments)X[U.status]+=1;return{teamName:$,updatedAt:P1(),members:{total:W.members.length,byStatus:Z,leadCount:Y,teammateCount:V},tasks:{total:W.tasks.length,byStatus:Q,blockedTaskIds:B,readyTaskIds:H,completionPct:_U(G,W.tasks.length)},runs:{total:W.runs.length,byStatus:J,activeRunIds:F,latestRunId:A},outcomes:{total:W.outcomes.length,byStatus:j,finalizedPct:_U(j.finalized,W.outcomes.length),missingRequiredSections:Yy(W.outcomes,W.outcomeFragments)},fragments:{total:W.outcomeFragments.length,byStatus:X}}}function S6($){let{event:W}=$;switch(W.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.task.id,agentId:W.task.assignee??W.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),outcomeId:W.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),outcomeId:W.fragment.outcomeId,fragmentId:W.fragment.id,agentId:W.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.message.taskId,agentId:W.message.fromAgentId,message:W.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),taskId:W.entry.taskId,agentId:W.entry.agentId,message:W.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1(),agentId:W.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:P1()}}import{sanitizeFileName as Vy,TeamMessageType as m}from"@cline/shared";import{nanoid as By}from"nanoid";import{TeamMessageType as Js}from"@cline/shared";function Ij($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function fU($,W){return $?.status==="stopped"&&Ij(W)}var Hy=600000,LU="recovered_queued";function Gy($){return`This is an automatic recovery of interrupted team run ${$.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
523
523
 
524
524
  ${$.message}`}class y6{agents=new Map;configs=new Map;onTeamEvent;constructor($,W){if(this.onTeamEvent=W,$)for(let[Z,Q]of Object.entries($))this.addAgent(Z,Q)}addAgent($,W){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let Z={...W,onEvent:(J)=>{W.onEvent?.(J),this.emitEvent({type:m.AgentEvent,agentId:$,event:J})}},Q=new P$(Z);if(Z.onEvent)Q.subscribeEvents(Z.onEvent);this.agents.set($,Q),this.configs.set($,W)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,W){let Z=this.agents.get($);if(!Z)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let Q=await Z.run(W);return this.emitEvent({type:m.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let J=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:m.TaskEnd,agentId:$,error:J,messages:Z.getMessages()}),Q}}async continueTo($,W){let Z=this.agents.get($);if(!Z)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let Q=await Z.continue(W);return this.emitEvent({type:m.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let J=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:m.TaskEnd,agentId:$,error:J,messages:Z.getMessages()}),Q}}async runParallel($){let W=$.map(async(Z)=>{let Q=this.agents.get(Z.agentId);if(!Q)return{agentId:Z.agentId,result:void 0,error:Error(`Agent "${Z.agentId}" not found in team`),metadata:Z.metadata};this.emitEvent({type:m.TaskStart,agentId:Z.agentId,message:Z.message});try{let J=await Q.run(Z.message);return this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,result:J}),{agentId:Z.agentId,result:J,metadata:Z.metadata}}catch(J){let j=J instanceof Error?J:Error(String(J));return this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,error:j,messages:Q.getMessages()}),{agentId:Z.agentId,result:void 0,error:j,metadata:Z.metadata}}});return Promise.all(W)}async runSequential($){let W=[];for(let Z of $){let Q=this.agents.get(Z.agentId);if(!Q){W.push({agentId:Z.agentId,result:void 0,error:Error(`Agent "${Z.agentId}" not found in team`),metadata:Z.metadata});continue}this.emitEvent({type:m.TaskStart,agentId:Z.agentId,message:Z.message});try{let J=await Q.run(Z.message);this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,result:J}),W.push({agentId:Z.agentId,result:J,metadata:Z.metadata})}catch(J){let j=J instanceof Error?J:Error(String(J));this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,error:j,messages:Q.getMessages()}),W.push({agentId:Z.agentId,result:void 0,error:j,metadata:Z.metadata})}}return W}async runPipeline($,W,Z){let Q=[],J=W;for(let j of $){let X=this.agents.get(j);if(!X){Q.push({agentId:j,result:void 0,error:Error(`Agent "${j}" not found in team`)});break}this.emitEvent({type:m.TaskStart,agentId:j,message:J});try{let Y=await X.run(J);this.emitEvent({type:m.TaskEnd,agentId:j,result:Y}),Q.push({agentId:j,result:Y});let V=$.indexOf(j)+1;if(V<$.length){let B=$[V];J=Z?Z(Y,B):`Previous agent output:
525
525
  ${Y.text}
526
526
 
527
- Please continue from here.`}}catch(Y){let V=Y instanceof Error?Y:Error(String(Y));this.emitEvent({type:m.TaskEnd,agentId:j,error:V,messages:X.getMessages()}),Q.push({agentId:j,result:void 0,error:V});break}}return Q}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function Ij($,W){return new y6($,W)}function TU($){let W=Ij({worker:$.worker,reviewer:$.reviewer}),Z=W;return Z.doAndReview=async(Q)=>{let J=await W.routeTo("worker",Q),j=await W.routeTo("reviewer",`Please review this work:
527
+ Please continue from here.`}}catch(Y){let V=Y instanceof Error?Y:Error(String(Y));this.emitEvent({type:m.TaskEnd,agentId:j,error:V,messages:X.getMessages()}),Q.push({agentId:j,result:void 0,error:V});break}}return Q}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function xj($,W){return new y6($,W)}function OU($){let W=xj({worker:$.worker,reviewer:$.reviewer}),Z=W;return Z.doAndReview=async(Q)=>{let J=await W.routeTo("worker",Q),j=await W.routeTo("reviewer",`Please review this work:
528
528
 
529
- ${J.text}`);return{workerResult:J,reviewResult:j}},Z}class e2{teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor($){this.teamName=$.teamName,this.teamId=`t_${Yy(Vy(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let W=$.leadAgentId??"lead";this.members.set(W,{agentId:W,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((W)=>{let Z=this.getUnresolvedDependencies(W);return{...W,blockedBy:Z,isReady:W.status==="pending"&&!W.assignee&&Z.length===0}}).filter((W)=>{if($?.status&&W.status!==$.status)return!1;if($?.assignee&&W.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,W){let Z=W?.unreadOnly??!0,Q=W?.markRead??!0,J=W?.limit,j=this.mailbox.filter((Y)=>Y.toAgentId===$&&(!Z||!Y.readAt)),X=typeof J==="number"&&J>0?j.slice(Math.max(0,j.length-J)):j;if(Q){let Y=new Date;for(let V of X)if(!V.readAt)V.readAt=Y}return X.map((Y)=>({...Y}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Z of this.tasks.values())$[Z.status]++;let W={draft:0,in_review:0,finalized:0};for(let Z of this.outcomes.values())W[Z.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Z)=>({agentId:Z.agentId,role:Z.role,description:Z.description,status:Z.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Z)=>!Z.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").length,outcomeCounts:W}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let Z of $.tasks)this.tasks.set(Z.id,{...Z});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Z)=>({...Z}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Z)=>({...Z}))),this.runs.clear();for(let Z of $.runs??[])this.runs.set(Z.id,{...Z});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").map((Z)=>Z.id)),this.outcomes.clear();for(let Z of $.outcomes??[])this.outcomes.set(Z.id,{...Z});this.outcomeFragments.clear();for(let Z of $.outcomeFragments??[])this.outcomeFragments.set(Z.id,{...Z});let W=Array.from(this.members.values()).filter((Z)=>Z.role==="lead");this.members.clear();for(let Z of W)this.members.set(Z.agentId,{...Z,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Z of $.members){if(Z.role!=="teammate")continue;this.members.set(Z.agentId,{agentId:Z.agentId,role:"teammate",description:Z.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,b6($.tasks.map((Z)=>Z.id),"task_")),this.messageCounter=Math.max(this.messageCounter,b6($.mailbox.map((Z)=>Z.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,b6($.missionLog.map((Z)=>Z.id),"log_")),this.runCounter=Math.max(this.runCounter,b6(($.runs??[]).map((Z)=>Z.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,b6(($.outcomes??[]).map((Z)=>Z.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,b6(($.outcomeFragments??[]).map((Z)=>Z.id),"frag_"))}isTeammateActive($){let W=this.members.get($);return!!W&&W.role==="teammate"&&!!W.agent}spawnTeammate({agentId:$,config:W}){let Z=this.members.get($);if(Z&&Z.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Z&&Z.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Q={...W,apiTimeoutMs:By,consumePendingUserMessage:()=>{let X=this.members.get($);if(!X||!X.pendingSteerMessage)return;let Y=X.pendingSteerMessage;return X.pendingSteerMessage=void 0,Y},onEvent:(X)=>{W.onEvent?.(X),this.emitEvent({type:m.AgentEvent,agentId:$,event:X}),this.trackMeaningfulEvent($,X)}},J=new P$(Q);if(Q.onEvent)J.subscribeEvents(Q.onEvent);let j={agentId:$,role:"teammate",description:W.role,status:"idle",agent:J,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,j),this.emitEvent({type:m.TeammateSpawned,agentId:$,role:W.role,teammate:{rolePrompt:W.systemPrompt,modelId:W.modelId,maxIterations:W.maxIterations,runtimeAgentId:J.getAgentId(),conversationId:J.getConversationId(),parentAgentId:null}}),{agentId:j.agentId,role:j.role,description:j.description,status:j.status}}shutdownTeammate($,W){let Z=this.members.get($);if(!Z||Z.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Z.agent?.abort()}catch(Q){if(!kj(Q))throw Q}Z.status="stopped",this.emitEvent({type:m.TeammateShutdown,agentId:$,reason:W})}updateTeammateConnections($){for(let W of this.members.values()){if(W.role!=="teammate"||!W.agent)continue;W.agent.updateConnection($)}}createTask($){let W=`task_${String(++this.taskCounter).padStart(4,"0")}`,Z=new Date,Q={id:W,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Z,updatedAt:Z,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(W,Q),this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask($,W){let Z=this.requireTask($);return this.assertDependenciesResolved(Z),Z.status="in_progress",Z.assignee=W,Z.updatedAt=new Date,this.emitEvent({type:m.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:W,taskId:$,kind:"progress",summary:`Claimed task "${Z.title}"`}),{...Z}}blockTask($,W,Z){let Q=this.requireTask($);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=Z,this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"blocked",summary:Z}),{...Q}}completeTask($,W,Z){let Q=this.requireTask($);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=Z,!Q.assignee)Q.assignee=W;return this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"done",summary:Z}),{...Q}}async routeToTeammate($,W,Z){let Q=this.members.get($);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${$}" was not found`);if(!Q.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Q.runningCount++,Q.status="running",this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let J=this.listMailbox($,{unreadOnly:!0,markRead:!0}),j=J.length>0?`${this.buildMailboxNotification(J)}
529
+ ${J.text}`);return{workerResult:J,reviewResult:j}},Z}class e2{teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor($){this.teamName=$.teamName,this.teamId=`t_${Vy(By(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let W=$.leadAgentId??"lead";this.members.set(W,{agentId:W,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((W)=>{let Z=this.getUnresolvedDependencies(W);return{...W,blockedBy:Z,isReady:W.status==="pending"&&!W.assignee&&Z.length===0}}).filter((W)=>{if($?.status&&W.status!==$.status)return!1;if($?.assignee&&W.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,W){let Z=W?.unreadOnly??!0,Q=W?.markRead??!0,J=W?.limit,j=this.mailbox.filter((Y)=>Y.toAgentId===$&&(!Z||!Y.readAt)),X=typeof J==="number"&&J>0?j.slice(Math.max(0,j.length-J)):j;if(Q){let Y=new Date;for(let V of X)if(!V.readAt)V.readAt=Y}return X.map((Y)=>({...Y}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Z of this.tasks.values())$[Z.status]++;let W={draft:0,in_review:0,finalized:0};for(let Z of this.outcomes.values())W[Z.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Z)=>({agentId:Z.agentId,role:Z.role,description:Z.description,status:Z.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Z)=>!Z.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").length,outcomeCounts:W}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let Z of $.tasks)this.tasks.set(Z.id,{...Z});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Z)=>({...Z}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Z)=>({...Z}))),this.runs.clear();for(let Z of $.runs??[])this.runs.set(Z.id,{...Z});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").map((Z)=>Z.id)),this.outcomes.clear();for(let Z of $.outcomes??[])this.outcomes.set(Z.id,{...Z});this.outcomeFragments.clear();for(let Z of $.outcomeFragments??[])this.outcomeFragments.set(Z.id,{...Z});let W=Array.from(this.members.values()).filter((Z)=>Z.role==="lead");this.members.clear();for(let Z of W)this.members.set(Z.agentId,{...Z,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Z of $.members){if(Z.role!=="teammate")continue;this.members.set(Z.agentId,{agentId:Z.agentId,role:"teammate",description:Z.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,b6($.tasks.map((Z)=>Z.id),"task_")),this.messageCounter=Math.max(this.messageCounter,b6($.mailbox.map((Z)=>Z.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,b6($.missionLog.map((Z)=>Z.id),"log_")),this.runCounter=Math.max(this.runCounter,b6(($.runs??[]).map((Z)=>Z.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,b6(($.outcomes??[]).map((Z)=>Z.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,b6(($.outcomeFragments??[]).map((Z)=>Z.id),"frag_"))}isTeammateActive($){let W=this.members.get($);return!!W&&W.role==="teammate"&&!!W.agent}spawnTeammate({agentId:$,config:W}){let Z=this.members.get($);if(Z&&Z.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Z&&Z.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Q={...W,apiTimeoutMs:Hy,consumePendingUserMessage:()=>{let X=this.members.get($);if(!X||!X.pendingSteerMessage)return;let Y=X.pendingSteerMessage;return X.pendingSteerMessage=void 0,Y},onEvent:(X)=>{W.onEvent?.(X),this.emitEvent({type:m.AgentEvent,agentId:$,event:X}),this.trackMeaningfulEvent($,X)}},J=new P$(Q);if(Q.onEvent)J.subscribeEvents(Q.onEvent);let j={agentId:$,role:"teammate",description:W.role,status:"idle",agent:J,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,j),this.emitEvent({type:m.TeammateSpawned,agentId:$,role:W.role,teammate:{rolePrompt:W.systemPrompt,modelId:W.modelId,maxIterations:W.maxIterations,runtimeAgentId:J.getAgentId(),conversationId:J.getConversationId(),parentAgentId:null}}),{agentId:j.agentId,role:j.role,description:j.description,status:j.status}}shutdownTeammate($,W){let Z=this.members.get($);if(!Z||Z.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Z.agent?.abort()}catch(Q){if(!Ij(Q))throw Q}Z.status="stopped",this.emitEvent({type:m.TeammateShutdown,agentId:$,reason:W})}updateTeammateConnections($){for(let W of this.members.values()){if(W.role!=="teammate"||!W.agent)continue;W.agent.updateConnection($)}}createTask($){let W=`task_${String(++this.taskCounter).padStart(4,"0")}`,Z=new Date,Q={id:W,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Z,updatedAt:Z,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(W,Q),this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask($,W){let Z=this.requireTask($);return this.assertDependenciesResolved(Z),Z.status="in_progress",Z.assignee=W,Z.updatedAt=new Date,this.emitEvent({type:m.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:W,taskId:$,kind:"progress",summary:`Claimed task "${Z.title}"`}),{...Z}}blockTask($,W,Z){let Q=this.requireTask($);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=Z,this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"blocked",summary:Z}),{...Q}}completeTask($,W,Z){let Q=this.requireTask($);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=Z,!Q.assignee)Q.assignee=W;return this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"done",summary:Z}),{...Q}}async routeToTeammate($,W,Z){let Q=this.members.get($);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${$}" was not found`);if(!Q.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Q.runningCount++,Q.status="running",this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let J=this.listMailbox($,{unreadOnly:!0,markRead:!0}),j=J.length>0?`${this.buildMailboxNotification(J)}
530
530
 
531
- ${W}`:W,X=Z?.continueConversation?await Q.agent.continue(j):await Q.agent.run(j);return this.emitEvent({type:m.TaskEnd,agentId:$,result:X}),this.recordProgressStep($,`Completed a delegated run (${X.iterations} iterations)`,Z?.taskId,!0),X}catch(J){let j=J instanceof Error?J:Error(String(J));if(this.emitEvent({type:m.TaskEnd,agentId:$,error:j,messages:Q.agent.getMessages()}),!_U(Q,j))this.appendMissionLog({agentId:$,taskId:Z?.taskId,kind:"error",summary:j.message});throw j}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get($)?.status!=="stopped")Q.status="idle"}}startTeammateRun($,W,Z){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,J={id:Q,agentId:$,taskId:Z?.taskId,status:"queued",message:W,priority:Z?.priority??0,retryCount:0,maxRetries:Math.max(0,Z?.maxRetries??0),continueConversation:Z?.continueConversation,startedAt:new Date(0),leaseOwner:Z?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,J),this.runQueue.push(Q),this.emitEvent({type:m.RunQueued,run:{...J}}),this.dispatchQueuedRuns(),{...J}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let W=this.selectNextDispatchableQueuedRun();$=W.nextDelayedAttemptAt;let Z=W.index;if(Z<0){this.scheduleQueuedRunDispatch($);return}let[Q]=this.runQueue.splice(Z,1),J=Q?this.runs.get(Q):void 0;if(!J||J.status!=="queued")continue;this.executeQueuedRun(J)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,W=Number.NEGATIVE_INFINITY,Z,Q=Date.now();for(let J=0;J<this.runQueue.length;J++){let j=this.runs.get(this.runQueue[J]);if(!j||j.status!=="queued")continue;if(j.nextAttemptAt&&j.nextAttemptAt.getTime()>Q){if(!Z||j.nextAttemptAt<Z)Z=j.nextAttemptAt;continue}if(j.priority>W)W=j.priority,$=J}return{index:$,nextDelayedAttemptAt:Z}}scheduleQueuedRunDispatch($){if(!$)return;let W=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},W)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let W of this.runs.values())if(W.status==="running")$++;return $}async executeQueuedRun($){let W=$.currentActivity===fU;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:m.RunStarted,run:{...$}});let Z=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Q=W?Hy($):$.message,J=await this.routeToTeammate($.agentId,Q,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=J,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:m.RunCompleted,run:{...$}})}catch(Q){let J=Q instanceof Error?Q.message:String(Q??"Unknown error");$.error=J,$.endedAt=new Date;let j=this.members.get($.agentId);if(_U(j,Q))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:m.RunCancelled,run:{...$},reason:J});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:m.RunFailed,run:{...$}})}finally{clearInterval(Z),this.dispatchQueuedRuns()}}listRuns($){let W=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Z)=>{if(!W&&!["running","queued"].includes(Z.status))return!1;if($?.status&&Z.status!==$.status)return!1;if($?.agentId&&Z.agentId!==$.agentId)return!1;return!0}).map((Z)=>({...Z}))}getRun($){let W=this.runs.get($);return W?{...W}:void 0}async awaitRun($,W=250){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);while(Z.status==="queued"||Z.status==="running")await LU(W);return{...Z}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((W)=>["queued","running"].includes(W.status)))await LU($);return this.listRuns()}cancelRun($,W){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);if(Z.status==="completed"||Z.status==="failed")return{...Z};Z.status="cancelled",Z.error=W,Z.endedAt=new Date,Z.currentActivity="cancelled";let Q=this.runQueue.indexOf($);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:m.RunCancelled,run:{...Z},reason:W}),{...Z}}recoverActiveRuns($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;let Q=this.members.get(Z.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){Z.status="interrupted",Z.error="teammate_unavailable_after_recovery",Z.endedAt=new Date,Z.currentActivity="interrupted",this.emitEvent({type:m.RunInterrupted,run:{...Z},reason:Z.error});continue}let J=new Date;if(Z.status="queued",Z.error=void 0,Z.endedAt=void 0,Z.heartbeatAt=J,Z.lastProgressAt=J,Z.lastProgressMessage=$,Z.currentActivity=fU,!this.runQueue.includes(Z.id))this.runQueue.push(Z.id);W.push({...Z}),this.emitEvent({type:m.RunQueued,run:{...Z}})}return this.dispatchQueuedRuns(),W}markStaleRunsInterrupted($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;Z.status="interrupted",Z.error=$,Z.endedAt=new Date,Z.currentActivity="interrupted",W.push({...Z}),this.emitEvent({type:m.RunInterrupted,run:{...Z},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),W}sendMessage($,W,Z,Q,J){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let j=this.members.get(W);if(!j)throw Error(`Unknown recipient "${W}"`);let X={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:W,subject:Z,body:Q,taskId:J,sentAt:new Date};if(this.mailbox.push(X),this.emitEvent({type:m.TeamMessage,message:{...X}}),j.role==="teammate"&&j.runningCount>0&&j.agent)j.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Z}". Use the team_read_mailbox tool to read it at your convenience.`;return{...X}}broadcast($,W,Z,Q){let J=[];for(let j of this.members.values()){if(j.agentId===$)continue;if(j.role==="lead")continue;J.push(this.sendMessage($,j.agentId,W,Z,Q?.taskId))}return J}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let W={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(W);let Z=this.members.get($.agentId);if(Z)Z.lastMissionAt=Date.now(),Z.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:m.TeamMissionLog,entry:{...W}}),{...W}}createOutcome($){let W={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(W.id,W),this.emitEvent({type:m.OutcomeCreated,outcome:{...W}}),{...W}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let W=this.outcomes.get($.outcomeId);if(!W)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!W.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Z={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(Z.id,Z),W.status==="draft")W.status="in_review";return this.emitEvent({type:m.OutcomeFragmentAttached,fragment:{...Z}}),{...Z}}reviewOutcomeFragment($){let W=this.outcomeFragments.get($.fragmentId);if(!W)throw Error(`Fragment "${$.fragmentId}" was not found`);return W.status=$.approved?"reviewed":"rejected",W.reviewedBy=$.reviewedBy,W.reviewedAt=new Date,this.emitEvent({type:m.OutcomeFragmentReviewed,fragment:{...W}}),{...W}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((W)=>W.outcomeId===$).map((W)=>({...W}))}finalizeOutcome($){let W=this.outcomes.get($);if(!W)throw Error(`Outcome "${$}" was not found`);let Z=this.listOutcomeFragments($);for(let Q of W.requiredSections)if(!Z.some((j)=>j.section===Q&&j.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return W.status="finalized",W.finalizedAt=new Date,this.emitEvent({type:m.OutcomeFinalized,outcome:{...W}}),{...W}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(W){if(!kj(W))throw W}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,W]of this.members.entries())if(W.role==="teammate")this.members.delete($)}requireTask($){let W=this.tasks.get($);if(!W)throw Error(`Task "${$}" was not found`);return W}assertDependenciesResolved($){let W=this.getUnresolvedDependencies($);if(W.length>0)throw Error(`Task "${$.id}" is blocked by "${W[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((W)=>{let Z=this.tasks.get(W);return!Z||Z.status!=="completed"})}trackMeaningfulEvent($,W){if(this.recordRunActivityFromAgentEvent($,W),W.type==="iteration_end"&&W.hadToolCalls){this.recordProgressStep($,`Completed iteration ${W.iteration} with ${W.toolCallCount} tool call(s)`);return}if(W.type==="content_end"&&W.contentType==="tool"&&!W.error){this.recordProgressStep($,`Finished tool "${W.toolName??"unknown"}"`);return}if(W.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${W.iterations} iterations)`});return}if(W.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:W.error.message})}recordRunActivityFromAgentEvent($,W){let Z;switch(W.type){case"iteration_start":Z=`iteration_${W.iteration}_started`;break;case"content_start":if(W.contentType==="tool")Z=`running_tool_${W.toolName??"unknown"}`;break;case"content_end":if(W.contentType==="tool")Z=W.error?this.formatProgressErrorActivity(`tool_${W.toolName??"unknown"}_error`,W.error):`finished_tool_${W.toolName??"unknown"}`;break;case"done":Z="finalizing_response";break;case"error":Z=this.formatProgressErrorActivity("run_error",W.error.message);break;default:break}if(!Z)return;for(let Q of this.runs.values()){if(Q.agentId!==$||Q.status!=="running")continue;this.recordRunProgress(Q,Z)}}recordRunProgress($,W){let Z=new Date;$.heartbeatAt=Z,$.lastProgressAt=Z,$.lastProgressMessage=W,$.currentActivity=W,this.emitEvent({type:m.RunProgress,run:{...$},message:W})}formatProgressErrorActivity($,W){let Z=W.replace(/\s+/g," ").trim();if(Z.length===0)return $;let Q=Z.length>240?`${Z.slice(0,237).trimEnd()}...`:Z;return`${$}: ${Q}`}recordProgressStep($,W,Z,Q=!1){this.missionStepCounter++;let J=this.members.get($);if(!J)return;let j=this.missionStepCounter-J.lastMissionStep,X=Date.now()-J.lastMissionAt;if(!Q&&j<this.missionLogIntervalSteps&&X<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Z,kind:"progress",summary:W})}buildMailboxNotification($){if($.length===0)return"";let W=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Z of $)W.push(`--- Message from ${Z.fromAgentId} | subject: ${Z.subject} ---`),W.push(Z.body);return W.push("---"),W.join(`
532
- `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function LU($){return new Promise((W)=>setTimeout(W,$))}function b6($,W){let Z=0;for(let Q of $){if(!Q.startsWith(W))continue;let J=Number.parseInt(Q.slice(W.length),10);if(Number.isFinite(J))Z=Math.max(Z,J)}return Z}function xj($,W){switch(W.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(W.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Z;if(W.type==="run_failed")Z=W.run.error;else if(W.type==="run_cancelled"||W.type==="run_interrupted")Z=W.run.error??W.reason;$.activeTeamRunIds.delete(W.run.id),$.pendingTeamRunUpdates.push({runId:W.run.id,agentId:W.run.agentId,taskId:W.run.taskId,status:W.type.replace("run_",""),error:Z,iterations:W.run.result?.iterations}),RQ($);break}default:break}}async function gj($,W,Z){switch(W.type){case"run_progress":await Z("onTeamTaskProgress",$,W.run.agentId,W.message,{kind:W.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(W.event.type==="content_start"&&W.event.contentType==="text"&&typeof W.event.text==="string"){let Q=W.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Q)await Z("onTeamTaskProgress",$,W.agentId,Q,{kind:"text"})}break;case"task_start":await Z("onTeamTaskStart",$,W.agentId,W.message);break;case"task_end":{if(W.error)await Z("onTeamTaskEnd",$,W.agentId,"failed",`[error] ${W.error.message}`,void 0,W.messages);else if(W.result?.finishReason==="aborted")await Z("onTeamTaskEnd",$,W.agentId,"cancelled","[done] aborted",W.result,W.result.messages);else await Z("onTeamTaskEnd",$,W.agentId,"completed",`[done] ${W.result?.finishReason??"completed"}`,W.result,W.result?.messages);break}default:break}}function mj($,W,Z,Q){if(!$.runtime.teamRuntime)return;let J=$.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:W,teamName:J,lifecycle:S6({teamName:J,sessionId:W,event:Z}),summary:P6(J,$.runtime.teamRuntime.exportState())}})}function H9($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function vj($,W){if($.aborting)return!1;if(!(W==="completed"||W==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&H9($)}function RQ($){let W=$.teamRunWaiters.splice(0);for(let Z of W)Z()}async function cj($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let W=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,W}if($.activeTeamRunIds.size===0)return[];await new Promise((W)=>{$.teamRunWaiters.push(W)})}}function uj($,W){let Z=W.map((j)=>{let X=[`- ${j.runId} (${j.agentId}) -> ${j.status}`];if(j.taskId)X.push(` task=${j.taskId}`);if(typeof j.iterations==="number")X.push(` iterations=${j.iterations}`);if(j.error)X.push(` error=${j.error}`);return X.join("")}),Q=$.activeTeamRunIds.size,J=Q>0?`There are still ${Q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return G9(`System-delivered teammate async run updates:
531
+ ${W}`:W,X=Z?.continueConversation?await Q.agent.continue(j):await Q.agent.run(j);return this.emitEvent({type:m.TaskEnd,agentId:$,result:X}),this.recordProgressStep($,`Completed a delegated run (${X.iterations} iterations)`,Z?.taskId,!0),X}catch(J){let j=J instanceof Error?J:Error(String(J));if(this.emitEvent({type:m.TaskEnd,agentId:$,error:j,messages:Q.agent.getMessages()}),!fU(Q,j))this.appendMissionLog({agentId:$,taskId:Z?.taskId,kind:"error",summary:j.message});throw j}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get($)?.status!=="stopped")Q.status="idle"}}startTeammateRun($,W,Z){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,J={id:Q,agentId:$,taskId:Z?.taskId,status:"queued",message:W,priority:Z?.priority??0,retryCount:0,maxRetries:Math.max(0,Z?.maxRetries??0),continueConversation:Z?.continueConversation,startedAt:new Date(0),leaseOwner:Z?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,J),this.runQueue.push(Q),this.emitEvent({type:m.RunQueued,run:{...J}}),this.dispatchQueuedRuns(),{...J}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let W=this.selectNextDispatchableQueuedRun();$=W.nextDelayedAttemptAt;let Z=W.index;if(Z<0){this.scheduleQueuedRunDispatch($);return}let[Q]=this.runQueue.splice(Z,1),J=Q?this.runs.get(Q):void 0;if(!J||J.status!=="queued")continue;this.executeQueuedRun(J)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,W=Number.NEGATIVE_INFINITY,Z,Q=Date.now();for(let J=0;J<this.runQueue.length;J++){let j=this.runs.get(this.runQueue[J]);if(!j||j.status!=="queued")continue;if(j.nextAttemptAt&&j.nextAttemptAt.getTime()>Q){if(!Z||j.nextAttemptAt<Z)Z=j.nextAttemptAt;continue}if(j.priority>W)W=j.priority,$=J}return{index:$,nextDelayedAttemptAt:Z}}scheduleQueuedRunDispatch($){if(!$)return;let W=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},W)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let W of this.runs.values())if(W.status==="running")$++;return $}async executeQueuedRun($){let W=$.currentActivity===LU;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:m.RunStarted,run:{...$}});let Z=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Q=W?Gy($):$.message,J=await this.routeToTeammate($.agentId,Q,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=J,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:m.RunCompleted,run:{...$}})}catch(Q){let J=Q instanceof Error?Q.message:String(Q??"Unknown error");$.error=J,$.endedAt=new Date;let j=this.members.get($.agentId);if(fU(j,Q))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:m.RunCancelled,run:{...$},reason:J});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:m.RunFailed,run:{...$}})}finally{clearInterval(Z),this.dispatchQueuedRuns()}}listRuns($){let W=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Z)=>{if(!W&&!["running","queued"].includes(Z.status))return!1;if($?.status&&Z.status!==$.status)return!1;if($?.agentId&&Z.agentId!==$.agentId)return!1;return!0}).map((Z)=>({...Z}))}getRun($){let W=this.runs.get($);return W?{...W}:void 0}async awaitRun($,W=250){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);while(Z.status==="queued"||Z.status==="running")await TU(W);return{...Z}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((W)=>["queued","running"].includes(W.status)))await TU($);return this.listRuns()}cancelRun($,W){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);if(Z.status==="completed"||Z.status==="failed")return{...Z};Z.status="cancelled",Z.error=W,Z.endedAt=new Date,Z.currentActivity="cancelled";let Q=this.runQueue.indexOf($);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:m.RunCancelled,run:{...Z},reason:W}),{...Z}}recoverActiveRuns($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;let Q=this.members.get(Z.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){Z.status="interrupted",Z.error="teammate_unavailable_after_recovery",Z.endedAt=new Date,Z.currentActivity="interrupted",this.emitEvent({type:m.RunInterrupted,run:{...Z},reason:Z.error});continue}let J=new Date;if(Z.status="queued",Z.error=void 0,Z.endedAt=void 0,Z.heartbeatAt=J,Z.lastProgressAt=J,Z.lastProgressMessage=$,Z.currentActivity=LU,!this.runQueue.includes(Z.id))this.runQueue.push(Z.id);W.push({...Z}),this.emitEvent({type:m.RunQueued,run:{...Z}})}return this.dispatchQueuedRuns(),W}markStaleRunsInterrupted($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;Z.status="interrupted",Z.error=$,Z.endedAt=new Date,Z.currentActivity="interrupted",W.push({...Z}),this.emitEvent({type:m.RunInterrupted,run:{...Z},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),W}sendMessage($,W,Z,Q,J){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let j=this.members.get(W);if(!j)throw Error(`Unknown recipient "${W}"`);let X={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:W,subject:Z,body:Q,taskId:J,sentAt:new Date};if(this.mailbox.push(X),this.emitEvent({type:m.TeamMessage,message:{...X}}),j.role==="teammate"&&j.runningCount>0&&j.agent)j.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Z}". Use the team_read_mailbox tool to read it at your convenience.`;return{...X}}broadcast($,W,Z,Q){let J=[];for(let j of this.members.values()){if(j.agentId===$)continue;if(j.role==="lead")continue;J.push(this.sendMessage($,j.agentId,W,Z,Q?.taskId))}return J}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let W={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(W);let Z=this.members.get($.agentId);if(Z)Z.lastMissionAt=Date.now(),Z.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:m.TeamMissionLog,entry:{...W}}),{...W}}createOutcome($){let W={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(W.id,W),this.emitEvent({type:m.OutcomeCreated,outcome:{...W}}),{...W}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let W=this.outcomes.get($.outcomeId);if(!W)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!W.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Z={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(Z.id,Z),W.status==="draft")W.status="in_review";return this.emitEvent({type:m.OutcomeFragmentAttached,fragment:{...Z}}),{...Z}}reviewOutcomeFragment($){let W=this.outcomeFragments.get($.fragmentId);if(!W)throw Error(`Fragment "${$.fragmentId}" was not found`);return W.status=$.approved?"reviewed":"rejected",W.reviewedBy=$.reviewedBy,W.reviewedAt=new Date,this.emitEvent({type:m.OutcomeFragmentReviewed,fragment:{...W}}),{...W}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((W)=>W.outcomeId===$).map((W)=>({...W}))}finalizeOutcome($){let W=this.outcomes.get($);if(!W)throw Error(`Outcome "${$}" was not found`);let Z=this.listOutcomeFragments($);for(let Q of W.requiredSections)if(!Z.some((j)=>j.section===Q&&j.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return W.status="finalized",W.finalizedAt=new Date,this.emitEvent({type:m.OutcomeFinalized,outcome:{...W}}),{...W}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(W){if(!Ij(W))throw W}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,W]of this.members.entries())if(W.role==="teammate")this.members.delete($)}requireTask($){let W=this.tasks.get($);if(!W)throw Error(`Task "${$}" was not found`);return W}assertDependenciesResolved($){let W=this.getUnresolvedDependencies($);if(W.length>0)throw Error(`Task "${$.id}" is blocked by "${W[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((W)=>{let Z=this.tasks.get(W);return!Z||Z.status!=="completed"})}trackMeaningfulEvent($,W){if(this.recordRunActivityFromAgentEvent($,W),W.type==="iteration_end"&&W.hadToolCalls){this.recordProgressStep($,`Completed iteration ${W.iteration} with ${W.toolCallCount} tool call(s)`);return}if(W.type==="content_end"&&W.contentType==="tool"&&!W.error){this.recordProgressStep($,`Finished tool "${W.toolName??"unknown"}"`);return}if(W.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${W.iterations} iterations)`});return}if(W.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:W.error.message})}recordRunActivityFromAgentEvent($,W){let Z;switch(W.type){case"iteration_start":Z=`iteration_${W.iteration}_started`;break;case"content_start":if(W.contentType==="tool")Z=`running_tool_${W.toolName??"unknown"}`;break;case"content_end":if(W.contentType==="tool")Z=W.error?this.formatProgressErrorActivity(`tool_${W.toolName??"unknown"}_error`,W.error):`finished_tool_${W.toolName??"unknown"}`;break;case"done":Z="finalizing_response";break;case"error":Z=this.formatProgressErrorActivity("run_error",W.error.message);break;default:break}if(!Z)return;for(let Q of this.runs.values()){if(Q.agentId!==$||Q.status!=="running")continue;this.recordRunProgress(Q,Z)}}recordRunProgress($,W){let Z=new Date;$.heartbeatAt=Z,$.lastProgressAt=Z,$.lastProgressMessage=W,$.currentActivity=W,this.emitEvent({type:m.RunProgress,run:{...$},message:W})}formatProgressErrorActivity($,W){let Z=W.replace(/\s+/g," ").trim();if(Z.length===0)return $;let Q=Z.length>240?`${Z.slice(0,237).trimEnd()}...`:Z;return`${$}: ${Q}`}recordProgressStep($,W,Z,Q=!1){this.missionStepCounter++;let J=this.members.get($);if(!J)return;let j=this.missionStepCounter-J.lastMissionStep,X=Date.now()-J.lastMissionAt;if(!Q&&j<this.missionLogIntervalSteps&&X<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Z,kind:"progress",summary:W})}buildMailboxNotification($){if($.length===0)return"";let W=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Z of $)W.push(`--- Message from ${Z.fromAgentId} | subject: ${Z.subject} ---`),W.push(Z.body);return W.push("---"),W.join(`
532
+ `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function TU($){return new Promise((W)=>setTimeout(W,$))}function b6($,W){let Z=0;for(let Q of $){if(!Q.startsWith(W))continue;let J=Number.parseInt(Q.slice(W.length),10);if(Number.isFinite(J))Z=Math.max(Z,J)}return Z}function gj($,W){switch(W.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(W.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Z;if(W.type==="run_failed")Z=W.run.error;else if(W.type==="run_cancelled"||W.type==="run_interrupted")Z=W.run.error??W.reason;$.activeTeamRunIds.delete(W.run.id),$.pendingTeamRunUpdates.push({runId:W.run.id,agentId:W.run.agentId,taskId:W.run.taskId,status:W.type.replace("run_",""),error:Z,iterations:W.run.result?.iterations}),EQ($);break}default:break}}async function mj($,W,Z){switch(W.type){case"run_progress":await Z("onTeamTaskProgress",$,W.run.agentId,W.message,{kind:W.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(W.event.type==="content_start"&&W.event.contentType==="text"&&typeof W.event.text==="string"){let Q=W.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Q)await Z("onTeamTaskProgress",$,W.agentId,Q,{kind:"text"})}break;case"task_start":await Z("onTeamTaskStart",$,W.agentId,W.message);break;case"task_end":{if(W.error)await Z("onTeamTaskEnd",$,W.agentId,"failed",`[error] ${W.error.message}`,void 0,W.messages);else if(W.result?.finishReason==="aborted")await Z("onTeamTaskEnd",$,W.agentId,"cancelled","[done] aborted",W.result,W.result.messages);else await Z("onTeamTaskEnd",$,W.agentId,"completed",`[done] ${W.result?.finishReason??"completed"}`,W.result,W.result?.messages);break}default:break}}function vj($,W,Z,Q){if(!$.runtime.teamRuntime)return;let J=$.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:W,teamName:J,lifecycle:S6({teamName:J,sessionId:W,event:Z}),summary:P6(J,$.runtime.teamRuntime.exportState())}})}function H9($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function cj($,W){if($.aborting)return!1;if(!(W==="completed"||W==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&H9($)}function EQ($){let W=$.teamRunWaiters.splice(0);for(let Z of W)Z()}async function uj($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let W=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,W}if($.activeTeamRunIds.size===0)return[];await new Promise((W)=>{$.teamRunWaiters.push(W)})}}function dj($,W){let Z=W.map((j)=>{let X=[`- ${j.runId} (${j.agentId}) -> ${j.status}`];if(j.taskId)X.push(` task=${j.taskId}`);if(typeof j.iterations==="number")X.push(` iterations=${j.iterations}`);if(j.error)X.push(` error=${j.error}`);return X.join("")}),Q=$.activeTeamRunIds.size,J=Q>0?`There are still ${Q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return G9(`System-delivered teammate async run updates:
533
533
  ${Z.join(`
534
534
  `)}
535
535
 
536
- ${J}`,$.config.mode)}function G9($,W){return Gy($,W==="plan"?"plan":W==="yolo"?"yolo":"act")}var dj=4;class B${adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,W={}){this.adapter=$;this.manifestStore=new bj($,W.messagesArtifactUploader,W.logger),this.teamChildren=new qQ($,this.manifestStore,(Z,Q,J)=>this.toPersistedMessages(Z,Q,J),B$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,W,Z){if(!$)return;return W?DZ(W.messages,W,Z):UZ($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,W){this.manifestStore.writeSessionManifest($,W)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let W=$.startedAt??X0(),Z=$.sessionId.trim(),Q=Z.length>0?Z:`${Date.now()}_${Fy(5)}`,J=this.manifestStore.artifacts.sessionMessagesPath(Q),j=this.manifestStore.artifacts.sessionCompactionPath(Q),X=this.manifestStore.artifacts.sessionManifestPath(Q),Y=G5({metadata:$.metadata,prompt:$.prompt}),V={version:1,session_id:Q,source:$.source,pid:$.pid,started_at:W,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:Y,messages_path:J};return await this.adapter.upsertSession({sessionId:Q,source:$.source,pid:$.pid,startedAt:W,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:V.prompt??null,metadata:h$(V.metadata),hookPath:"",messagesPath:J,updatedAt:X0()}),this.manifestStore.initializeMessagesFile(Q,J,W),this.manifestStore.writeSessionManifest(X,V),{manifestPath:X,messagesPath:J,compactionPath:j,manifest:V}}async updateSessionStatus($,W,Z){let Q;if((await UK(()=>this.adapter.getSession($),async(j)=>{return Q=K0(W)?void 0:X0(),this.adapter.updateSession({sessionId:$,status:W,endedAt:Q??null,exitCode:K0(W)?null:typeof Z==="number"?Z:null,expectedStatusLock:j.statusLock})},dj)).updated){if(W==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession($){for(let W=0;W<dj;W++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return{updated:!1};let Q=Z.metadata??void 0,J=$.metadata!==void 0?h$($.metadata)??{}:h$(Q)??{},j=k2(typeof Q?.title==="string"?Q.title:void 0),X=$.title!==void 0?k2($.title):j??DJ($.prompt);if(X)J.title=X;else delete J.title;let Y=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:Y?Object.keys(J).length>0?J:null:void 0,title:X,expectedStatusLock:Z.statusLock})).updated)continue;let{path:B,manifest:H}=this.manifestStore.readManifestFile($.sessionId);if(H){if($.prompt!==void 0)H.prompt=$.prompt??void 0;let G=$.metadata!==void 0?h$($.metadata)??{}:h$(H.metadata)??{};if(X)G.title=X;H.metadata=Object.keys(G).length>0?G:void 0,this.manifestStore.writeSessionManifest(B,H)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,W){return this.teamChildren.appendSubagentHookAudit(W),Promise.resolve()}persistSessionMessages($,W,Z){let Q=UZ(W);return this.manifestStore.persistSessionMessages($,Q,Z)}async readSessionCompactionState($){return await this.manifestStore.readSessionCompactionState($)}async persistSessionCompactionState($,W){await this.manifestStore.persistSessionCompactionState($,W)}async deleteSessionCompactionState($){await this.manifestStore.deleteSessionCompactionState($)}applySubagentStatus($,W){return this.teamChildren.applySubagentStatus($,W)}applySubagentStatusBySessionId($,W){return this.teamChildren.applySubagentStatusBySessionId($,W)}applyStatusToRunningChildSessions($,W){return this.teamChildren.applyStatusToRunningChildSessions($,W)}onTeamTaskStart($,W,Z){return this.teamChildren.onTeamTaskStart($,W,Z)}onTeamTaskEnd($,W,Z,Q,J,j){return this.teamChildren.onTeamTaskEnd($,W,Z,Q,J,j)}onTeamTaskProgress($,W,Z,Q){return this.teamChildren.onTeamTaskProgress($,W,Z,Q)}handleSubAgentStart($,W){return this.teamChildren.handleSubAgentStart($,W)}handleSubAgentEnd($,W){return this.teamChildren.handleSubAgentEnd($,W)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(W){return typeof W==="object"&&W!==null&&"code"in W&&W.code==="EPERM"}}async reconcileDeadRunningSession($){if(K0($.status)===!1||this.isPidAlive($.pid))return $;let W=X0(),Z=B$.STALE_REASON;for(let Q=0;Q<dj;Q++){let J=await this.adapter.getSession($.sessionId);if(!J)return;if(K0(J.status)===!1)return J;let j={...J.metadata??{},terminal_marker:Z,terminal_marker_at:W,terminal_marker_pid:J.pid,terminal_marker_source:B$.STALE_SOURCE},X=await this.adapter.updateSession({sessionId:J.sessionId,status:"failed",endedAt:W,exitCode:1,metadata:j,expectedStatusLock:J.statusLock});if(!X.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(J.sessionId,"failed");let Y=AK(J,{status:"failed",endedAt:W,exitCode:1,metadata:j}),{path:V}=this.manifestStore.readManifestFile(J.sessionId);return this.manifestStore.writeSessionManifest(V,Y),this.manifestStore.appendStaleSessionHookLog(W,J.sessionId,J.pid,Z,B$.STALE_SOURCE),{...J,status:"failed",endedAt:W,exitCode:1,metadata:j,statusLock:X.statusLock,updatedAt:W}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let W=Math.max(1,Math.floor($)),Z=Math.min(W*5,2000);await this.reconcileDeadSessions(Z);let Q=(await this.adapter.listSessions({limit:Z})).slice(0,W),J=await Promise.all(Q.map((j)=>this.manifestStore.readSessionManifestTitle(j.sessionId)));return Q.map((j,X)=>{let Y=h$(j.metadata??void 0),V=k2(J[X]),B=V?{...Y??{},title:V}:Y;return{...j,metadata:B}})}async reconcileDeadSessions($=2000){let W=Math.max(1,Math.floor($)),Z=(await Promise.all(["idle","running","pending"].map((J)=>this.adapter.listSessions({limit:W,status:J})))).flat(),Q=0;for(let J of Z){let j=await this.reconcileDeadRunningSession(J);if(j&&j.status!==J.status)Q++}return Q}async deleteSession($){let W=$.trim();if(!W)throw Error("session id is required");let Z=await this.adapter.getSession(W);if(!Z)return{deleted:!1};if(await this.adapter.deleteSession(W,!1),!Z.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:W});await this.adapter.deleteSession(W,!0),await Promise.allSettled(Q.map(async(J)=>{await xJ(J.cwd,J.sessionId),C5(J.messagesPath),await this.deleteSessionCompactionStateIfExists(J.sessionId),C5(this.manifestStore.artifacts.sessionManifestPath(J.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(J.sessionId)}))}if(await xJ(Z.cwd,W),C5(Z.messagesPath),await this.deleteSessionCompactionStateIfExists(W),C5(this.manifestStore.artifacts.sessionManifestPath(W,!1)),Z.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(W);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir(W)]);for(let J of[Z.messagesPath])if(typeof J==="string"&&J.trim().length>0)Q.add(Ky(J));for(let J of Q)this.manifestStore.artifacts.removeDir(J)}return{deleted:!0}}async deleteSessionCompactionStateIfExists($){try{await this.manifestStore.deleteSessionCompactionState($)}catch{}}}function pj(){return new Date().toISOString()}function MU($,W){let Z=`${$}.tmp`;Dy(Z,`${JSON.stringify(W,null,2)}
537
- `,"utf8"),Uy(Z,$)}class RU{sessionsDirPath;constructor($=_y()){this.sessionsDirPath=$}ensureSessionsDir(){if(!lj(this.sessionsDirPath))Ay(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return qU(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return qU(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!lj($))return{version:1,sessions:{}};try{let W=JSON.parse(zU($,"utf8"));if(W?.version===1&&W.sessions)return W}catch{}return{version:1,sessions:{}}}writeIndex($){MU(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!lj($))return{version:1,nextId:1,requests:[]};try{let W=JSON.parse(zU($,"utf8"));if(W?.version===1&&typeof W.nextId==="number"&&Array.isArray(W.requests))return W}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){MU(this.spawnQueuePath(),$)}async upsertSession($){let W=this.readIndex();W.sessions[$.sessionId]=$,this.writeIndex(W)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((W)=>$.parentSessionId!==void 0?W.parentSessionId===$.parentSessionId:!0).filter((W)=>$.status!==void 0?W.status===$.status:!0).sort((W,Z)=>Z.startedAt.localeCompare(W.startedAt)).slice(0,$.limit)}async updateSession($){let W=this.readIndex(),Z=W.sessions[$.sessionId];if(!Z)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Z.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Z.statusLock};let Q=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Z.statusLock,J={...Z,status:$.status??Z.status,endedAt:$.endedAt!==void 0?$.endedAt:Z.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Z.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Z.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Z.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Z.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Z.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Z.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Z.conversationId??null,statusLock:Q,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Z.isSubagent,updatedAt:pj()};if($.setRunning)J.status="running",J.endedAt=null,J.exitCode=null;return W.sessions[$.sessionId]=J,this.writeIndex(W),{updated:!0,statusLock:J.statusLock}}async deleteSession($,W){let Z=this.readIndex();if(!Z.sessions[$])return!1;if(delete Z.sessions[$],W){for(let J of Object.values(Z.sessions))if(J.parentSessionId===$)delete Z.sessions[J.sessionId]}return this.writeIndex(Z),!0}async enqueueSpawnRequest($){let W=this.readQueue();W.requests.push({id:W.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:pj()}),W.nextId+=1,this.writeQueue(W)}async claimSpawnRequest($,W){let Z=this.readQueue(),Q=Z.requests.find((J)=>J.rootSessionId===$&&J.parentAgentId===W&&!J.consumedAt);if(!Q)return;return Q.consumedAt=pj(),this.writeQueue(Z),Q.task}}class rj extends B${constructor($,W={}){super(new RU($),W)}ensureSessionsDir(){return super.ensureSessionsDir()}}var wU={};w(wU,{CoreSessionService:()=>S1});import{existsSync as fy,mkdirSync as Ly}from"node:fs";import{resolveSessionDataDir as Ty}from"@cline/shared/storage";var ij=`
536
+ ${J}`,$.config.mode)}function G9($,W){return Ky($,W==="plan"?"plan":W==="yolo"?"yolo":"act")}var lj=4;class B${adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,W={}){this.adapter=$;this.manifestStore=new yj($,W.messagesArtifactUploader,W.logger),this.teamChildren=new MQ($,this.manifestStore,(Z,Q,J)=>this.toPersistedMessages(Z,Q,J),B$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,W,Z){if(!$)return;return W?_Z(W.messages,W,Z):DZ($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,W){this.manifestStore.writeSessionManifest($,W)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let W=$.startedAt??X0(),Z=$.sessionId.trim(),Q=Z.length>0?Z:`${Date.now()}_${Ay(5)}`,J=this.manifestStore.artifacts.sessionMessagesPath(Q),j=this.manifestStore.artifacts.sessionCompactionPath(Q),X=this.manifestStore.artifacts.sessionManifestPath(Q),Y=G5({metadata:$.metadata,prompt:$.prompt}),V={version:1,session_id:Q,source:$.source,pid:$.pid,started_at:W,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:Y,messages_path:J};return await this.adapter.upsertSession({sessionId:Q,source:$.source,pid:$.pid,startedAt:W,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:V.prompt??null,metadata:h$(V.metadata),hookPath:"",messagesPath:J,updatedAt:X0()}),this.manifestStore.initializeMessagesFile(Q,J,W),this.manifestStore.writeSessionManifest(X,V),{manifestPath:X,messagesPath:J,compactionPath:j,manifest:V}}async updateSessionStatus($,W,Z){let Q;if((await DK(()=>this.adapter.getSession($),async(j)=>{return Q=K0(W)?void 0:X0(),this.adapter.updateSession({sessionId:$,status:W,endedAt:Q??null,exitCode:K0(W)?null:typeof Z==="number"?Z:null,expectedStatusLock:j.statusLock})},lj)).updated){if(W==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession($){for(let W=0;W<lj;W++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return{updated:!1};let Q=Z.metadata??void 0,J=$.metadata!==void 0?h$($.metadata)??{}:h$(Q)??{},j=k2(typeof Q?.title==="string"?Q.title:void 0),X=$.title!==void 0?k2($.title):j??_J($.prompt);if(X)J.title=X;else delete J.title;let Y=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:Y?Object.keys(J).length>0?J:null:void 0,title:X,expectedStatusLock:Z.statusLock})).updated)continue;let{path:B,manifest:H}=this.manifestStore.readManifestFile($.sessionId);if(H){if($.prompt!==void 0)H.prompt=$.prompt??void 0;let G=$.metadata!==void 0?h$($.metadata)??{}:h$(H.metadata)??{};if(X)G.title=X;H.metadata=Object.keys(G).length>0?G:void 0,this.manifestStore.writeSessionManifest(B,H)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,W){return this.teamChildren.appendSubagentHookAudit(W),Promise.resolve()}persistSessionMessages($,W,Z){let Q=DZ(W);return this.manifestStore.persistSessionMessages($,Q,Z)}async readSessionCompactionState($){return await this.manifestStore.readSessionCompactionState($)}async persistSessionCompactionState($,W){await this.manifestStore.persistSessionCompactionState($,W)}async deleteSessionCompactionState($){await this.manifestStore.deleteSessionCompactionState($)}applySubagentStatus($,W){return this.teamChildren.applySubagentStatus($,W)}applySubagentStatusBySessionId($,W){return this.teamChildren.applySubagentStatusBySessionId($,W)}applyStatusToRunningChildSessions($,W){return this.teamChildren.applyStatusToRunningChildSessions($,W)}onTeamTaskStart($,W,Z){return this.teamChildren.onTeamTaskStart($,W,Z)}onTeamTaskEnd($,W,Z,Q,J,j){return this.teamChildren.onTeamTaskEnd($,W,Z,Q,J,j)}onTeamTaskProgress($,W,Z,Q){return this.teamChildren.onTeamTaskProgress($,W,Z,Q)}handleSubAgentStart($,W){return this.teamChildren.handleSubAgentStart($,W)}handleSubAgentEnd($,W){return this.teamChildren.handleSubAgentEnd($,W)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(W){return typeof W==="object"&&W!==null&&"code"in W&&W.code==="EPERM"}}async reconcileDeadRunningSession($){if(K0($.status)===!1||this.isPidAlive($.pid))return $;let W=X0(),Z=B$.STALE_REASON;for(let Q=0;Q<lj;Q++){let J=await this.adapter.getSession($.sessionId);if(!J)return;if(K0(J.status)===!1)return J;let j={...J.metadata??{},terminal_marker:Z,terminal_marker_at:W,terminal_marker_pid:J.pid,terminal_marker_source:B$.STALE_SOURCE},X=await this.adapter.updateSession({sessionId:J.sessionId,status:"failed",endedAt:W,exitCode:1,metadata:j,expectedStatusLock:J.statusLock});if(!X.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(J.sessionId,"failed");let Y=UK(J,{status:"failed",endedAt:W,exitCode:1,metadata:j}),{path:V}=this.manifestStore.readManifestFile(J.sessionId);return this.manifestStore.writeSessionManifest(V,Y),this.manifestStore.appendStaleSessionHookLog(W,J.sessionId,J.pid,Z,B$.STALE_SOURCE),{...J,status:"failed",endedAt:W,exitCode:1,metadata:j,statusLock:X.statusLock,updatedAt:W}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let W=Math.max(1,Math.floor($)),Z=Math.min(W*5,2000);await this.reconcileDeadSessions(Z);let Q=(await this.adapter.listSessions({limit:Z})).slice(0,W),J=await Promise.all(Q.map((j)=>this.manifestStore.readSessionManifestTitle(j.sessionId)));return Q.map((j,X)=>{let Y=h$(j.metadata??void 0),V=k2(J[X]),B=V?{...Y??{},title:V}:Y;return{...j,metadata:B}})}async reconcileDeadSessions($=2000){let W=Math.max(1,Math.floor($)),Z=(await Promise.all(["idle","running","pending"].map((J)=>this.adapter.listSessions({limit:W,status:J})))).flat(),Q=0;for(let J of Z){let j=await this.reconcileDeadRunningSession(J);if(j&&j.status!==J.status)Q++}return Q}async deleteSession($){let W=$.trim();if(!W)throw Error("session id is required");let Z=await this.adapter.getSession(W);if(!Z)return{deleted:!1};if(await this.adapter.deleteSession(W,!1),!Z.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:W});await this.adapter.deleteSession(W,!0),await Promise.allSettled(Q.map(async(J)=>{await gJ(J.cwd,J.sessionId),C5(J.messagesPath),await this.deleteSessionCompactionStateIfExists(J.sessionId),C5(this.manifestStore.artifacts.sessionManifestPath(J.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(J.sessionId)}))}if(await gJ(Z.cwd,W),C5(Z.messagesPath),await this.deleteSessionCompactionStateIfExists(W),C5(this.manifestStore.artifacts.sessionManifestPath(W,!1)),Z.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(W);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir(W)]);for(let J of[Z.messagesPath])if(typeof J==="string"&&J.trim().length>0)Q.add(Fy(J));for(let J of Q)this.manifestStore.artifacts.removeDir(J)}return{deleted:!0}}async deleteSessionCompactionStateIfExists($){try{await this.manifestStore.deleteSessionCompactionState($)}catch{}}}function rj(){return new Date().toISOString()}function RU($,W){let Z=`${$}.tmp`;_y(Z,`${JSON.stringify(W,null,2)}
537
+ `,"utf8"),Dy(Z,$)}class EU{sessionsDirPath;constructor($=fy()){this.sessionsDirPath=$}ensureSessionsDir(){if(!pj(this.sessionsDirPath))Uy(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return MU(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return MU(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!pj($))return{version:1,sessions:{}};try{let W=JSON.parse(qU($,"utf8"));if(W?.version===1&&W.sessions)return W}catch{}return{version:1,sessions:{}}}writeIndex($){RU(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!pj($))return{version:1,nextId:1,requests:[]};try{let W=JSON.parse(qU($,"utf8"));if(W?.version===1&&typeof W.nextId==="number"&&Array.isArray(W.requests))return W}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){RU(this.spawnQueuePath(),$)}async upsertSession($){let W=this.readIndex();W.sessions[$.sessionId]=$,this.writeIndex(W)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((W)=>$.parentSessionId!==void 0?W.parentSessionId===$.parentSessionId:!0).filter((W)=>$.status!==void 0?W.status===$.status:!0).sort((W,Z)=>Z.startedAt.localeCompare(W.startedAt)).slice(0,$.limit)}async updateSession($){let W=this.readIndex(),Z=W.sessions[$.sessionId];if(!Z)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Z.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Z.statusLock};let Q=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Z.statusLock,J={...Z,status:$.status??Z.status,endedAt:$.endedAt!==void 0?$.endedAt:Z.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Z.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Z.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Z.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Z.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Z.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Z.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Z.conversationId??null,statusLock:Q,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Z.isSubagent,updatedAt:rj()};if($.setRunning)J.status="running",J.endedAt=null,J.exitCode=null;return W.sessions[$.sessionId]=J,this.writeIndex(W),{updated:!0,statusLock:J.statusLock}}async deleteSession($,W){let Z=this.readIndex();if(!Z.sessions[$])return!1;if(delete Z.sessions[$],W){for(let J of Object.values(Z.sessions))if(J.parentSessionId===$)delete Z.sessions[J.sessionId]}return this.writeIndex(Z),!0}async enqueueSpawnRequest($){let W=this.readQueue();W.requests.push({id:W.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:rj()}),W.nextId+=1,this.writeQueue(W)}async claimSpawnRequest($,W){let Z=this.readQueue(),Q=Z.requests.find((J)=>J.rootSessionId===$&&J.parentAgentId===W&&!J.consumedAt);if(!Q)return;return Q.consumedAt=rj(),this.writeQueue(Z),Q.task}}class ij extends B${constructor($,W={}){super(new EU($),W)}ensureSessionsDir(){return super.ensureSessionsDir()}}var CU={};w(CU,{CoreSessionService:()=>S1});import{existsSync as Ly,mkdirSync as Ty}from"node:fs";import{resolveSessionDataDir as Oy}from"@cline/shared/storage";var nj=`
538
538
  session_id AS sessionId,
539
539
  source,
540
540
  pid,
@@ -561,33 +561,33 @@ ${J}`,$.config.mode)}function G9($,W){return Gy($,W==="plan"?"plan":W==="yolo"?"
561
561
  metadata_json AS metadata,
562
562
  hook_path AS hookPath,
563
563
  messages_path AS messagesPath,
564
- updated_at AS updatedAt`;function nj($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let W=$.metadata;if(typeof W==="string"&&W.trim())try{let Z=JSON.parse(W);$.metadata=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z:null}catch{$.metadata=null}else $.metadata=null;return $}function aj($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function EU($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class NU{store;sessionsDirPath;constructor($,W=Ty()){this.store=$;this.sessionsDirPath=W}ensureSessionsDir(){if(!fy(this.sessionsDirPath))Ly(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
564
+ updated_at AS updatedAt`;function aj($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let W=$.metadata;if(typeof W==="string"&&W.trim())try{let Z=JSON.parse(W);$.metadata=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z:null}catch{$.metadata=null}else $.metadata=null;return $}function oj($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function NU($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class wU{store;sessionsDirPath;constructor($,W=Oy()){this.store=$;this.sessionsDirPath=W}ensureSessionsDir(){if(!Ly(this.sessionsDirPath))Ty(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
565
565
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
566
566
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
567
567
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
568
568
  metadata_json, transcript_path, hook_path, messages_path, updated_at
569
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.isSubagent?1:0,$.prompt??null,aj($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let W=this.store.queryOne(`SELECT ${ij} FROM sessions WHERE session_id = ?`,[$]);return W?nj(W):void 0}async listSessions($){let W=[],Z=[];if($.parentSessionId)W.push("parent_session_id = ?"),Z.push($.parentSessionId);if($.status)W.push("status = ?"),Z.push($.status);let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${ij}
569
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.isSubagent?1:0,$.prompt??null,oj($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let W=this.store.queryOne(`SELECT ${nj} FROM sessions WHERE session_id = ?`,[$]);return W?aj(W):void 0}async listSessions($){let W=[],Z=[];if($.parentSessionId)W.push("parent_session_id = ?"),Z.push($.parentSessionId);if($.status)W.push("status = ?"),Z.push($.status);let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${nj}
570
570
  FROM sessions
571
571
  ${Q}
572
572
  ORDER BY started_at DESC
573
- LIMIT ?`,[...Z,$.limit]).map(nj)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
573
+ LIMIT ?`,[...Z,$.limit]).map(aj)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
574
574
  SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
575
575
  parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
576
576
  prompt = COALESCE(prompt, ?)
577
- WHERE session_id = ? AND status_lock = ?`,[X0(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let W=[],Z=[];if($.status!==void 0)W.push("status = ?"),Z.push($.status);if($.endedAt!==void 0)W.push("ended_at = ?"),Z.push($.endedAt);if($.exitCode!==void 0)W.push("exit_code = ?"),Z.push($.exitCode);if($.prompt!==void 0)W.push("prompt = ?"),Z.push($.prompt??null);if($.metadata!==void 0)W.push("metadata_json = ?"),Z.push(aj($.metadata));if($.parentSessionId!==void 0)W.push("parent_session_id = ?"),Z.push($.parentSessionId??null);if($.parentAgentId!==void 0)W.push("parent_agent_id = ?"),Z.push($.parentAgentId??null);if($.agentId!==void 0)W.push("agent_id = ?"),Z.push($.agentId??null);if($.conversationId!==void 0)W.push("conversation_id = ?"),Z.push($.conversationId??null);if(W.length===0){let X=await this.getSession($.sessionId);return{updated:!!X,statusLock:X?.statusLock??0}}let Q=0;if($.expectedStatusLock!==void 0)Q=$.expectedStatusLock+1,W.push("status_lock = ?"),Z.push(Q);W.push("updated_at = ?"),Z.push(X0());let J=`UPDATE sessions SET ${W.join(", ")} WHERE session_id = ?`;if(Z.push($.sessionId),$.expectedStatusLock!==void 0)J+=" AND status_lock = ?",Z.push($.expectedStatusLock);if((this.store.run(J,Z).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Q=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Q}}async deleteSession($,W){let Z=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(W)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Z>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
577
+ WHERE session_id = ? AND status_lock = ?`,[X0(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let W=[],Z=[];if($.status!==void 0)W.push("status = ?"),Z.push($.status);if($.endedAt!==void 0)W.push("ended_at = ?"),Z.push($.endedAt);if($.exitCode!==void 0)W.push("exit_code = ?"),Z.push($.exitCode);if($.prompt!==void 0)W.push("prompt = ?"),Z.push($.prompt??null);if($.metadata!==void 0)W.push("metadata_json = ?"),Z.push(oj($.metadata));if($.parentSessionId!==void 0)W.push("parent_session_id = ?"),Z.push($.parentSessionId??null);if($.parentAgentId!==void 0)W.push("parent_agent_id = ?"),Z.push($.parentAgentId??null);if($.agentId!==void 0)W.push("agent_id = ?"),Z.push($.agentId??null);if($.conversationId!==void 0)W.push("conversation_id = ?"),Z.push($.conversationId??null);if(W.length===0){let X=await this.getSession($.sessionId);return{updated:!!X,statusLock:X?.statusLock??0}}let Q=0;if($.expectedStatusLock!==void 0)Q=$.expectedStatusLock+1,W.push("status_lock = ?"),Z.push(Q);W.push("updated_at = ?"),Z.push(X0());let J=`UPDATE sessions SET ${W.join(", ")} WHERE session_id = ?`;if(Z.push($.sessionId),$.expectedStatusLock!==void 0)J+=" AND status_lock = ?",Z.push($.expectedStatusLock);if((this.store.run(J,Z).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Q=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Q}}async deleteSession($,W){let Z=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(W)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Z>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
578
578
  VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,X0()])}async claimSpawnRequest($,W){let Z=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
579
579
  WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
580
- ORDER BY id ASC LIMIT 1`,[$,W]);if(!Z||typeof Z.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[X0(),Z.id]),Z.task??void 0}}class S1 extends B${store;constructor($,W={}){super(new NU($,W.sessionArtifactsDir),W);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
580
+ ORDER BY id ASC LIMIT 1`,[$,W]);if(!Z||typeof Z.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[X0(),Z.id]),Z.task??void 0}}class S1 extends B${store;constructor($,W={}){super(new wU($,W.sessionArtifactsDir),W);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
581
581
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
582
582
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
583
583
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
584
584
  metadata_json, transcript_path, hook_path, messages_path, updated_at
585
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"","",$.messagesPath,X0()])}}function Oy($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let W=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(W==="local"||W==="hub"||W==="remote")return W;return"auto"}var K9,F9;function zy($,W){if($!=="auto"&&$!=="hub")return;if(W.hub?.endpoint?.trim())return;RW(W.hub?.workspaceRoot?.trim()||W.hub?.cwd?.trim()||process.cwd())}async function qy($){await $.reconcileDeadSessions?.().catch(()=>{})}function SU($){try{let W=new C1;return W.init(),new S1(W,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(W){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),PU($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:W,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new rj(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function CU($,W,Z){return new b1({sessionService:Z??$.sessionService??SU($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:W,fetch:$.fetch})}async function oj($){if(K9)return K9;if(F9)return await F9;return F9=(async()=>{return K9=SU($),await qy(K9),K9})().finally(()=>{F9=void 0}),await F9}async function h6($){let W=x0($.distinctId);$.telemetry?.setDistinctId(W);let Z=Oy($);if(zy(Z,$),Z==="remote"){let Q=$.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Q}),new N6({endpoint:Q,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Z==="hub"){let Q=$.hub?.endpoint?.trim(),J=Q||await H2({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!J)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:J,explicitEndpoint:Q||void 0}),new Y$({url:J,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Z==="auto"){let Q=await T4({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Q){$.logger?.log("Using discovered local hub runtime host",{url:Q});let J=new Y$({url:Q,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await J.connect(),J}catch(j){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:j}),PU($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:j,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),CU($,W)}return CU($,W)}var kU={};w(kU,{NoOpFeatureFlagsProvider:()=>W8,FeatureFlagsService:()=>$8});import{existsSync as My,mkdirSync as Ry,readFileSync as Ey,writeFileSync as Ny}from"node:fs";import{dirname as wy}from"node:path";import{FEATURE_FLAGS as yU,FeatureFlagDefaultValue as sj}from"@cline/shared";var Cy=3600000,Py=604800000,hU=1;class $8{provider;telemetry;logger;cacheTtlMs;cacheFilePath;persistentCacheMaxAgeMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};constructor($){this.provider=$.provider,this.telemetry=$.telemetry,this.logger=$.logger,this.cacheTtlMs=$.cacheTtlMs??Cy,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??Py,this.context={...$.context??{}},this.hydrateFromPersistentCache()}setContext($){this.context={...$}}hydrateCache($){this.cacheInfo={updateTime:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload},this.rebuildCacheFromSnapshot($.flagsPayload)}getCacheSnapshot(){return{updateTime:this.cacheInfo.updateTime,userId:this.cacheInfo.userId,flagsPayload:this.cacheInfo.flagsPayload}}async poll($){let W=$??this.context.userId??null,Z=Date.now();if(Z-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===W)return}let Q=this.cacheInfo;this.cacheInfo={updateTime:Z,userId:W||null};try{let J=await this.provider.getAllFlagsAndPayloads({flagKeys:yU.length>0?yU:void 0,context:{...this.context,userId:W}});if(this.cacheInfo.userId!==W)return;this.cacheInfo.flagsPayload=J,this.rebuildCacheFromSnapshot(J),this.writePersistentCache()}catch(J){if(this.cacheInfo.userId!==W)return;throw this.cacheInfo=Q.updateTime?Q:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:J}),J}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((W)=>this.isFeatureFlagPayload(W));if(typeof $==="object")return Object.values($).every((W)=>this.isFeatureFlagPayload(W));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=Object.entries($).filter(([,Q])=>this.isFeatureFlagPayload(Q));if(W.length===0)return;let Z={};for(let[Q,J]of W)Z[Q]=J;return Z}readPersistentCache(){try{if(!this.cacheFilePath||!My(this.cacheFilePath))return;let $=JSON.parse(Ey(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let W=$;if(W.version!==hU||typeof W.updatedAt!=="number"||!Number.isFinite(W.updatedAt)||Date.now()-W.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:W.updatedAt,userId:W.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(W.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(W.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;Ry(wy(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),W={version:hU,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};Ny(this.cacheFilePath,`${JSON.stringify(W,null,2)}
586
- `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let W=new Map;for(let Z of this.getReturnedFlagKeys($)){let Q=this.getFeatureFlag(Z);W.set(Z,Q??!1)}this.cache=W}getFeatureFlag($){try{let W=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Z=this.cacheInfo.flagsPayload?.featureFlags?.[$],Q=W??Z??sj[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Q)this.telemetry?.capture({event:v.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Z}});return Q}catch(W){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:W}),sj[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??sj[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,W){if(process.env.IS_TEST==="true")this.cache.set($,W)}async dispose(){await this.provider.dispose()}}class W8{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}O8();var uU={};w(uU,{createCheckpointComparePlan:()=>NQ,compareCheckpointToWorkspace:()=>A9,buildCheckpointWorkspaceDiff:()=>wQ});import{execFile as yy}from"node:child_process";import*as vU from"node:fs/promises";import*as x6 from"node:path";import{promisify as hy}from"node:util";var gU={};w(gU,{trimMessagesToCheckpoint:()=>xU,trimMessagesBeforeCheckpoint:()=>ej,readSessionCheckpointHistory:()=>Z8,findCheckpointForRun:()=>I6,createRestoredCheckpointMetadata:()=>tj,createCheckpointRestorePlan:()=>$X,applyCheckpointToWorktree:()=>WX});import{execFile as Sy}from"node:child_process";import{promisify as by}from"node:util";var k6=by(Sy);function Z8($){let W=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(W?.history)?W.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let J=String(Q.ref??"").trim(),j=Number(Q.createdAt??0),X=Number(Q.runCount??0);if(J.length===0||!Number.isFinite(j)||!Number.isInteger(X)||X<1)return[];let Y=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:J,createdAt:j,runCount:X,...Y?{kind:Y}:{}}]})}function tj($,W){let Z=Z8($).filter((J)=>J.runCount<=W),Q=Z.at(-1);return Q?{latest:Q,history:Z}:void 0}function I6($,W){return $.reduce((Z,Q)=>{if(Q.runCount>W)return Z;if(!Z||Q.runCount>Z.runCount)return Q;return Z},void 0)}function IU($,W){let Z=0;for(let Q=0;Q<$.length;Q+=1){let J=$[Q];if(J?.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"?J.metadata:void 0)?.kind==="recovery_notice")continue;if(Z+=1,Z===W)return Q}throw Error(`Could not find user message for checkpoint run ${W}`)}function xU($,W){let Z=IU($,W);return $.slice(0,Z+1)}function ej($,W){let Z=IU($,W);return $.slice(0,Z)}function $X($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=I6(Z8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Z,cwd:Q,...$.restoreMessages!==!1?{messages:xU($.messages??[],W)}:{}}}async function WX($,W){if((await k6("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await k6("git",["-C",$,"cat-file","-e",`${W.ref}^{commit}`],{windowsHide:!0}),await k6("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await k6("git",["-C",$,"clean","-fd"],{windowsHide:!0}),W.kind==="commit"){await k6("git",["-C",$,"reset","--hard",W.ref],{windowsHide:!0});return}await k6("git",["-C",$,"stash","apply",W.ref],{windowsHide:!0})}var ky=hy(yy),Iy=52428800;async function EQ($,W){let{stdout:Z}=await ky("git",["-C",$,...W],{windowsHide:!0,maxBuffer:Iy,encoding:"utf8"});return Z}function mU($){return $.split("\x00").filter(Boolean)}function cU($,W){let Z=x6.resolve($,W),Q=x6.relative($,Z);if(Q.startsWith("..")||x6.isAbsolute(Q))throw Error(`Checkpoint diff path escapes workspace: ${W}`);return Z}async function xy($,W,Z){try{return await EQ($,["show",`${W}:${Z}`])}catch{return""}}async function gy($,W){try{return await vU.readFile(cU($,W),"utf8")}catch{return""}}async function my($,W){await EQ($,["cat-file","-e",`${W.ref}^{tree}`]);let[Z,Q]=await Promise.all([EQ($,["diff","--name-only","-z",W.ref,"--"]),EQ($,["ls-files","--others","--exclude-standard","-z"])]);return[...new Set([...mU(Z),...mU(Q)])].sort((j,X)=>j.localeCompare(X))}function NQ($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=I6(Z8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to compare a checkpoint");return{checkpoint:Z,cwd:Q}}async function wQ($,W){let Z=await my($,W);return(await Promise.all(Z.map(async(J)=>{let[j,X]=await Promise.all([xy($,W.ref,J),gy($,J)]);return{filePath:cU($,J),leftContent:j,rightContent:X}}))).filter((J)=>J.leftContent!==J.rightContent)}async function A9($){let W=NQ($),Z=await wQ(W.cwd,W.checkpoint);return{...W,diffs:Z}}class U9{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,W,Z,Q,J,j,X,Y,V,B){this.clientName=W,this.runtimeAddress=Z,this.host=$,this.prepare=Q,this.capabilities=J,this.logger=j,this.telemetry=X,this.distinctId=Y,this.featureFlags=V,this.settings=RA($),this.pendingPrompts=EA($),this.automation=new eJ(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=B?new W9({workspaceRoot:B.workspaceRoot??process.cwd(),specs:{cronSpecsDir:B.cronSpecsDir??B.cronDir,scope:OF(B.cronScope),workspaceRoot:B.workspaceRoot},runtimeHandlers:zF({host:$,getExtensionContext:()=>eZ({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:B.dbPath,logger:B.logger,pollIntervalMs:B.pollIntervalMs,claimLeaseSeconds:B.claimLeaseSeconds,globalMaxConcurrency:B.globalMaxConcurrency,watcherDebounceMs:B.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((H)=>{if(H.type!=="ended")return;this.disposeSessionBootstrap(H.payload.sessionId)})}static async create($={}){let W=x0($.distinctId),Z=P0($.capabilities),Q={...$,capabilities:Z,distinctId:W},J=await h6(Q),j=TF($.automation),X=$.featureFlags||new $8({provider:new W8,telemetry:$.telemetry,logger:$.logger,context:{distinctId:W,clientName:$.clientName}}),Y=new U9(J,$.clientName,J.runtimeAddress,$.prepare,Z,$.logger,$.telemetry,W,X,j?{...j,logger:$.logger}:void 0);if(j&&j.autoStart!==!1)await Y.automation.start();return Y}async disposeSessionBootstrap($){let W=this.activeSessionBootstraps.get($);if(!W)return;this.activeSessionBootstraps.delete($),await Promise.resolve(W.dispose?.())}async start($){let W=NA($),Z=await this.prepare?.(W);try{let Q=Z?await Z.applyToStartSessionInput(W):W,J=await this.host.startSession(Dj(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(j)=>eZ({automationService:this.automationService,automation:this.automation,context:j,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Z)if(await this.host.getSession(J.sessionId))this.activeSessionBootstraps.set(J.sessionId,Z);else await Promise.resolve(Z.dispose?.());return wA({input:Q,sessionId:J.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),J}catch(Q){throw await Promise.resolve(Z?.dispose?.()),Q}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let W=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(W.map((Z)=>this.disposeSessionBootstrap(Z)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await TQ(this.host,$);list=async($=200,W={})=>await this.listHistory({...W,limit:$});delete=async($)=>{let W=await this.host.deleteSession($);if(W)await this.disposeSessionBootstrap($);return W};update=(...$)=>this.host.updateSession(...$);updateSessionCompactionState=(...$)=>this.host.updateSessionCompactionState(...$);readSessionCompactionState=(...$)=>this.host.readSessionCompactionState(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let W=$.start?Dj($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Z)=>eZ({automationService:this.automationService,automation:this.automation,context:Z,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:W})}async compareCheckpoint($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=await this.host.getSession(W);if(!Z)throw Error(`Session ${W} not found`);return A9({session:Z,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,W){return this.host.subscribe($,W)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()};updateSessionConnection=(...$)=>{return this.host.updateSessionConnection?.(...$)??Promise.resolve()}}var lU={};w(lU,{resolvePluginSkillDirectoriesFromPaths:()=>J$,resolvePluginConfigSearchPaths:()=>_5,resolveAndLoadAgentPlugins:()=>X6,resolveAgentPluginPaths:()=>Q$,loadAgentPluginsFromPathsWithDiagnostics:()=>x2,loadAgentPluginsFromPaths:()=>fZ,loadAgentPluginFromPath:()=>U5,discoverPluginModulePaths:()=>f5});var iU={};w(iU,{toHookConfigFileName:()=>O5,runSubprocessEvent:()=>g6,runHook:()=>v6,resolveHooksConfigSearchPaths:()=>L5,parseHookEventPayload:()=>m6,mergeAgentHooks:()=>c2,listHookConfigFiles:()=>I$,createSubprocessHooks:()=>SQ,createHookConfigFileHooks:()=>z5,createHookConfigFileExtension:()=>H6,createHookAuditHooks:()=>B6,createAgentHooksExtension:()=>Y6,HookEventPayloadSchema:()=>PQ,HookEventNameSchema:()=>CQ,HookConfigFileName:()=>V6,HOOK_CONFIG_FILE_EVENT_MAP:()=>T5,HOOKS_CONFIG_DIRECTORY_NAME:()=>MZ});import{HookEventNameSchema as CQ,HookEventPayloadSchema as PQ,parseHookEventPayload as m6,resolveHookSessionContext as ry}from"@cline/shared";import{z as Q8}from"zod";import{spawn as vy}from"node:child_process";import{augmentNodeCommandForDebug as cy,withResolvedClineBuildEnv as uy}from"@cline/shared";function dy($){let W=$.trim();if(!W)return{};let Q=W.split(`
587
- `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse subprocess stdout JSON"}}}function ly($,W){let Z=$ instanceof Error?$:Error(String($)),Q=Z,J=W.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${J}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${J}": ${Z.message}`)}async function py($,W){let Z=$.stdin;if(!Z)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,J)=>{let j=(X)=>{Z.off("error",j);let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X)};Z.once("error",j),Z.end(W,(X)=>{if(Z.off("error",j),X){let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X);return}Q()})})}async function g6($,W){let Z=cy(W.command,{env:W.env,debugRole:"hook"});if(!Array.isArray(Z)||Z.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!W.detached,J=vy(Z[0],Z.slice(1),{cwd:W.cwd,env:uy(W.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q,windowsHide:!0}),j=new Promise((K)=>{J.once("spawn",()=>{try{W.onSpawn?.({command:Z,pid:J.pid??void 0,detached:Q})}catch{}K()})}),X=new Promise((K,F)=>{J.once("error",(A)=>{F(ly(A,Z))})});if(await py(J,JSON.stringify($)),Q){await Promise.race([j,X]),J.unref();return}if(!J.stdout||!J.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let Y="",V="",B=!1,H;J.stdout.on("data",(K)=>{Y+=K.toString()}),J.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,J.kill("SIGKILL")},W.timeoutMs);J.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:D}=dy(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:D,timedOut:B})})});return await Promise.race([G,X])}var iy=Q8.object({contextModification:Q8.string().optional(),cancel:Q8.boolean().optional(),review:Q8.boolean().optional(),errorMessage:Q8.string().optional(),context:Q8.string().optional(),overrideInput:Q8.unknown().optional()}).passthrough();var ny=["agent","hook"];async function v6($,W={}){let Z=W.command??ny;return await g6($,{command:Z,cwd:W.cwd,env:W.env,detached:W.detached,timeoutMs:W.timeoutMs,onSpawn:W.onSpawn})}function rU($){return $ instanceof Error?$:Error(String($))}function ay($){if(!$||typeof $!=="object")return;let W=iy.safeParse($);if(!W.success)return;let Z=W.data;if(!(("cancel"in Z)||("review"in Z)||("context"in Z)||("contextModification"in Z)||("overrideInput"in Z)||("errorMessage"in Z)))return;let J=typeof Z.context==="string"?Z.context:typeof Z.contextModification==="string"?Z.contextModification:typeof Z.errorMessage==="string"&&Z.errorMessage.length>0?Z.errorMessage:void 0;return{cancel:typeof Z.cancel==="boolean"?Z.cancel:void 0,review:typeof Z.review==="boolean"?Z.review:void 0,context:J,overrideInput:Object.hasOwn(Z,"overrideInput")?Z.overrideInput:void 0}}function pU($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q;else W[Z]=JSON.stringify(Q);return W}function H$($,W,Z){let Q=Z.env??process.env,J=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",j=Z.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:W.conversationId,sessionContext:ry(Z.sessionContext,{hookName:$,conversationId:W.conversationId,agentId:W.agentId,parentAgentId:W.parentAgentId}),workspaceRoots:j?[j]:[],workspaceInfo:Z.workspaceInfo,userId:J,agent_id:W.agentId,parent_agent_id:W.parentAgentId}}function oy($){return{name:$.name,message:$.message,stack:$.stack}}function sy($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function ty($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function ey($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function $h($){return{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}function Wh($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}async function J8($,W){try{let Z=await v6($,{command:W.command,cwd:W.cwd,env:W.env,detached:!0,onSpawn:W.onSpawn});W.onDispatch?.({payload:$,result:Z,detached:!0})}catch(Z){W.onDispatchError?.(rU(Z),$)}}function SQ($={}){return{hooks:{beforeRun:async(Y)=>{let V=ty(Y);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let H={...H$("agent_resume",V,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await J8(H,$)}else{let H={...H$("agent_start",V,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await J8(H,$)}return},beforeTool:async(Y)=>{let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...H$("tool_call",V,$),hookName:"tool_call",iteration:Y.snapshot.iteration,tool_call:{id:Y.toolCall.toolCallId,name:Y.toolCall.toolName,input:Y.input},preToolUse:{toolName:Y.toolCall.toolName,parameters:pU(Y.input)}};try{let H=await v6(B,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:B,result:H,detached:!1}),H?.timedOut)throw Error("tool_call hook command timed out");if(H?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${H.parseError}`);return Wh(ay(H?.parsedJson))}catch(H){$.onDispatchError?.(rU(H),B);return}},afterTool:async(Y)=>{let V=$h(Y),B={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},H={...H$("tool_result",B,$),hookName:"tool_result",iteration:Y.snapshot.iteration,tool_result:V,postToolUse:{toolName:V.name,parameters:pU(V.input),result:typeof V.output==="string"?V.output:JSON.stringify(V.output),success:!V.error,executionTimeMs:V.durationMs}};await J8(H,$);return},afterRun:async({snapshot:Y,result:V})=>{let B={agentId:Y.agentId,conversationId:Y.conversationId??Y.runId??Y.agentId,parentAgentId:Y.parentAgentId??null};if(V.status==="completed"){let K={...H$("agent_end",B,$),hookName:"agent_end",iteration:V.iterations,turn:{outputText:V.outputText,status:V.status},taskComplete:{taskMetadata:{}}};await J8(K,$);return}let H=V.status==="aborted"||sy(V.error?.message)?"agent_abort":"agent_error",G=H==="agent_error"?{...H$(H,B,$),hookName:H,iteration:V.iterations,error:oy(V.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...H$(H,B,$),hookName:H,reason:V.error?.message,taskCancel:{taskMetadata:{}}};await J8(G,$)},onEvent:async(Y)=>{if(Y.type!=="message-added"||Y.message.role!=="user")return;let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...H$("prompt_submit",V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:ey(Y.message.content),attachments:[]}};await J8(B,$)}},shutdown:async({agentId:Y,conversationId:V,parentAgentId:B,reason:H})=>{let G={...H$("session_shutdown",{agentId:Y,conversationId:V,parentAgentId:B},$),hookName:"session_shutdown",reason:H};await J8(G,$)}}}bQ();var aU={};w(aU,{registerRemoteConfigSessionBlobUpload:()=>kQ,readRemoteConfigSessionBlobUploadMetadata:()=>ZX,prepareRemoteConfigCoreIntegration:()=>JX,createRemoteConfigSessionMessagesArtifactUploader:()=>QX,buildRemoteConfigSessionBlobUploadMetadata:()=>yQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>hQ});import{buildRemoteConfigSessionBlobUploadMetadata as yQ,clearRemoteConfigSessionBlobUpload as Zh,createClineTelemetryServiceConfig as Qh,createSessionId as Jh,createRemoteConfigSessionMessagesArtifactUploader as jh,prepareRemoteConfigRuntime as Xh,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as hQ,readRemoteConfigSessionBlobUploadMetadata as ZX,registerRemoteConfigSessionBlobUpload as kQ}from"@cline/shared";function Yh($,W){let Z=$.telemetry||W.telemetryService?{...W.telemetryService??{},...$.telemetry??{}}:void 0;if(!Z)return;return d1(Qh(Z)).telemetry}function QX(){let $=jh();return{async uploadMessagesFile(W){await $.uploadMessagesFile(W)}}}async function JX($){let W=await Xh($),Z=Yh(W,$),Q=[W.pluginDefinition],J=W.claims?.subject,j=yQ(W.bundle?.remoteConfig,J),X;return{prepared:W,extensions:Q,telemetry:Z,applyToStartSessionInput(Y){let V=Y.config.extensions??[],B=Y.config.telemetry,H=j?Y.config.sessionId?.trim()||Jh():Y.config.sessionId;if(H&&j)X=H;let G=H&&j?kQ(H,W.bundle?.remoteConfig,J):void 0,K=G?{...Y.sessionMetadata??{},[hQ]:G}:Y.sessionMetadata;return{...Y,...K?{sessionMetadata:K}:{},config:{...Y.config,...H?{sessionId:H}:{},extensions:[...V,...Q],telemetry:Z??B}}},async dispose(){if(X)Zh(X)}}}var ZD={};w(ZD,{createTeamName:()=>gQ,DefaultRuntimeBuilder:()=>d6});import{hasRuntimeConfigExtension as Oh}from"@cline/shared";import{nanoid as zh}from"nanoid";X1();var WD={};w(WD,{createLocalTeamStore:()=>VX,SqliteTeamStore:()=>j8,FileTeamStore:()=>D9});import{appendFileSync as Vh,existsSync as c6,mkdirSync as oU,readdirSync as Bh,readFileSync as sU,renameSync as Hh,writeFileSync as Gh}from"node:fs";import{join as jX}from"node:path";import{resolveTeamDataDir as Kh}from"@cline/shared/storage";function tU(){return new Date().toISOString()}function XX($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function eU($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class D9{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??Kh()}init(){this.ensureTeamDir()}listTeamNames(){if(!c6(this.teamDirPath))return[];return Bh(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>c6(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let W=this.readEnvelope($);return W?.teamState?eU(W.teamState):void 0}readHistory($,W=200){let Z=this.historyPath($);if(!c6(Z))return[];return sU(Z,"utf8").split(`
588
- `).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0,W)}loadRuntime($){let W=this.readEnvelope($);return{state:W?.teamState?eU(W.teamState):void 0,teammates:W?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,W){this.ensureTeamSubdir($),Vh(this.historyPath($),`${JSON.stringify({ts:tU(),eventType:W.type,payload:W})}
589
- `,"utf8")}persistRuntime($,W,Z){this.ensureTeamSubdir($);let Q={version:1,updatedAt:tU(),teamState:W,teammates:Z},J=this.statePath($),j=`${J}.tmp`;Gh(j,`${JSON.stringify(Q,null,2)}
590
- `,"utf8"),Hh(j,J)}markInProgressRunsInterrupted($,W){let Z=this.readEnvelope($);if(!Z?.teamState?.runs?.length)return[];let Q=Z.teamState.runs.filter((j)=>j.status==="queued"||j.status==="running").map((j)=>j.id);if(Q.length===0)return[];let J=new Date;return Z.teamState={...Z.teamState,runs:Z.teamState.runs.map((j)=>j.status==="queued"||j.status==="running"?{...j,status:"interrupted",error:W,endedAt:J}:j)},this.persistRuntime($,Z.teamState,Z.teammates),Q}ensureTeamDir(){if(!c6(this.teamDirPath))oU(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let W=jX(this.ensureTeamDir(),XX($));if(!c6(W))oU(W,{recursive:!0});return W}statePath($){return jX(this.ensureTeamDir(),XX($),"state.json")}historyPath($){return jX(this.ensureTeamDir(),XX($),"task-history.jsonl")}readEnvelope($){let W=this.statePath($);if(!c6(W))return;try{let Z=JSON.parse(sU(W,"utf8"));if(Z?.version===1&&Z.teamState)return Z}catch{}return}}import{existsSync as Fh,mkdirSync as Ah}from"node:fs";import{join as Uh}from"node:path";import{safeJsonParse as $D}from"@cline/shared";import{loadSqliteDb as Dh,nowIso as YX}from"@cline/shared/db";import{resolveDbDataDir as _h}from"@cline/shared/storage";function fh(){return _h()}function u6($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function Lh($){let W=$D($);if(!Array.isArray(W))return[];let Z=[];for(let Q of W){if(!Q||typeof Q!=="object")continue;let J=Q,j=J.agentId,X=J.rolePrompt;if(typeof j!=="string"||!j.trim())continue;if(typeof X!=="string"||!X.trim())continue;let Y={agentId:j.trim(),rolePrompt:X};if(typeof J.modelId==="string"&&J.modelId.trim())Y.modelId=J.modelId.trim();if(typeof J.maxIterations==="number"&&Number.isFinite(J.maxIterations))Y.maxIterations=Math.max(1,Math.floor(J.maxIterations));Z.push(Y)}return Z}function Th($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class j8{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??fh()}init(){this.getRawDb()}ensureTeamDir(){if(!Fh(this.teamDirPath))Ah(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return Uh(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=Dh(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
585
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"","",$.messagesPath,X0()])}}function zy($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let W=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(W==="local"||W==="hub"||W==="remote")return W;return"auto"}var K9,F9;function qy($,W){if($!=="auto"&&$!=="hub")return;if(W.hub?.endpoint?.trim())return;EW(W.hub?.workspaceRoot?.trim()||W.hub?.cwd?.trim()||process.cwd())}async function My($){await $.reconcileDeadSessions?.().catch(()=>{})}function bU($){try{let W=new C1;return W.init(),new S1(W,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(W){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),SU($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:W,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new ij(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function PU($,W,Z){return new b1({sessionService:Z??$.sessionService??bU($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:W,fetch:$.fetch})}async function sj($){if(K9)return K9;if(F9)return await F9;return F9=(async()=>{return K9=bU($),await My(K9),K9})().finally(()=>{F9=void 0}),await F9}async function h6($){let W=x0($.distinctId);$.telemetry?.setDistinctId(W);let Z=zy($);if(qy(Z,$),Z==="remote"){let Q=$.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Q}),new N6({endpoint:Q,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Z==="hub"){let Q=$.hub?.endpoint?.trim(),J=Q||await H2({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!J)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:J,explicitEndpoint:Q||void 0}),new Y$({url:J,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Z==="auto"){let Q=await T4({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Q){$.logger?.log("Using discovered local hub runtime host",{url:Q});let J=new Y$({url:Q,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await J.connect(),J}catch(j){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:j}),SU($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:j,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),PU($,W)}return PU($,W)}var IU={};w(IU,{NoOpFeatureFlagsProvider:()=>W8,FeatureFlagsService:()=>$8});import{existsSync as Ry,mkdirSync as Ey,readFileSync as Ny,writeFileSync as wy}from"node:fs";import{dirname as Cy}from"node:path";import{FEATURE_FLAGS as hU,FeatureFlagDefaultValue as tj}from"@cline/shared";var Py=3600000,Sy=604800000,kU=1;class $8{provider;telemetry;logger;cacheTtlMs;cacheFilePath;persistentCacheMaxAgeMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};constructor($){this.provider=$.provider,this.telemetry=$.telemetry,this.logger=$.logger,this.cacheTtlMs=$.cacheTtlMs??Py,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??Sy,this.context={...$.context??{}},this.hydrateFromPersistentCache()}setContext($){this.context={...$}}hydrateCache($){this.cacheInfo={updateTime:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload},this.rebuildCacheFromSnapshot($.flagsPayload)}getCacheSnapshot(){return{updateTime:this.cacheInfo.updateTime,userId:this.cacheInfo.userId,flagsPayload:this.cacheInfo.flagsPayload}}async poll($){let W=$??this.context.userId??null,Z=Date.now();if(Z-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===W)return}let Q=this.cacheInfo;this.cacheInfo={updateTime:Z,userId:W||null};try{let J=await this.provider.getAllFlagsAndPayloads({flagKeys:hU.length>0?hU:void 0,context:{...this.context,userId:W}});if(this.cacheInfo.userId!==W)return;this.cacheInfo.flagsPayload=J,this.rebuildCacheFromSnapshot(J),this.writePersistentCache()}catch(J){if(this.cacheInfo.userId!==W)return;throw this.cacheInfo=Q.updateTime?Q:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:J}),J}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((W)=>this.isFeatureFlagPayload(W));if(typeof $==="object")return Object.values($).every((W)=>this.isFeatureFlagPayload(W));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=Object.entries($).filter(([,Q])=>this.isFeatureFlagPayload(Q));if(W.length===0)return;let Z={};for(let[Q,J]of W)Z[Q]=J;return Z}readPersistentCache(){try{if(!this.cacheFilePath||!Ry(this.cacheFilePath))return;let $=JSON.parse(Ny(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let W=$;if(W.version!==kU||typeof W.updatedAt!=="number"||!Number.isFinite(W.updatedAt)||Date.now()-W.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:W.updatedAt,userId:W.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(W.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(W.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;Ey(Cy(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),W={version:kU,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};wy(this.cacheFilePath,`${JSON.stringify(W,null,2)}
586
+ `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let W=new Map;for(let Z of this.getReturnedFlagKeys($)){let Q=this.getFeatureFlag(Z);W.set(Z,Q??!1)}this.cache=W}getFeatureFlag($){try{let W=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Z=this.cacheInfo.flagsPayload?.featureFlags?.[$],Q=W??Z??tj[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Q)this.telemetry?.capture({event:v.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Z}});return Q}catch(W){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:W}),tj[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??tj[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,W){if(process.env.IS_TEST==="true")this.cache.set($,W)}async dispose(){await this.provider.dispose()}}class W8{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}O8();var dU={};w(dU,{createCheckpointComparePlan:()=>wQ,compareCheckpointToWorkspace:()=>A9,buildCheckpointWorkspaceDiff:()=>CQ});import{execFile as hy}from"node:child_process";import*as cU from"node:fs/promises";import*as x6 from"node:path";import{promisify as ky}from"node:util";var mU={};w(mU,{trimMessagesToCheckpoint:()=>gU,trimMessagesBeforeCheckpoint:()=>$X,readSessionCheckpointHistory:()=>Z8,findCheckpointForRun:()=>I6,createRestoredCheckpointMetadata:()=>ej,createCheckpointRestorePlan:()=>WX,applyCheckpointToWorktree:()=>ZX});import{execFile as by}from"node:child_process";import{promisify as yy}from"node:util";var k6=yy(by);function Z8($){let W=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(W?.history)?W.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let J=String(Q.ref??"").trim(),j=Number(Q.createdAt??0),X=Number(Q.runCount??0);if(J.length===0||!Number.isFinite(j)||!Number.isInteger(X)||X<1)return[];let Y=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:J,createdAt:j,runCount:X,...Y?{kind:Y}:{}}]})}function ej($,W){let Z=Z8($).filter((J)=>J.runCount<=W),Q=Z.at(-1);return Q?{latest:Q,history:Z}:void 0}function I6($,W){return $.reduce((Z,Q)=>{if(Q.runCount>W)return Z;if(!Z||Q.runCount>Z.runCount)return Q;return Z},void 0)}function xU($,W){let Z=0;for(let Q=0;Q<$.length;Q+=1){let J=$[Q];if(J?.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"?J.metadata:void 0)?.kind==="recovery_notice")continue;if(Z+=1,Z===W)return Q}throw Error(`Could not find user message for checkpoint run ${W}`)}function gU($,W){let Z=xU($,W);return $.slice(0,Z+1)}function $X($,W){let Z=xU($,W);return $.slice(0,Z)}function WX($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=I6(Z8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Z,cwd:Q,...$.restoreMessages!==!1?{messages:gU($.messages??[],W)}:{}}}async function ZX($,W){if((await k6("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await k6("git",["-C",$,"cat-file","-e",`${W.ref}^{commit}`],{windowsHide:!0}),await k6("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await k6("git",["-C",$,"clean","-fd"],{windowsHide:!0}),W.kind==="commit"){await k6("git",["-C",$,"reset","--hard",W.ref],{windowsHide:!0});return}await k6("git",["-C",$,"stash","apply",W.ref],{windowsHide:!0})}var Iy=ky(hy),xy=52428800;async function NQ($,W){let{stdout:Z}=await Iy("git",["-C",$,...W],{windowsHide:!0,maxBuffer:xy,encoding:"utf8"});return Z}function vU($){return $.split("\x00").filter(Boolean)}function uU($,W){let Z=x6.resolve($,W),Q=x6.relative($,Z);if(Q.startsWith("..")||x6.isAbsolute(Q))throw Error(`Checkpoint diff path escapes workspace: ${W}`);return Z}async function gy($,W,Z){try{return await NQ($,["show",`${W}:${Z}`])}catch{return""}}async function my($,W){try{return await cU.readFile(uU($,W),"utf8")}catch{return""}}async function vy($,W){await NQ($,["cat-file","-e",`${W.ref}^{tree}`]);let[Z,Q]=await Promise.all([NQ($,["diff","--name-only","-z",W.ref,"--"]),NQ($,["ls-files","--others","--exclude-standard","-z"])]);return[...new Set([...vU(Z),...vU(Q)])].sort((j,X)=>j.localeCompare(X))}function wQ($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=I6(Z8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to compare a checkpoint");return{checkpoint:Z,cwd:Q}}async function CQ($,W){let Z=await vy($,W);return(await Promise.all(Z.map(async(J)=>{let[j,X]=await Promise.all([gy($,W.ref,J),my($,J)]);return{filePath:uU($,J),leftContent:j,rightContent:X}}))).filter((J)=>J.leftContent!==J.rightContent)}async function A9($){let W=wQ($),Z=await CQ(W.cwd,W.checkpoint);return{...W,diffs:Z}}class U9{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,W,Z,Q,J,j,X,Y,V,B){this.clientName=W,this.runtimeAddress=Z,this.host=$,this.prepare=Q,this.capabilities=J,this.logger=j,this.telemetry=X,this.distinctId=Y,this.featureFlags=V,this.settings=EA($),this.pendingPrompts=NA($),this.automation=new $j(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=B?new W9({workspaceRoot:B.workspaceRoot??process.cwd(),specs:{cronSpecsDir:B.cronSpecsDir??B.cronDir,scope:zF(B.cronScope),workspaceRoot:B.workspaceRoot},runtimeHandlers:qF({host:$,getExtensionContext:()=>$Q({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:B.dbPath,logger:B.logger,pollIntervalMs:B.pollIntervalMs,claimLeaseSeconds:B.claimLeaseSeconds,globalMaxConcurrency:B.globalMaxConcurrency,watcherDebounceMs:B.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((H)=>{if(H.type!=="ended")return;this.disposeSessionBootstrap(H.payload.sessionId)})}static async create($={}){let W=x0($.distinctId),Z=P0($.capabilities),Q={...$,capabilities:Z,distinctId:W},J=await h6(Q),j=OF($.automation),X=$.featureFlags||new $8({provider:new W8,telemetry:$.telemetry,logger:$.logger,context:{distinctId:W,clientName:$.clientName}}),Y=new U9(J,$.clientName,J.runtimeAddress,$.prepare,Z,$.logger,$.telemetry,W,X,j?{...j,logger:$.logger}:void 0);if(j&&j.autoStart!==!1)await Y.automation.start();return Y}async disposeSessionBootstrap($){let W=this.activeSessionBootstraps.get($);if(!W)return;this.activeSessionBootstraps.delete($),await Promise.resolve(W.dispose?.())}async start($){let W=wA($),Z=await this.prepare?.(W);try{let Q=Z?await Z.applyToStartSessionInput(W):W,J=await this.host.startSession(_j(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(j)=>$Q({automationService:this.automationService,automation:this.automation,context:j,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Z)if(await this.host.getSession(J.sessionId))this.activeSessionBootstraps.set(J.sessionId,Z);else await Promise.resolve(Z.dispose?.());return CA({input:Q,sessionId:J.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),J}catch(Q){throw await Promise.resolve(Z?.dispose?.()),Q}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let W=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(W.map((Z)=>this.disposeSessionBootstrap(Z)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await OQ(this.host,$);list=async($=200,W={})=>await this.listHistory({...W,limit:$});delete=async($)=>{let W=await this.host.deleteSession($);if(W)await this.disposeSessionBootstrap($);return W};update=(...$)=>this.host.updateSession(...$);updateSessionCompactionState=(...$)=>this.host.updateSessionCompactionState(...$);readSessionCompactionState=(...$)=>this.host.readSessionCompactionState(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let W=$.start?_j($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Z)=>$Q({automationService:this.automationService,automation:this.automation,context:Z,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:W})}async compareCheckpoint($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=await this.host.getSession(W);if(!Z)throw Error(`Session ${W} not found`);return A9({session:Z,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,W){return this.host.subscribe($,W)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()};updateSessionConnection=(...$)=>{return this.host.updateSessionConnection?.(...$)??Promise.resolve()}}var pU={};w(pU,{resolvePluginSkillDirectoriesFromPaths:()=>J$,resolvePluginConfigSearchPaths:()=>_5,resolveAndLoadAgentPlugins:()=>X6,resolveAgentPluginPaths:()=>Q$,loadAgentPluginsFromPathsWithDiagnostics:()=>x2,loadAgentPluginsFromPaths:()=>LZ,loadAgentPluginFromPath:()=>U5,discoverPluginModulePaths:()=>f5});var nU={};w(nU,{toHookConfigFileName:()=>O5,runSubprocessEvent:()=>g6,runHook:()=>v6,resolveHooksConfigSearchPaths:()=>L5,parseHookEventPayload:()=>m6,mergeAgentHooks:()=>c2,listHookConfigFiles:()=>I$,createSubprocessHooks:()=>bQ,createHookConfigFileHooks:()=>z5,createHookConfigFileExtension:()=>H6,createHookAuditHooks:()=>B6,createAgentHooksExtension:()=>Y6,HookEventPayloadSchema:()=>SQ,HookEventNameSchema:()=>PQ,HookConfigFileName:()=>V6,HOOK_CONFIG_FILE_EVENT_MAP:()=>T5,HOOKS_CONFIG_DIRECTORY_NAME:()=>RZ});import{HookEventNameSchema as PQ,HookEventPayloadSchema as SQ,parseHookEventPayload as m6,resolveHookSessionContext as iy}from"@cline/shared";import{z as Q8}from"zod";import{spawn as cy}from"node:child_process";import{augmentNodeCommandForDebug as uy,withResolvedClineBuildEnv as dy}from"@cline/shared";function ly($){let W=$.trim();if(!W)return{};let Q=W.split(`
587
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse subprocess stdout JSON"}}}function py($,W){let Z=$ instanceof Error?$:Error(String($)),Q=Z,J=W.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${J}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${J}": ${Z.message}`)}async function ry($,W){let Z=$.stdin;if(!Z)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,J)=>{let j=(X)=>{Z.off("error",j);let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X)};Z.once("error",j),Z.end(W,(X)=>{if(Z.off("error",j),X){let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X);return}Q()})})}async function g6($,W){let Z=uy(W.command,{env:W.env,debugRole:"hook"});if(!Array.isArray(Z)||Z.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!W.detached,J=cy(Z[0],Z.slice(1),{cwd:W.cwd,env:dy(W.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q,windowsHide:!0}),j=new Promise((K)=>{J.once("spawn",()=>{try{W.onSpawn?.({command:Z,pid:J.pid??void 0,detached:Q})}catch{}K()})}),X=new Promise((K,F)=>{J.once("error",(A)=>{F(py(A,Z))})});if(await ry(J,JSON.stringify($)),Q){await Promise.race([j,X]),J.unref();return}if(!J.stdout||!J.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let Y="",V="",B=!1,H;J.stdout.on("data",(K)=>{Y+=K.toString()}),J.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,J.kill("SIGKILL")},W.timeoutMs);J.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:D}=ly(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:D,timedOut:B})})});return await Promise.race([G,X])}var ny=Q8.object({contextModification:Q8.string().optional(),cancel:Q8.boolean().optional(),review:Q8.boolean().optional(),errorMessage:Q8.string().optional(),context:Q8.string().optional(),overrideInput:Q8.unknown().optional()}).passthrough();var ay=["agent","hook"];async function v6($,W={}){let Z=W.command??ay;return await g6($,{command:Z,cwd:W.cwd,env:W.env,detached:W.detached,timeoutMs:W.timeoutMs,onSpawn:W.onSpawn})}function iU($){return $ instanceof Error?$:Error(String($))}function oy($){if(!$||typeof $!=="object")return;let W=ny.safeParse($);if(!W.success)return;let Z=W.data;if(!(("cancel"in Z)||("review"in Z)||("context"in Z)||("contextModification"in Z)||("overrideInput"in Z)||("errorMessage"in Z)))return;let J=typeof Z.context==="string"?Z.context:typeof Z.contextModification==="string"?Z.contextModification:typeof Z.errorMessage==="string"&&Z.errorMessage.length>0?Z.errorMessage:void 0;return{cancel:typeof Z.cancel==="boolean"?Z.cancel:void 0,review:typeof Z.review==="boolean"?Z.review:void 0,context:J,overrideInput:Object.hasOwn(Z,"overrideInput")?Z.overrideInput:void 0}}function rU($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q;else W[Z]=JSON.stringify(Q);return W}function H$($,W,Z){let Q=Z.env??process.env,J=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",j=Z.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:W.conversationId,sessionContext:iy(Z.sessionContext,{hookName:$,conversationId:W.conversationId,agentId:W.agentId,parentAgentId:W.parentAgentId}),workspaceRoots:j?[j]:[],workspaceInfo:Z.workspaceInfo,userId:J,agent_id:W.agentId,parent_agent_id:W.parentAgentId}}function sy($){return{name:$.name,message:$.message,stack:$.stack}}function ty($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function ey($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function $h($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function Wh($){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 Zh($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}async function J8($,W){try{let Z=await v6($,{command:W.command,cwd:W.cwd,env:W.env,detached:!0,onSpawn:W.onSpawn});W.onDispatch?.({payload:$,result:Z,detached:!0})}catch(Z){W.onDispatchError?.(iU(Z),$)}}function bQ($={}){return{hooks:{beforeRun:async(Y)=>{let V=ey(Y);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let H={...H$("agent_resume",V,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await J8(H,$)}else{let H={...H$("agent_start",V,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await J8(H,$)}return},beforeTool:async(Y)=>{let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...H$("tool_call",V,$),hookName:"tool_call",iteration:Y.snapshot.iteration,tool_call:{id:Y.toolCall.toolCallId,name:Y.toolCall.toolName,input:Y.input},preToolUse:{toolName:Y.toolCall.toolName,parameters:rU(Y.input)}};try{let H=await v6(B,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:B,result:H,detached:!1}),H?.timedOut)throw Error("tool_call hook command timed out");if(H?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${H.parseError}`);return Zh(oy(H?.parsedJson))}catch(H){$.onDispatchError?.(iU(H),B);return}},afterTool:async(Y)=>{let V=Wh(Y),B={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},H={...H$("tool_result",B,$),hookName:"tool_result",iteration:Y.snapshot.iteration,tool_result:V,postToolUse:{toolName:V.name,parameters:rU(V.input),result:typeof V.output==="string"?V.output:JSON.stringify(V.output),success:!V.error,executionTimeMs:V.durationMs}};await J8(H,$);return},afterRun:async({snapshot:Y,result:V})=>{let B={agentId:Y.agentId,conversationId:Y.conversationId??Y.runId??Y.agentId,parentAgentId:Y.parentAgentId??null};if(V.status==="completed"){let K={...H$("agent_end",B,$),hookName:"agent_end",iteration:V.iterations,turn:{outputText:V.outputText,status:V.status},taskComplete:{taskMetadata:{}}};await J8(K,$);return}let H=V.status==="aborted"||ty(V.error?.message)?"agent_abort":"agent_error",G=H==="agent_error"?{...H$(H,B,$),hookName:H,iteration:V.iterations,error:sy(V.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...H$(H,B,$),hookName:H,reason:V.error?.message,taskCancel:{taskMetadata:{}}};await J8(G,$)},onEvent:async(Y)=>{if(Y.type!=="message-added"||Y.message.role!=="user")return;let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...H$("prompt_submit",V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:$h(Y.message.content),attachments:[]}};await J8(B,$)}},shutdown:async({agentId:Y,conversationId:V,parentAgentId:B,reason:H})=>{let G={...H$("session_shutdown",{agentId:Y,conversationId:V,parentAgentId:B},$),hookName:"session_shutdown",reason:H};await J8(G,$)}}}yQ();var oU={};w(oU,{registerRemoteConfigSessionBlobUpload:()=>IQ,readRemoteConfigSessionBlobUploadMetadata:()=>QX,prepareRemoteConfigCoreIntegration:()=>jX,createRemoteConfigSessionMessagesArtifactUploader:()=>JX,buildRemoteConfigSessionBlobUploadMetadata:()=>hQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>kQ});import{buildRemoteConfigSessionBlobUploadMetadata as hQ,clearRemoteConfigSessionBlobUpload as Qh,createClineTelemetryServiceConfig as Jh,createSessionId as jh,createRemoteConfigSessionMessagesArtifactUploader as Xh,prepareRemoteConfigRuntime as Yh,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as kQ,readRemoteConfigSessionBlobUploadMetadata as QX,registerRemoteConfigSessionBlobUpload as IQ}from"@cline/shared";function Vh($,W){let Z=$.telemetry||W.telemetryService?{...W.telemetryService??{},...$.telemetry??{}}:void 0;if(!Z)return;return d1(Jh(Z)).telemetry}function JX(){let $=Xh();return{async uploadMessagesFile(W){await $.uploadMessagesFile(W)}}}async function jX($){let W=await Yh($),Z=Vh(W,$),Q=[W.pluginDefinition],J=W.claims?.subject,j=hQ(W.bundle?.remoteConfig,J),X;return{prepared:W,extensions:Q,telemetry:Z,applyToStartSessionInput(Y){let V=Y.config.extensions??[],B=Y.config.telemetry,H=j?Y.config.sessionId?.trim()||jh():Y.config.sessionId;if(H&&j)X=H;let G=H&&j?IQ(H,W.bundle?.remoteConfig,J):void 0,K=G?{...Y.sessionMetadata??{},[kQ]:G}:Y.sessionMetadata;return{...Y,...K?{sessionMetadata:K}:{},config:{...Y.config,...H?{sessionId:H}:{},extensions:[...V,...Q],telemetry:Z??B}}},async dispose(){if(X)Qh(X)}}}var QD={};w(QD,{createTeamName:()=>mQ,DefaultRuntimeBuilder:()=>d6});import{hasRuntimeConfigExtension as zh}from"@cline/shared";import{nanoid as qh}from"nanoid";X1();var ZD={};w(ZD,{createLocalTeamStore:()=>BX,SqliteTeamStore:()=>j8,FileTeamStore:()=>D9});import{appendFileSync as Bh,existsSync as c6,mkdirSync as sU,readdirSync as Hh,readFileSync as tU,renameSync as Gh,writeFileSync as Kh}from"node:fs";import{join as XX}from"node:path";import{resolveTeamDataDir as Fh}from"@cline/shared/storage";function eU(){return new Date().toISOString()}function YX($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function $D($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class D9{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??Fh()}init(){this.ensureTeamDir()}listTeamNames(){if(!c6(this.teamDirPath))return[];return Hh(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>c6(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let W=this.readEnvelope($);return W?.teamState?$D(W.teamState):void 0}readHistory($,W=200){let Z=this.historyPath($);if(!c6(Z))return[];return tU(Z,"utf8").split(`
588
+ `).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0,W)}loadRuntime($){let W=this.readEnvelope($);return{state:W?.teamState?$D(W.teamState):void 0,teammates:W?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,W){this.ensureTeamSubdir($),Bh(this.historyPath($),`${JSON.stringify({ts:eU(),eventType:W.type,payload:W})}
589
+ `,"utf8")}persistRuntime($,W,Z){this.ensureTeamSubdir($);let Q={version:1,updatedAt:eU(),teamState:W,teammates:Z},J=this.statePath($),j=`${J}.tmp`;Kh(j,`${JSON.stringify(Q,null,2)}
590
+ `,"utf8"),Gh(j,J)}markInProgressRunsInterrupted($,W){let Z=this.readEnvelope($);if(!Z?.teamState?.runs?.length)return[];let Q=Z.teamState.runs.filter((j)=>j.status==="queued"||j.status==="running").map((j)=>j.id);if(Q.length===0)return[];let J=new Date;return Z.teamState={...Z.teamState,runs:Z.teamState.runs.map((j)=>j.status==="queued"||j.status==="running"?{...j,status:"interrupted",error:W,endedAt:J}:j)},this.persistRuntime($,Z.teamState,Z.teammates),Q}ensureTeamDir(){if(!c6(this.teamDirPath))sU(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let W=XX(this.ensureTeamDir(),YX($));if(!c6(W))sU(W,{recursive:!0});return W}statePath($){return XX(this.ensureTeamDir(),YX($),"state.json")}historyPath($){return XX(this.ensureTeamDir(),YX($),"task-history.jsonl")}readEnvelope($){let W=this.statePath($);if(!c6(W))return;try{let Z=JSON.parse(tU(W,"utf8"));if(Z?.version===1&&Z.teamState)return Z}catch{}return}}import{existsSync as Ah,mkdirSync as Uh}from"node:fs";import{join as Dh}from"node:path";import{safeJsonParse as WD}from"@cline/shared";import{loadSqliteDb as _h,nowIso as VX}from"@cline/shared/db";import{resolveDbDataDir as fh}from"@cline/shared/storage";function Lh(){return fh()}function u6($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function Th($){let W=WD($);if(!Array.isArray(W))return[];let Z=[];for(let Q of W){if(!Q||typeof Q!=="object")continue;let J=Q,j=J.agentId,X=J.rolePrompt;if(typeof j!=="string"||!j.trim())continue;if(typeof X!=="string"||!X.trim())continue;let Y={agentId:j.trim(),rolePrompt:X};if(typeof J.modelId==="string"&&J.modelId.trim())Y.modelId=J.modelId.trim();if(typeof J.maxIterations==="number"&&Number.isFinite(J.maxIterations))Y.maxIterations=Math.max(1,Math.floor(J.maxIterations));Z.push(Y)}return Z}function Oh($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class j8{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??Lh()}init(){this.getRawDb()}ensureTeamDir(){if(!Ah(this.teamDirPath))Uh(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return Dh(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=_h(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
591
591
  CREATE TABLE IF NOT EXISTS team_store_schema_version (
592
592
  lock INTEGER PRIMARY KEY CHECK (lock = 1),
593
593
  version INTEGER NOT NULL
@@ -671,8 +671,8 @@ ${J}`,$.config.mode)}function G9($,W){return Gy($,W==="plan"?"plan":W==="yolo"?"
671
671
  version INTEGER NOT NULL DEFAULT 1,
672
672
  PRIMARY KEY(team_name, fragment_id)
673
673
  );
674
- `)}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}withTransaction($){let W=this.getRawDb();W.exec("BEGIN IMMEDIATE;");try{$(),W.exec("COMMIT;")}catch(Z){try{W.exec("ROLLBACK;")}catch{}throw Z}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[u6($)]);if(!W)return;let Z=$D(W.state_json);if(!Z)return;try{return Th(Z)}catch{return}}readHistory($,W=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[u6($),W]).flatMap((Z)=>{try{return[{eventType:Z.event_type,payload:JSON.parse(Z.payload_json),ts:Z.ts}]}catch{return[]}})}loadRuntime($){let W=u6($),Z=this.readState(W),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[W]),J=Q?Lh(Q.teammates_json):[];return{state:Z,teammates:J,interruptedRunIds:[]}}appendTeamEvent($,W,Z,Q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
675
- VALUES (?, ?, ?, ?, NULL, ?)`,[u6($),YX(),W,JSON.stringify(Z),Q??null])}persistRuntime($,W,Z){let Q=u6($),J=YX();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
674
+ `)}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}withTransaction($){let W=this.getRawDb();W.exec("BEGIN IMMEDIATE;");try{$(),W.exec("COMMIT;")}catch(Z){try{W.exec("ROLLBACK;")}catch{}throw Z}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[u6($)]);if(!W)return;let Z=WD(W.state_json);if(!Z)return;try{return Oh(Z)}catch{return}}readHistory($,W=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[u6($),W]).flatMap((Z)=>{try{return[{eventType:Z.event_type,payload:JSON.parse(Z.payload_json),ts:Z.ts}]}catch{return[]}})}loadRuntime($){let W=u6($),Z=this.readState(W),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[W]),J=Q?Th(Q.teammates_json):[];return{state:Z,teammates:J,interruptedRunIds:[]}}appendTeamEvent($,W,Z,Q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
675
+ VALUES (?, ?, ?, ?, NULL, ?)`,[u6($),VX(),W,JSON.stringify(Z),Q??null])}persistRuntime($,W,Z){let Q=u6($),J=VX();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
676
676
  VALUES (?, ?, ?, ?)
677
677
  ON CONFLICT(team_name) DO UPDATE SET
678
678
  state_json = excluded.state_json,
@@ -717,44 +717,44 @@ ${J}`,$.config.mode)}function G9($,W){return Gy($,W==="plan"?"plan":W==="yolo"?"
717
717
  status = excluded.status,
718
718
  reviewed_by = excluded.reviewed_by,
719
719
  reviewed_at = excluded.reviewed_at,
720
- version = team_outcome_fragments.version + 1`,[Q,j.outcomeId,j.id,j.section,j.sourceAgentId,j.sourceRunId??null,j.content,j.status,j.reviewedBy??null,j.reviewedAt?j.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,W){let Z=u6($),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[Z]);if(Q.length===0)return[];let J=YX();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
721
- WHERE team_name = ? AND status IN ('queued', 'running')`,[W,J,Z]),Q.map((j)=>j.run_id)}handleTeamEvent($,W){this.appendTeamEvent($,W.type,W)}}function VX($={}){try{let W=new j8($);return W.init(),W}catch{let W=new D9({teamDir:$.teamDir});return W.init(),W}}function IQ($,W){return Oh($,W)}function qh($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function Mh($,W){return $.filter((Z)=>qh(Z.name,W))}function BX($,W){return u1(Mh($,W))}var Rh={apply_diff:"editor",attempt_completion:"submit_and_exit",bash:"run_commands",execute_command:"run_commands",list_code_definition_names:"search_codebase",list_files:"run_commands",read_file:"read_files",replace_in_file:"editor",search_files:"search_codebase",use_skill:"skills",write_to_file:"editor"};function Eh($){let W=$.trim().toLowerCase();return Rh[W]??W}function Nh($,W){if(W.tools===void 0)return $;let Z=new Set(W.tools.map(Eh));if(W.skills!==void 0)Z.add("skills");return $.filter((Q)=>Z.has(Q.name))}function gQ(){return`team-${zh(5)}`}function xQ($,W,Z,Q,J,j,X,Y){let V=a0[e1({mode:Z})],B=r8(W,Q,Z,J??p8);return BX(y2({cwd:$,...V,enableSkills:!!X,...B,executors:{...X?{skills:X}:{},...Y??{}}}),j)}function wh($){return xQ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,Ch,$.toolExecutors).some((W)=>W.name==="skills")}var Ch=async()=>"";async function Ph($){let W=J0();if(!X$({filePath:W}))return{tools:[]};let Z=new a2({clientFactory:z6({settingsPath:W})}),Q;try{Q=await n2(Z,{filePath:W})}catch(Y){await Z.dispose().catch(()=>{});let V=Y instanceof Error?Y.message:String(Y);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${V}`),{tools:[]}}let J=Q.filter((Y)=>Y.disabled!==!0),j=await Promise.allSettled(J.map((Y)=>M6({serverName:Y.name,provider:Z}))),X=[];for(let[Y,V]of j.entries())if(V.status==="fulfilled")X.push(...V.value);else{let B=V.reason instanceof Error?V.reason.message:String(V.reason);$?.log(`[mcp] Failed to load tools from MCP server "${J[Y].name}", skipping: ${B}`)}return{tools:X,shutdown:async()=>{await Z.dispose()}}}function Sh($,W){if(!$)return;for(let Z of $.getTeammateIds())try{$.shutdownTeammate(Z,W)}catch{}}function bh($){if($===void 0)return!0;switch($){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function yh($){let W=a0[e1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??W.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??W.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class d6{teamRuntimeEntries=new Map;async build($){let{config:W,hooks:Z,extensions:Q,logger:J,telemetry:j,createSpawnTool:X,onTeamRestored:Y,userInstructionService:V,configExtensions:B,toolExecutors:H}=$,G=$.onTeamEvent??(()=>{}),K=yh(W),F=W.workspaceRoot??W.cwd,A=$.toolPolicies??W.toolPolicies,D=L1(),U=[],f=W.teamName?.trim()||gQ(),_=W.sessionId?.trim()||f,R=K.enableSpawnAgent?w6({workspaceRoot:F}):{configs:[],errors:[]},O=R.configs.some((l)=>l.skills!==void 0),T=IQ(B,"rules"),L=IQ(B,"skills"),C=L||O,E=IQ(B,"workflows"),p=IQ(B,"plugins"),x=T||L||E,P=!1,r=Boolean(V),d=V,I1;for(let l of R.errors)(J??W.logger)?.log?.(`[agents] Failed to load agent config at ${l.path}: ${l.error.message}`);if(!d&&(x||O))d=c$({skills:C?{workspacePath:F,includePluginSkills:p,pluginSkillDirectories:p?$.pluginSkillDirectories:void 0,pluginPaths:W.pluginPaths,cwd:W.cwd}:{workspacePath:F},rules:{workspacePath:W.cwd},workflows:{workspacePath:W.cwd}});if(d)await d.start().catch(()=>{});let $2=K.enableTools&&L&&Boolean(d)&&d?.hasConfiguredSkills(W.skills)===!0&&wh({cwd:W.cwd,providerId:W.providerId,mode:K.mode,modelId:W.modelId,toolRoutingRules:W.toolRoutingRules,toolPolicies:A,toolExecutors:H}),A$=d&&x?d.createExtension({includeRules:T,includeSkills:L,includeWorkflows:E,registerSkillsTool:$2,allowedSkillNames:W.skills}):void 0,I0=A$?[...Q??W.extensions??[],A$]:Q??W.extensions;if(K.enableTools){if(U.push(...xQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H)),!K.disableMcpSettingsTools){let l=await Ph(W.logger);U.push(...l.tools),I1=l.shutdown}}let U0,D1=K.enableAgentTeams?VX():void 0,K8=D1?.loadRuntime(_),V0=K8?.state,d0=K8?.teammates??[],J1=new Map(d0.map((l)=>[l.agentId,l])),y=W.sessionId||f,j1,k=[],W0=!1,T0=S$({providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey??"",baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,temperature:W.temperature,maxIterations:W.maxIterations,hooks:Z,extensions:I0,logger:J??W.logger,telemetry:$.telemetry??W.telemetry,workspaceMetadata:W.workspaceMetadata});if(K.enableSpawnAgent){if(R.configs.length>0)U.push(...BX(C6({configProvider:T0,agents:R.configs,createSubAgentTools:(l)=>K.enableTools?Nh(xQ(W.cwd,l.providerId??W.providerId,K.mode,l.modelId??W.modelId,W.toolRoutingRules,A,l.skills!==void 0&&d?.createSkillsExecutor?d.createSkillsExecutor(l.skills):void 0,H),l):[],hookErrorMode:W.hookErrorMode,toolPolicies:A,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),A))}if(!this.teamRuntimeEntries.has(y))this.teamRuntimeEntries.set(y,{delegatedAgentConfigProvider:T0});let q0=()=>{if(!K.enableAgentTeams)return;let l=this.teamRuntimeEntries.get(y)??{delegatedAgentConfigProvider:T0};if(this.teamRuntimeEntries.set(y,l),U0=l.runtime,!U0){if(U0=new e2({teamName:f,leadAgentId:W.sessionId||"lead",missionLogIntervalSteps:K.missionLogIntervalSteps,missionLogIntervalMs:K.missionLogIntervalMs,onTeamEvent:(B0)=>{if(G(B0),U0&&D1){if(B0.type==="teammate_spawned"&&B0.teammate?.rolePrompt){let x1={agentId:B0.agentId,rolePrompt:B0.teammate.rolePrompt,modelId:B0.teammate.modelId,maxIterations:B0.teammate.maxIterations};J1.set(x1.agentId,x1)}if(B0.type==="teammate_shutdown"&&!bh(B0.reason))J1.delete(B0.agentId);D1.handleTeamEvent(_,B0),D1.persistRuntime(_,U0.exportState(),Array.from(J1.values()))}}}),V0)U0.hydrateState(V0),W0=!0;l.runtime=U0}if(!P){if(!U0)return;P=!0;let B0=o8({runtime:U0,leadAgentId:W.sessionId||"lead",restoredFromPersistence:Boolean(V0),restoredTeammates:d0,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(x1)=>{k=x1,j1?.addTools(x1)},createBaseTools:K.enableTools?()=>xQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H):void 0,teammateConfigProvider:T0});if(W0)U0.recoverActiveRuns("runtime_recovered");if(B0.restoredFromPersistence)Y?.();U.push(...B0.tools)}return U0};if(K.enableSpawnAgent&&X){let l=X();U.push({...l,execute:async(B0,x1)=>{return q0(),l.execute(B0,x1)}})}if(K.enableAgentTeams)q0();let d9=BX(U,A),t6=d9.some((l)=>l.name==="submit_and_exit"&&l.lifecycle?.completesRun===!0),F8=K.enableAgentTeams?()=>{let l=this.teamRuntimeEntries.get(y)?.runtime;if(!l)return;let B0=l.listTasks(),x1=B0.some((U$)=>U$.status==="in_progress"||U$.status==="pending"),rY=l.listRuns({}),hf=rY.some((U$)=>U$.status==="running"||U$.status==="queued");if(x1||hf){let U$=B0.filter((l0)=>l0.status==="in_progress"||l0.status==="pending").map((l0)=>`${l0.id} (${l0.status}): ${l0.title}`).join(", "),iY=rY.filter((l0)=>l0.status==="running"||l0.status==="queued").map((l0)=>`${l0.id} (${l0.status})`).join(", "),N7=[];if(U$)N7.push(`Unfinished tasks: ${U$}`);if(iY)N7.push(`Active runs: ${iY}`);return`[SYSTEM] You still have team obligations. ${N7.join(". ")}. Use team_run_task to delegate work, or team_task with action=complete to mark tasks done, or team_await_runs to wait for active runs. Do NOT stop until all tasks are completed.`}return}:void 0,yf=t6?{requireCompletionTool:!0,...F8?{completionGuard:F8}:{}}:F8?{completionGuard:F8}:void 0;return{tools:d9,logger:J??W.logger,telemetry:j??W.telemetry,teamRuntime:U0,teamRestoredFromPersistence:Boolean(V0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(y)?.delegatedAgentConfigProvider??T0,extensions:I0,completionPolicy:yf,registerLeadAgent:(l)=>{if(j1=l,k.length>0)l.addTools(u1(k,[...D]))},shutdown:async(l)=>{if(Sh(U0,l),this.teamRuntimeEntries.delete(y),await I1?.(),!r)d?.stop()}}}}var JD={};w(JD,{requestDesktopToolApproval:()=>GX});import{mkdir as hh,readFile as kh,unlink as Ih,writeFile as xh}from"node:fs/promises";import{join as QD}from"node:path";function gh($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function mh($){return new Promise((W)=>setTimeout(W,$))}async function HX($){try{await Ih($)}catch{}}async function GX($,W={}){let Z=W.approvalDir?.trim(),Q=W.sessionId?.trim();if(!Z||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await hh(Z,{recursive:!0});let J=gh(`${$.toolCallId}`),j=QD(Z,`${Q}.request.${J}.json`),X=QD(Z,`${Q}.decision.${J}.json`),Y=W.nowIso??(()=>new Date().toISOString());await xh(j,`${JSON.stringify({requestId:J,sessionId:Q,createdAt:Y(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
722
- `,"utf8");let V=W.timeoutMs??300000,B=W.pollIntervalMs??200,H=Date.now();while(Date.now()-H<V){try{let G=await kh(X,"utf8"),K=JSON.parse(G),F={approved:K.approved===!0,reason:typeof K.reason==="string"?K.reason:void 0};return await Promise.all([HX(X),HX(j)]),F}catch{}await mh(B)}return await HX(j),{approved:!1,reason:"Tool approval request timed out"}}X1();var fD={};w(fD,{uninstallMarketplaceSkill:()=>rQ,uninstallMarketplacePlugin:()=>iQ,uninstallMarketplaceMcpServerFromSettings:()=>lQ,uninstallMarketplaceEntry:()=>NX,resolveMarketplaceMcpServerName:()=>z9,marketplaceEntryKey:()=>EX,isMarketplaceSkillInstalled:()=>pQ,getMarketplaceSkillCandidates:()=>q9,getGlobalMarketplaceSkillPaths:()=>M9,findInstalledGlobalMarketplaceSkillName:()=>R9});import{spawn as zk}from"node:child_process";import{existsSync as DD,rmSync as qk}from"node:fs";import{homedir as Mk,platform as Rk}from"node:os";import{dirname as Ek,join as UD}from"node:path";import{resolveClineDir as Nk,resolveMcpSettingsPath as wk}from"@cline/shared/storage";var XD={};w(XD,{parseMcpInstallArgs:()=>_9,installMcpServer:()=>KX,buildMcpInstallTransport:()=>mQ});function vh($){let W=($??"stdio").trim();if(W==="http"||W==="streamable-http")return"streamableHttp";if(W==="stdio"||W==="sse"||W==="streamableHttp")return W;throw Error(`Unsupported MCP transport "${W}". Expected stdio, sse, http, streamable-http, or streamableHttp.`)}function ch($){let W;try{W=new URL($)}catch{throw Error(`Invalid MCP server URL: ${$}`)}if(W.protocol!=="http:"&&W.protocol!=="https:")throw Error(`Invalid MCP server URL: ${$} (only http and https are supported)`)}function uh($){let W=$.indexOf(":");if(W<=0)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);let Z=$.slice(0,W).trim(),Q=$.slice(W+1).trim();if(!Z||!Q)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);if(!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(Z))throw Error(`Invalid MCP header name "${Z}".`);return[Z,Q]}function dh($){let W=$.indexOf("<");return W>=0&&$.indexOf(">",W+1)>W+1}function jD($){let W=[...$.headers??[]],Z=[],Q=$.transport,J=$.targetArgs??[];for(let j=0;j<J.length;j++){let X=J[j];if($.parseTransport&&X==="--transport"){let Y=J[j+1];if(!Y)throw Error("--transport requires a value");Q=Y,j++;continue}if($.parseTransport&&X?.startsWith("--transport=")){Q=X.slice(12);continue}if(X==="--header"){let Y=J[j+1];if(!Y)throw Error("--header requires a value");W.push(Y),j++;continue}if(X?.startsWith("--header=")){W.push(X.slice(9));continue}Z.push(X)}return{headers:W,targetArgs:Z,transport:Q}}function lh($){if($.length===0)return{warnings:[]};let W={},Z=[];for(let Q of $){let[J,j]=uh(Q);if(W[J]=j,dh(j))Z.push(`Header "${J}" looks like it contains a placeholder. Update it in MCP settings before using this server.`)}return{headers:W,warnings:Z}}function mQ($){let W=$.name.trim();if(!W)throw Error("MCP server name is required");let{headers:Z,targetArgs:Q,transport:J}=jD({headers:$.headers,targetArgs:$.targetArgs,transport:$.transport}),j=vh(J),{headers:X,warnings:Y}=lh(Z);if(j==="stdio"){if(Z.length>0)throw Error("Stdio MCP installs do not support request headers.");let[B,...H]=Q;if(!B?.trim())throw Error("Stdio MCP install requires a command after the server name, for example: cline mcp install fs --yes -- npx -y @modelcontextprotocol/server-filesystem /tmp");return{name:W,transport:{type:j,command:B,args:H.length>0?H:void 0},warnings:Y}}if(Q.length!==1)throw Error("Remote MCP install requires exactly one URL argument after the server name.");let V=Q[0]?.trim()??"";return ch(V),{name:W,transport:X?{type:j,url:V,headers:X}:{type:j,url:V},warnings:Y}}function _9($){let[W,...Z]=$;if(!W)throw Error("Marketplace MCP install args must start with a server name.");return{name:W,...jD({parseTransport:!0,targetArgs:Z})}}function ph($,W,Z){A1(Z,(Q)=>{let J=Q.mcpServers,j=J&&typeof J==="object"&&!Array.isArray(J)?{...J}:{};j[$]={transport:W},Q.mcpServers=j})}function KX($){let{name:W,transport:Z,warnings:Q}=mQ($);return ph(W,Z,$.settingsPath??J0()),{name:W,status:"installed",transport:Z,warnings:Q}}X1();var AD={};w(AD,{uninstallPlugin:()=>T9});import{existsSync as p6,readdirSync as $k,readFileSync as Wk,rmdirSync as Zk,rmSync as Qk,statSync as Jk}from"node:fs";import{basename as Z1,dirname as n$,extname as jk,isAbsolute as Xk,join as G$,relative as Yk,resolve as l6,sep as _X}from"node:path";import{discoverPluginModulePaths as Vk,resolvePluginConfigSearchPaths as Bk}from"@cline/shared/storage";var HD={};w(HD,{syncPluginMcpServersToSettings:()=>f9,removePluginMcpServersFromSettings:()=>L9,disablePluginMcpServersInSettings:()=>DX});import{existsSync as rh,mkdirSync as ih,readFileSync as nh,writeFileSync as ah}from"node:fs";import{dirname as VD,isAbsolute as oh,relative as sh,resolve as YD}from"node:path";function X8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function vQ($,W){let Z=sh(YD($),YD(W));return Z===""||!Z.startsWith("..")&&!oh(Z)}function FX($){if(!rh($))return{mcpServers:{}};try{let W=JSON.parse(nh($,"utf8"));if(X8(W))return W}catch(W){throw Error(`Invalid MCP settings at "${$}": ${W instanceof Error?W.message:String(W)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function AX($){if(X8($.mcpServers))return{...$.mcpServers};return{}}function UX($,W,Z){ih(VD($),{recursive:!0}),ah($,`${JSON.stringify({...W,mcpServers:Z},null,2)}
723
- `,"utf8")}function BD($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((W)=>W.trim()).filter((W)=>W.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((W)=>W.trim()).filter((W)=>W.length>0))]}}function uQ($){if(!X8($))return;let W=$.metadata;return X8(W)?W:void 0}function cQ($,W){let Z=uQ($);if(!Z||Z.source!=="plugin")return!1;let Q=typeof Z.pluginName==="string"?Z.pluginName:typeof Z.plugin==="string"?Z.plugin:void 0,J=typeof Z.pluginPath==="string"?Z.pluginPath:void 0;if(W.pluginName&&Q===W.pluginName){if(!W.pluginPath||J===W.pluginPath)return!0}if(J&&W.pluginPath&&(J===W.pluginPath||vQ(W.pluginPath,J)||vQ(J,W.pluginPath)))return!0;if(Q&&W.pluginNames?.some((j)=>j===Q))return!0;if(J&&W.pluginPaths?.some((j)=>J===j||vQ(j,J)||vQ(J,j)))return!0;return!1}function th($){let W=X8($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:VD($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...W,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function eh($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let W=await j6({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Z=[],Q=[],J=(W.failures??[]).map((j)=>({pluginPath:j.pluginPath,pluginName:j.pluginName,message:j.message}));for(let j of W.extensions??[]){let X=j.__clinePluginPath;if(!X)continue;if(!j.setup){Z.push({pluginName:j.name,pluginPath:X});continue}let Y=[],V={registerTool:(B)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(B)=>{if(!j.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');Y.push(B)}};try{await j.setup(V,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(B){J.push({pluginPath:X,pluginName:j.name,message:B instanceof Error?B.message:String(B)});continue}Z.push({pluginName:j.name,pluginPath:X});for(let B of Y)Q.push({pluginName:j.name,pluginPath:X,server:{...B,metadata:{...B.metadata??{},source:"plugin",pluginName:j.name,pluginPath:X}}})}return{plugins:Z,servers:Q,failures:J}}finally{await W.shutdown().catch(()=>{})}}async function f9($){let W=$.settingsPath??J0(),Z={mutations:[],failures:[]},Q;try{Q=await eh($)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}Z.failures.push(...Q.failures);let J;try{J=FX(W)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}let j=AX(J),X=new Map,Y=new Map;for(let B of Q.plugins)X.set(B.pluginPath,new Set),Y.set(B.pluginPath,B.pluginName);let V=FQ(Q.servers.map((B)=>({server:B.server,owner:B,ownerLabel:B.pluginName})));for(let B of V){let H=B.owner;if(!X.has(H.pluginPath))X.set(H.pluginPath,new Set);if(B.name)X.get(H.pluginPath)?.add(B.name);if(!B.registration){Z.mutations.push({name:B.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:B.loadError??"invalid MCP server registration"});continue}let G=j[B.registration.name];if(G!==void 0){if(!cQ(G,{pluginName:H.pluginName,pluginPath:H.pluginPath})){Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}j[B.registration.name]=th({registration:B.registration,pluginName:H.pluginName,pluginPath:H.pluginPath,existing:X8(G)?G:void 0}),Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:G===void 0?"created":"updated"})}for(let[B,H]of Object.entries(j)){let G=uQ(H),K=typeof G?.pluginPath==="string"?G.pluginPath:"",F=X.get(K);if(F&&cQ(H,{pluginPath:K})&&!F.has(B))delete j[B],Z.mutations.push({name:B,pluginName:typeof G?.pluginName==="string"?G.pluginName:Y.get(K)??"plugin",pluginPath:K,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Z.mutations.some((B)=>B.action!=="skipped"))try{UX(W,J,j)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)})}return Z}function DX($){let W=$.settingsPath??J0(),Z;try{Z=FX(W)}catch{return[]}let Q=AX(Z),J=BD($),j=[];for(let[X,Y]of Object.entries(Q)){if(!X8(Y)||!cQ(Y,J))continue;let V=uQ(Y);Q[X]={...Y,disabled:!0},j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"disabled"})}if(j.length>0)UX(W,Z,Q);return j}function L9($){let W=$.settingsPath??J0(),Z;try{Z=FX(W)}catch{return[]}let Q=AX(Z),J=BD($),j=[];for(let[X,Y]of Object.entries(Q)){if(!cQ(Y,J))continue;let V=uQ(Y);delete Q[X],j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"removed"})}if(j.length>0)UX(W,Z,Q);return j}var zX="_installed",Hk="package",Gk=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function fX($){return $.trim().toLowerCase()}function U1($,W){let Z=W?.trim();if(!Z)return;$.add(Z)}function Kk($){return $.replace(/-[0-9a-f]{12}$/i,"")}function LX($){let W=jk($);return W?$.slice(0,-W.length):$}function TX($){if(!p6($))return;try{let W=JSON.parse(Wk($,"utf8"));return typeof W.name==="string"?W.name.trim():void 0}catch{return}}function qX($,W){let Z=Yk(W,$);return Z===""||!Z.startsWith("..")&&!Xk(Z)}function GD($){let Z=l6($).split(_X),Q=Z.lastIndexOf(zX);if(Q<0)return;let J=Z[Q+1];if(!J)return;let j=Gk.get(J)??1,X=Q+2+j;if(Z.length<X)return;let Y=Z.slice(0,X).join(_X)||_X;return p6(Y)?Y:void 0}function dQ($){try{return $k($,{withFileTypes:!0})}catch{return[]}}function Fk($){let W=G$($,zX);if(!p6(W))return[];let Z=[];for(let Q of dQ(W)){if(!Q.isDirectory())continue;let J=G$(W,Q.name);if(Q.name==="git"){for(let j of dQ(J)){if(!j.isDirectory())continue;let X=G$(J,j.name);for(let Y of dQ(X))if(Y.isDirectory())Z.push(G$(X,Y.name))}continue}for(let j of dQ(J))if(j.isDirectory())Z.push(G$(J,j.name))}return Z.sort((Q,J)=>Q.localeCompare(J))}function KD($){try{return Vk($)}catch{return[]}}function OX($){let W=KD($),Z=new Set;U1(Z,Z1($)),U1(Z,Kk(Z1($))),U1(Z,TX(G$($,"package.json"))),U1(Z,TX(G$($,Hk,"package.json")));for(let Q of W)U1(Z,Z1(Q)),U1(Z,LX(Z1(Q)));return{installPath:$,entryPaths:W,names:[...Z].sort((Q,J)=>Q.localeCompare(J)),installed:!0}}function Ak($,W){let Z=l6($),Q=W.find((X)=>qX(Z,X));if(!Q)return;let J=n$(Z);while(J!==Q&&J!==n$(J)){if(p6(G$(J,"package.json")))return J;J=n$(J)}let j=Z1(Z);if((j==="index.ts"||j==="index.js")&&n$(Z)!==Q)return n$(Z);return Z}function FD($,W){let Z=Ak($,W);if(!Z)return;let Q=new Set;return U1(Q,Z1($)),U1(Q,LX(Z1($))),U1(Q,Z1(Z)),U1(Q,LX(Z1(Z))),U1(Q,TX(G$(Z,"package.json"))),{installPath:Z,entryPaths:[$],names:[...Q].sort((J,j)=>J.localeCompare(j)),installed:!1}}function Uk($){let W=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return Bk(W).filter((Z)=>p6(Z))}function Dk($){let W=new Map;for(let Z of $){for(let Q of Fk(Z))W.set(Q,OX(Q));for(let Q of KD(Z)){let J=GD(Q);if(J){if(!W.has(J))W.set(J,OX(J));continue}let j=FD(Q,$);if(j)W.set(j.installPath,j)}}return[...W.values()].sort((Z,Q)=>Z.installPath.localeCompare(Q.installPath))}function _k($,W){let Z=fX(W);if(!Z)return!1;if(fX($.installPath)===Z)return!0;return $.names.some((Q)=>fX(Q)===Z)}function fk($,W,Z){let Q=l6($);for(let j of W){if(qX(Q,j.installPath))return j;if(j.entryPaths.some((X)=>l6(X)===Q))return j}let J=GD(Q);if(J)return OX(J);if(p6(Q))return FD(Q,Z);return}function Lk($){let W=E0(),Z=W.disabledPlugins;if(!Z?.length)return;let Q=Z.filter((J)=>{let j=l6(J);if(qX(j,$.installPath))return!1;return!$.entryPaths.some((X)=>l6(X)===j)});if(Q.length===Z.length)return;f1({...W,disabledPlugins:Q})}function Tk($){let W=n$($);while(W!==n$(W)&&Z1(W)!==zX){try{Zk(W)}catch{return}W=n$(W)}}function Ok($){return`${$.names[0]??Z1($.installPath)} at ${$.installPath}`}async function T9($){let W=Uk($),Z=Dk(W),Q=$.path?.trim(),J=$.name?.trim(),j;if(Q){if(j=fk(Q,Z,W),!j)throw Error(`No plugin found at ${Q}`)}else{if(!J)throw Error("plugin uninstall requires a plugin name");let Y=Z.filter((V)=>_k(V,J));if(Y.length===0)throw Error(`No plugin found matching "${J}"`);if(Y.length>1)throw Error(`Multiple plugins match "${J}": ${Y.map(Ok).join(", ")}`);j=Y[0]}let X=Jk(j.installPath,{throwIfNoEntry:!1});if(!X)throw Error(`Plugin install path does not exist: ${j.installPath}`);if(L9({pluginPaths:[j.installPath,...j.entryPaths],pluginNames:j.names}),Qk(j.installPath,{recursive:X.isDirectory(),force:!0}),Lk(j),j.installed)Tk(j.installPath);return{name:J||j.names[0]||Z1(j.installPath),installPath:j.installPath,removedPaths:[j.installPath],entryPaths:j.entryPaths}}var MX=120000,O9=12000,Ck=/(api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|authorization|credential)/i,Pk=/((?:^|[^\w])(?:[a-z0-9_]*?(?:api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|credential)[a-z0-9_]*)\s*[:=]\s*)(.+)$/gi,Sk=/((?:^|[^\w])authorization\s*[:=]\s*)bearer\s+([^\s,"'}\]]+)/gi,bk=/((?:^|[^\w])authorization\s*[:=])(?!\s*bearer\b)\s*(.+)$/gi;function RX($){return $.install?.args??[]}function yk(){return process.env.HOME?.trim()||process.env.USERPROFILE?.trim()||Mk()}function hk($){let W=0,Z=$.length;while(W<Z&&($[W]==="."||$[W]==="-"))W++;while(Z>W&&($[Z-1]==="."||$[Z-1]==="-"))Z--;return $.slice(W,Z)}function kk($){return hk($.toLowerCase().replace(/[^a-z0-9._]+/g,"-")).slice(0,255)||"skill"}function _D($){return $.split(/\r?\n/).map((W)=>{if(!Ck.test(W))return W;return W.replace(Pk,"$1[redacted]").replace(Sk,"$1Bearer [redacted]").replace(/\b(Bearer)\s+(?!\[redacted\])([^\s,"'}\]]+)/gi,"$1 [redacted]").replace(bk,"$1 [redacted]").replace(/((?:^|[^\w])(?:api\s+key|access\s+token|refresh\s+token|auth(?:orization)?\s+token|secret|password|credential)\s+(?:is\s+)?)(\S+)/gi,"$1[redacted]")}).join(`
724
- `).slice(-O9)}function Ik($){let W=_D([$.stdout,$.stderr].filter(Boolean).join(`
725
- `)).trim();return W.length>0?W:void 0}function xk($){if($==="")return'""';if(/^[a-zA-Z0-9_./:=@%+,-]+$/.test($))return $;return JSON.stringify($)}function gk($,W){return[$,...W].map((Z)=>xk(_D(Z).trim())).join(" ")}var mk=async($,W)=>new Promise((Z,Q)=>{let J=!1,j=!1,X=zk($,W,{env:process.env,shell:Rk()==="win32",stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V="",B=setTimeout(()=>{if(!J)X.kill("SIGKILL")},MX+5000),H=setTimeout(()=>{j=!0,V+=`
726
- Timed out after ${MX/1000}s.`,X.kill("SIGTERM")},MX);B.unref?.(),H.unref?.(),X.stdout?.on("data",(G)=>{if(Y+=String(G),Y.length>O9*2)Y=Y.slice(-O9)}),X.stderr?.on("data",(G)=>{if(V+=String(G),V.length>O9*2)V=V.slice(-O9)}),X.once("error",(G)=>{clearTimeout(H),clearTimeout(B),Q(G)}),X.once("close",(G,K)=>{J=!0,clearTimeout(H),clearTimeout(B),Z({exitCode:j?124:G??(K==="SIGINT"?130:1),stdout:Y,stderr:V})})});function EX($){return`${$.type}:${$.id}`}function z9($){let W=RX($);if(W.length===0)throw Error("Marketplace install args are required.");return _9(W).name}function lQ($,W={}){let Z=z9($),Q=W.mcpSettingsPath??wk(),J=A1(Q,(j)=>{let X=j.mcpServers&&typeof j.mcpServers==="object"&&!Array.isArray(j.mcpServers)?j.mcpServers:{},Y=Object.hasOwn(X,Z);if(Y)delete X[Z];return j.mcpServers=X,Y});return{name:Z,deleted:J}}function q9($){let W=new Set,Z=(J)=>{let j=kk(J??"");if(j&&j!=="skill")W.add(j)};Z($.id),Z($.name);let Q=RX($);for(let J=0;J<Q.length;J++){let j=Q[J];if((j==="--skill"||j==="-s")&&Q[J+1]){Z(Q[J+1]),J++;continue}let X=j.split("@").at(1);if(X)Z(X)}return[...W]}function M9($){return[UD(Nk(),"skills",$,"SKILL.md"),UD(yk(),".agents","skills",$,"SKILL.md")].filter((W,Z,Q)=>Q.indexOf(W)===Z)}function R9($){if($.type!=="skill")return;return q9($).find((W)=>M9(W).some((Z)=>DD(Z)))}function pQ($){return R9($)!==void 0}function vk($){let W=[];if($.type!=="skill")return W;for(let Z of q9($))for(let Q of M9(Z)){if(!DD(Q))continue;let J=Ek(Q);qk(J,{recursive:!0,force:!0}),W.push(J)}return W}async function rQ($,W={}){let Z=R9($);if(!Z)return{id:$.id,type:"skill",status:"uninstalled",message:`${$.name??$.id} is not installed.`};let Q="npx",J=["-y","skills@latest","remove",Z,"-g","-y"],j=gk(Q,J),X=W.spawnCommand??mk,Y;try{Y=await X(Q,J)}catch(H){throw Error(`Failed to start ${$.name??$.id} uninstall command:
720
+ version = team_outcome_fragments.version + 1`,[Q,j.outcomeId,j.id,j.section,j.sourceAgentId,j.sourceRunId??null,j.content,j.status,j.reviewedBy??null,j.reviewedAt?j.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,W){let Z=u6($),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[Z]);if(Q.length===0)return[];let J=VX();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
721
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[W,J,Z]),Q.map((j)=>j.run_id)}handleTeamEvent($,W){this.appendTeamEvent($,W.type,W)}}function BX($={}){try{let W=new j8($);return W.init(),W}catch{let W=new D9({teamDir:$.teamDir});return W.init(),W}}function xQ($,W){return zh($,W)}function Mh($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function Rh($,W){return $.filter((Z)=>Mh(Z.name,W))}function HX($,W){return u1(Rh($,W))}var Eh={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 Nh($){let W=$.trim().toLowerCase();return Eh[W]??W}function wh($,W){if(W.tools===void 0)return $;let Z=new Set(W.tools.map(Nh));if(W.skills!==void 0)Z.add("skills");return $.filter((Q)=>Z.has(Q.name))}function mQ(){return`team-${qh(5)}`}function gQ($,W,Z,Q,J,j,X,Y){let V=a0[e1({mode:Z})],B=r8(W,Q,Z,J??p8);return HX(y2({cwd:$,...V,enableSkills:!!X,...B,executors:{...X?{skills:X}:{},...Y??{}}}),j)}function Ch($){return gQ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,Ph,$.toolExecutors).some((W)=>W.name==="skills")}var Ph=async()=>"";async function Sh($){let W=J0();if(!X$({filePath:W}))return{tools:[]};let Z=new a2({clientFactory:z6({settingsPath:W})}),Q;try{Q=await n2(Z,{filePath:W})}catch(Y){await Z.dispose().catch(()=>{});let V=Y instanceof Error?Y.message:String(Y);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${V}`),{tools:[]}}let J=Q.filter((Y)=>Y.disabled!==!0),j=await Promise.allSettled(J.map((Y)=>M6({serverName:Y.name,provider:Z}))),X=[];for(let[Y,V]of j.entries())if(V.status==="fulfilled")X.push(...V.value);else{let B=V.reason instanceof Error?V.reason.message:String(V.reason);$?.log(`[mcp] Failed to load tools from MCP server "${J[Y].name}", skipping: ${B}`)}return{tools:X,shutdown:async()=>{await Z.dispose()}}}function bh($,W){if(!$)return;for(let Z of $.getTeammateIds())try{$.shutdownTeammate(Z,W)}catch{}}function yh($){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 hh($){let W=a0[e1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??W.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??W.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class d6{teamRuntimeEntries=new Map;async build($){let{config:W,hooks:Z,extensions:Q,logger:J,telemetry:j,createSpawnTool:X,onTeamRestored:Y,userInstructionService:V,configExtensions:B,toolExecutors:H}=$,G=$.onTeamEvent??(()=>{}),K=hh(W),F=W.workspaceRoot??W.cwd,A=$.toolPolicies??W.toolPolicies,D=L1(),U=[],f=W.teamName?.trim()||mQ(),_=W.sessionId?.trim()||f,R=K.enableSpawnAgent?w6({workspaceRoot:F}):{configs:[],errors:[]},O=R.configs.some((l)=>l.skills!==void 0),T=xQ(B,"rules"),L=xQ(B,"skills"),C=L||O,E=xQ(B,"workflows"),p=xQ(B,"plugins"),x=T||L||E,P=!1,r=Boolean(V),d=V,I1;for(let l of R.errors)(J??W.logger)?.log?.(`[agents] Failed to load agent config at ${l.path}: ${l.error.message}`);if(!d&&(x||O))d=c$({skills:C?{workspacePath:F,includePluginSkills:p,pluginSkillDirectories:p?$.pluginSkillDirectories:void 0,pluginPaths:W.pluginPaths,cwd:W.cwd}:{workspacePath:F},rules:{workspacePath:W.cwd},workflows:{workspacePath:W.cwd}});if(d)await d.start().catch(()=>{});let $2=K.enableTools&&L&&Boolean(d)&&d?.hasConfiguredSkills(W.skills)===!0&&Ch({cwd:W.cwd,providerId:W.providerId,mode:K.mode,modelId:W.modelId,toolRoutingRules:W.toolRoutingRules,toolPolicies:A,toolExecutors:H}),A$=d&&x?d.createExtension({includeRules:T,includeSkills:L,includeWorkflows:E,registerSkillsTool:$2,allowedSkillNames:W.skills}):void 0,I0=A$?[...Q??W.extensions??[],A$]:Q??W.extensions;if(K.enableTools){if(U.push(...gQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H)),!K.disableMcpSettingsTools){let l=await Sh(W.logger);U.push(...l.tools),I1=l.shutdown}}let U0,D1=K.enableAgentTeams?BX():void 0,K8=D1?.loadRuntime(_),V0=K8?.state,d0=K8?.teammates??[],J1=new Map(d0.map((l)=>[l.agentId,l])),y=W.sessionId||f,j1,k=[],W0=!1,T0=S$({providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey??"",baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,temperature:W.temperature,maxIterations:W.maxIterations,hooks:Z,extensions:I0,logger:J??W.logger,telemetry:$.telemetry??W.telemetry,workspaceMetadata:W.workspaceMetadata});if(K.enableSpawnAgent){if(R.configs.length>0)U.push(...HX(C6({configProvider:T0,agents:R.configs,createSubAgentTools:(l)=>K.enableTools?wh(gQ(W.cwd,l.providerId??W.providerId,K.mode,l.modelId??W.modelId,W.toolRoutingRules,A,l.skills!==void 0&&d?.createSkillsExecutor?d.createSkillsExecutor(l.skills):void 0,H),l):[],hookErrorMode:W.hookErrorMode,toolPolicies:A,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),A))}if(!this.teamRuntimeEntries.has(y))this.teamRuntimeEntries.set(y,{delegatedAgentConfigProvider:T0});let M0=()=>{if(!K.enableAgentTeams)return;let l=this.teamRuntimeEntries.get(y)??{delegatedAgentConfigProvider:T0};if(this.teamRuntimeEntries.set(y,l),U0=l.runtime,!U0){if(U0=new e2({teamName:f,leadAgentId:W.sessionId||"lead",missionLogIntervalSteps:K.missionLogIntervalSteps,missionLogIntervalMs:K.missionLogIntervalMs,onTeamEvent:(B0)=>{if(G(B0),U0&&D1){if(B0.type==="teammate_spawned"&&B0.teammate?.rolePrompt){let x1={agentId:B0.agentId,rolePrompt:B0.teammate.rolePrompt,modelId:B0.teammate.modelId,maxIterations:B0.teammate.maxIterations};J1.set(x1.agentId,x1)}if(B0.type==="teammate_shutdown"&&!yh(B0.reason))J1.delete(B0.agentId);D1.handleTeamEvent(_,B0),D1.persistRuntime(_,U0.exportState(),Array.from(J1.values()))}}}),V0)U0.hydrateState(V0),W0=!0;l.runtime=U0}if(!P){if(!U0)return;P=!0;let B0=o8({runtime:U0,leadAgentId:W.sessionId||"lead",restoredFromPersistence:Boolean(V0),restoredTeammates:d0,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(x1)=>{k=x1,j1?.addTools(x1)},createBaseTools:K.enableTools?()=>gQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H):void 0,teammateConfigProvider:T0});if(W0)U0.recoverActiveRuns("runtime_recovered");if(B0.restoredFromPersistence)Y?.();U.push(...B0.tools)}return U0};if(K.enableSpawnAgent&&X){let l=X();U.push({...l,execute:async(B0,x1)=>{return M0(),l.execute(B0,x1)}})}if(K.enableAgentTeams)M0();let d9=HX(U,A),t6=d9.some((l)=>l.name==="submit_and_exit"&&l.lifecycle?.completesRun===!0),F8=K.enableAgentTeams?()=>{let l=this.teamRuntimeEntries.get(y)?.runtime;if(!l)return;let B0=l.listTasks(),x1=B0.some((U$)=>U$.status==="in_progress"||U$.status==="pending"),iY=l.listRuns({}),kf=iY.some((U$)=>U$.status==="running"||U$.status==="queued");if(x1||kf){let U$=B0.filter((l0)=>l0.status==="in_progress"||l0.status==="pending").map((l0)=>`${l0.id} (${l0.status}): ${l0.title}`).join(", "),nY=iY.filter((l0)=>l0.status==="running"||l0.status==="queued").map((l0)=>`${l0.id} (${l0.status})`).join(", "),w7=[];if(U$)w7.push(`Unfinished tasks: ${U$}`);if(nY)w7.push(`Active runs: ${nY}`);return`[SYSTEM] You still have team obligations. ${w7.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,hf=t6?{requireCompletionTool:!0,...F8?{completionGuard:F8}:{}}:F8?{completionGuard:F8}:void 0;return{tools:d9,logger:J??W.logger,telemetry:j??W.telemetry,teamRuntime:U0,teamRestoredFromPersistence:Boolean(V0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(y)?.delegatedAgentConfigProvider??T0,extensions:I0,completionPolicy:hf,registerLeadAgent:(l)=>{if(j1=l,k.length>0)l.addTools(u1(k,[...D]))},shutdown:async(l)=>{if(bh(U0,l),this.teamRuntimeEntries.delete(y),await I1?.(),!r)d?.stop()}}}}var jD={};w(jD,{requestDesktopToolApproval:()=>KX});import{mkdir as kh,readFile as Ih,unlink as xh,writeFile as gh}from"node:fs/promises";import{join as JD}from"node:path";function mh($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function vh($){return new Promise((W)=>setTimeout(W,$))}async function GX($){try{await xh($)}catch{}}async function KX($,W={}){let Z=W.approvalDir?.trim(),Q=W.sessionId?.trim();if(!Z||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await kh(Z,{recursive:!0});let J=mh(`${$.toolCallId}`),j=JD(Z,`${Q}.request.${J}.json`),X=JD(Z,`${Q}.decision.${J}.json`),Y=W.nowIso??(()=>new Date().toISOString());await gh(j,`${JSON.stringify({requestId:J,sessionId:Q,createdAt:Y(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
722
+ `,"utf8");let V=W.timeoutMs??300000,B=W.pollIntervalMs??200,H=Date.now();while(Date.now()-H<V){try{let G=await Ih(X,"utf8"),K=JSON.parse(G),F={approved:K.approved===!0,reason:typeof K.reason==="string"?K.reason:void 0};return await Promise.all([GX(X),GX(j)]),F}catch{}await vh(B)}return await GX(j),{approved:!1,reason:"Tool approval request timed out"}}X1();var LD={};w(LD,{uninstallMarketplaceSkill:()=>iQ,uninstallMarketplacePlugin:()=>nQ,uninstallMarketplaceMcpServerFromSettings:()=>pQ,uninstallMarketplaceEntry:()=>wX,resolveMarketplaceMcpServerName:()=>z9,marketplaceEntryKey:()=>NX,isMarketplaceSkillInstalled:()=>rQ,getMarketplaceSkillCandidates:()=>q9,getGlobalMarketplaceSkillPaths:()=>M9,findInstalledGlobalMarketplaceSkillName:()=>R9});import{spawn as qk}from"node:child_process";import{existsSync as _D,rmSync as Mk}from"node:fs";import{homedir as Rk,platform as Ek}from"node:os";import{dirname as Nk,join as DD}from"node:path";import{resolveClineDir as wk,resolveMcpSettingsPath as Ck}from"@cline/shared/storage";var YD={};w(YD,{parseMcpInstallArgs:()=>_9,installMcpServer:()=>FX,buildMcpInstallTransport:()=>vQ});function ch($){let W=($??"stdio").trim();if(W==="http"||W==="streamable-http")return"streamableHttp";if(W==="stdio"||W==="sse"||W==="streamableHttp")return W;throw Error(`Unsupported MCP transport "${W}". Expected stdio, sse, http, streamable-http, or streamableHttp.`)}function uh($){let W;try{W=new URL($)}catch{throw Error(`Invalid MCP server URL: ${$}`)}if(W.protocol!=="http:"&&W.protocol!=="https:")throw Error(`Invalid MCP server URL: ${$} (only http and https are supported)`)}function dh($){let W=$.indexOf(":");if(W<=0)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);let Z=$.slice(0,W).trim(),Q=$.slice(W+1).trim();if(!Z||!Q)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);if(!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(Z))throw Error(`Invalid MCP header name "${Z}".`);return[Z,Q]}function lh($){let W=$.indexOf("<");return W>=0&&$.indexOf(">",W+1)>W+1}function XD($){let W=[...$.headers??[]],Z=[],Q=$.transport,J=$.targetArgs??[];for(let j=0;j<J.length;j++){let X=J[j];if($.parseTransport&&X==="--transport"){let Y=J[j+1];if(!Y)throw Error("--transport requires a value");Q=Y,j++;continue}if($.parseTransport&&X?.startsWith("--transport=")){Q=X.slice(12);continue}if(X==="--header"){let Y=J[j+1];if(!Y)throw Error("--header requires a value");W.push(Y),j++;continue}if(X?.startsWith("--header=")){W.push(X.slice(9));continue}Z.push(X)}return{headers:W,targetArgs:Z,transport:Q}}function ph($){if($.length===0)return{warnings:[]};let W={},Z=[];for(let Q of $){let[J,j]=dh(Q);if(W[J]=j,lh(j))Z.push(`Header "${J}" looks like it contains a placeholder. Update it in MCP settings before using this server.`)}return{headers:W,warnings:Z}}function vQ($){let W=$.name.trim();if(!W)throw Error("MCP server name is required");let{headers:Z,targetArgs:Q,transport:J}=XD({headers:$.headers,targetArgs:$.targetArgs,transport:$.transport}),j=ch(J),{headers:X,warnings:Y}=ph(Z);if(j==="stdio"){if(Z.length>0)throw Error("Stdio MCP installs do not support request headers.");let[B,...H]=Q;if(!B?.trim())throw Error("Stdio MCP install requires a command after the server name, for example: cline mcp install fs --yes -- npx -y @modelcontextprotocol/server-filesystem /tmp");return{name:W,transport:{type:j,command:B,args:H.length>0?H:void 0},warnings:Y}}if(Q.length!==1)throw Error("Remote MCP install requires exactly one URL argument after the server name.");let V=Q[0]?.trim()??"";return uh(V),{name:W,transport:X?{type:j,url:V,headers:X}:{type:j,url:V},warnings:Y}}function _9($){let[W,...Z]=$;if(!W)throw Error("Marketplace MCP install args must start with a server name.");return{name:W,...XD({parseTransport:!0,targetArgs:Z})}}function rh($,W,Z){A1(Z,(Q)=>{let J=Q.mcpServers,j=J&&typeof J==="object"&&!Array.isArray(J)?{...J}:{};j[$]={transport:W},Q.mcpServers=j})}function FX($){let{name:W,transport:Z,warnings:Q}=vQ($);return rh(W,Z,$.settingsPath??J0()),{name:W,status:"installed",transport:Z,warnings:Q}}X1();var UD={};w(UD,{uninstallPlugin:()=>T9});import{existsSync as p6,readdirSync as Wk,readFileSync as Zk,rmdirSync as Qk,rmSync as Jk,statSync as jk}from"node:fs";import{basename as Z1,dirname as n$,extname as Xk,isAbsolute as Yk,join as G$,relative as Vk,resolve as l6,sep as fX}from"node:path";import{discoverPluginModulePaths as Bk,resolvePluginConfigSearchPaths as Hk}from"@cline/shared/storage";var GD={};w(GD,{syncPluginMcpServersToSettings:()=>f9,removePluginMcpServersFromSettings:()=>L9,disablePluginMcpServersInSettings:()=>_X});import{existsSync as ih,mkdirSync as nh,readFileSync as ah,writeFileSync as oh}from"node:fs";import{dirname as BD,isAbsolute as sh,relative as th,resolve as VD}from"node:path";function X8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function cQ($,W){let Z=th(VD($),VD(W));return Z===""||!Z.startsWith("..")&&!sh(Z)}function AX($){if(!ih($))return{mcpServers:{}};try{let W=JSON.parse(ah($,"utf8"));if(X8(W))return W}catch(W){throw Error(`Invalid MCP settings at "${$}": ${W instanceof Error?W.message:String(W)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function UX($){if(X8($.mcpServers))return{...$.mcpServers};return{}}function DX($,W,Z){nh(BD($),{recursive:!0}),oh($,`${JSON.stringify({...W,mcpServers:Z},null,2)}
723
+ `,"utf8")}function HD($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((W)=>W.trim()).filter((W)=>W.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((W)=>W.trim()).filter((W)=>W.length>0))]}}function dQ($){if(!X8($))return;let W=$.metadata;return X8(W)?W:void 0}function uQ($,W){let Z=dQ($);if(!Z||Z.source!=="plugin")return!1;let Q=typeof Z.pluginName==="string"?Z.pluginName:typeof Z.plugin==="string"?Z.plugin:void 0,J=typeof Z.pluginPath==="string"?Z.pluginPath:void 0;if(W.pluginName&&Q===W.pluginName){if(!W.pluginPath||J===W.pluginPath)return!0}if(J&&W.pluginPath&&(J===W.pluginPath||cQ(W.pluginPath,J)||cQ(J,W.pluginPath)))return!0;if(Q&&W.pluginNames?.some((j)=>j===Q))return!0;if(J&&W.pluginPaths?.some((j)=>J===j||cQ(j,J)||cQ(J,j)))return!0;return!1}function eh($){let W=X8($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:BD($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...W,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function $k($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let W=await j6({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Z=[],Q=[],J=(W.failures??[]).map((j)=>({pluginPath:j.pluginPath,pluginName:j.pluginName,message:j.message}));for(let j of W.extensions??[]){let X=j.__clinePluginPath;if(!X)continue;if(!j.setup){Z.push({pluginName:j.name,pluginPath:X});continue}let Y=[],V={registerTool:(B)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(B)=>{if(!j.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');Y.push(B)}};try{await j.setup(V,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(B){J.push({pluginPath:X,pluginName:j.name,message:B instanceof Error?B.message:String(B)});continue}Z.push({pluginName:j.name,pluginPath:X});for(let B of Y)Q.push({pluginName:j.name,pluginPath:X,server:{...B,metadata:{...B.metadata??{},source:"plugin",pluginName:j.name,pluginPath:X}}})}return{plugins:Z,servers:Q,failures:J}}finally{await W.shutdown().catch(()=>{})}}async function f9($){let W=$.settingsPath??J0(),Z={mutations:[],failures:[]},Q;try{Q=await $k($)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}Z.failures.push(...Q.failures);let J;try{J=AX(W)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}let j=UX(J),X=new Map,Y=new Map;for(let B of Q.plugins)X.set(B.pluginPath,new Set),Y.set(B.pluginPath,B.pluginName);let V=AQ(Q.servers.map((B)=>({server:B.server,owner:B,ownerLabel:B.pluginName})));for(let B of V){let H=B.owner;if(!X.has(H.pluginPath))X.set(H.pluginPath,new Set);if(B.name)X.get(H.pluginPath)?.add(B.name);if(!B.registration){Z.mutations.push({name:B.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:B.loadError??"invalid MCP server registration"});continue}let G=j[B.registration.name];if(G!==void 0){if(!uQ(G,{pluginName:H.pluginName,pluginPath:H.pluginPath})){Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}j[B.registration.name]=eh({registration:B.registration,pluginName:H.pluginName,pluginPath:H.pluginPath,existing:X8(G)?G:void 0}),Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:G===void 0?"created":"updated"})}for(let[B,H]of Object.entries(j)){let G=dQ(H),K=typeof G?.pluginPath==="string"?G.pluginPath:"",F=X.get(K);if(F&&uQ(H,{pluginPath:K})&&!F.has(B))delete j[B],Z.mutations.push({name:B,pluginName:typeof G?.pluginName==="string"?G.pluginName:Y.get(K)??"plugin",pluginPath:K,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Z.mutations.some((B)=>B.action!=="skipped"))try{DX(W,J,j)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)})}return Z}function _X($){let W=$.settingsPath??J0(),Z;try{Z=AX(W)}catch{return[]}let Q=UX(Z),J=HD($),j=[];for(let[X,Y]of Object.entries(Q)){if(!X8(Y)||!uQ(Y,J))continue;let V=dQ(Y);Q[X]={...Y,disabled:!0},j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"disabled"})}if(j.length>0)DX(W,Z,Q);return j}function L9($){let W=$.settingsPath??J0(),Z;try{Z=AX(W)}catch{return[]}let Q=UX(Z),J=HD($),j=[];for(let[X,Y]of Object.entries(Q)){if(!uQ(Y,J))continue;let V=dQ(Y);delete Q[X],j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"removed"})}if(j.length>0)DX(W,Z,Q);return j}var qX="_installed",Gk="package",Kk=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function LX($){return $.trim().toLowerCase()}function U1($,W){let Z=W?.trim();if(!Z)return;$.add(Z)}function Fk($){return $.replace(/-[0-9a-f]{12}$/i,"")}function TX($){let W=Xk($);return W?$.slice(0,-W.length):$}function OX($){if(!p6($))return;try{let W=JSON.parse(Zk($,"utf8"));return typeof W.name==="string"?W.name.trim():void 0}catch{return}}function MX($,W){let Z=Vk(W,$);return Z===""||!Z.startsWith("..")&&!Yk(Z)}function KD($){let Z=l6($).split(fX),Q=Z.lastIndexOf(qX);if(Q<0)return;let J=Z[Q+1];if(!J)return;let j=Kk.get(J)??1,X=Q+2+j;if(Z.length<X)return;let Y=Z.slice(0,X).join(fX)||fX;return p6(Y)?Y:void 0}function lQ($){try{return Wk($,{withFileTypes:!0})}catch{return[]}}function Ak($){let W=G$($,qX);if(!p6(W))return[];let Z=[];for(let Q of lQ(W)){if(!Q.isDirectory())continue;let J=G$(W,Q.name);if(Q.name==="git"){for(let j of lQ(J)){if(!j.isDirectory())continue;let X=G$(J,j.name);for(let Y of lQ(X))if(Y.isDirectory())Z.push(G$(X,Y.name))}continue}for(let j of lQ(J))if(j.isDirectory())Z.push(G$(J,j.name))}return Z.sort((Q,J)=>Q.localeCompare(J))}function FD($){try{return Bk($)}catch{return[]}}function zX($){let W=FD($),Z=new Set;U1(Z,Z1($)),U1(Z,Fk(Z1($))),U1(Z,OX(G$($,"package.json"))),U1(Z,OX(G$($,Gk,"package.json")));for(let Q of W)U1(Z,Z1(Q)),U1(Z,TX(Z1(Q)));return{installPath:$,entryPaths:W,names:[...Z].sort((Q,J)=>Q.localeCompare(J)),installed:!0}}function Uk($,W){let Z=l6($),Q=W.find((X)=>MX(Z,X));if(!Q)return;let J=n$(Z);while(J!==Q&&J!==n$(J)){if(p6(G$(J,"package.json")))return J;J=n$(J)}let j=Z1(Z);if((j==="index.ts"||j==="index.js")&&n$(Z)!==Q)return n$(Z);return Z}function AD($,W){let Z=Uk($,W);if(!Z)return;let Q=new Set;return U1(Q,Z1($)),U1(Q,TX(Z1($))),U1(Q,Z1(Z)),U1(Q,TX(Z1(Z))),U1(Q,OX(G$(Z,"package.json"))),{installPath:Z,entryPaths:[$],names:[...Q].sort((J,j)=>J.localeCompare(j)),installed:!1}}function Dk($){let W=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return Hk(W).filter((Z)=>p6(Z))}function _k($){let W=new Map;for(let Z of $){for(let Q of Ak(Z))W.set(Q,zX(Q));for(let Q of FD(Z)){let J=KD(Q);if(J){if(!W.has(J))W.set(J,zX(J));continue}let j=AD(Q,$);if(j)W.set(j.installPath,j)}}return[...W.values()].sort((Z,Q)=>Z.installPath.localeCompare(Q.installPath))}function fk($,W){let Z=LX(W);if(!Z)return!1;if(LX($.installPath)===Z)return!0;return $.names.some((Q)=>LX(Q)===Z)}function Lk($,W,Z){let Q=l6($);for(let j of W){if(MX(Q,j.installPath))return j;if(j.entryPaths.some((X)=>l6(X)===Q))return j}let J=KD(Q);if(J)return zX(J);if(p6(Q))return AD(Q,Z);return}function Tk($){let W=E0(),Z=W.disabledPlugins;if(!Z?.length)return;let Q=Z.filter((J)=>{let j=l6(J);if(MX(j,$.installPath))return!1;return!$.entryPaths.some((X)=>l6(X)===j)});if(Q.length===Z.length)return;f1({...W,disabledPlugins:Q})}function Ok($){let W=n$($);while(W!==n$(W)&&Z1(W)!==qX){try{Qk(W)}catch{return}W=n$(W)}}function zk($){return`${$.names[0]??Z1($.installPath)} at ${$.installPath}`}async function T9($){let W=Dk($),Z=_k(W),Q=$.path?.trim(),J=$.name?.trim(),j;if(Q){if(j=Lk(Q,Z,W),!j)throw Error(`No plugin found at ${Q}`)}else{if(!J)throw Error("plugin uninstall requires a plugin name");let Y=Z.filter((V)=>fk(V,J));if(Y.length===0)throw Error(`No plugin found matching "${J}"`);if(Y.length>1)throw Error(`Multiple plugins match "${J}": ${Y.map(zk).join(", ")}`);j=Y[0]}let X=jk(j.installPath,{throwIfNoEntry:!1});if(!X)throw Error(`Plugin install path does not exist: ${j.installPath}`);if(L9({pluginPaths:[j.installPath,...j.entryPaths],pluginNames:j.names}),Jk(j.installPath,{recursive:X.isDirectory(),force:!0}),Tk(j),j.installed)Ok(j.installPath);return{name:J||j.names[0]||Z1(j.installPath),installPath:j.installPath,removedPaths:[j.installPath],entryPaths:j.entryPaths}}var RX=120000,O9=12000,Pk=/(api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|authorization|credential)/i,Sk=/((?:^|[^\w])(?:[a-z0-9_]*?(?:api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|credential)[a-z0-9_]*)\s*[:=]\s*)(.+)$/gi,bk=/((?:^|[^\w])authorization\s*[:=]\s*)bearer\s+([^\s,"'}\]]+)/gi,yk=/((?:^|[^\w])authorization\s*[:=])(?!\s*bearer\b)\s*(.+)$/gi;function EX($){return $.install?.args??[]}function hk(){return process.env.HOME?.trim()||process.env.USERPROFILE?.trim()||Rk()}function kk($){let W=0,Z=$.length;while(W<Z&&($[W]==="."||$[W]==="-"))W++;while(Z>W&&($[Z-1]==="."||$[Z-1]==="-"))Z--;return $.slice(W,Z)}function Ik($){return kk($.toLowerCase().replace(/[^a-z0-9._]+/g,"-")).slice(0,255)||"skill"}function fD($){return $.split(/\r?\n/).map((W)=>{if(!Pk.test(W))return W;return W.replace(Sk,"$1[redacted]").replace(bk,"$1Bearer [redacted]").replace(/\b(Bearer)\s+(?!\[redacted\])([^\s,"'}\]]+)/gi,"$1 [redacted]").replace(yk,"$1 [redacted]").replace(/((?:^|[^\w])(?:api\s+key|access\s+token|refresh\s+token|auth(?:orization)?\s+token|secret|password|credential)\s+(?:is\s+)?)(\S+)/gi,"$1[redacted]")}).join(`
724
+ `).slice(-O9)}function xk($){let W=fD([$.stdout,$.stderr].filter(Boolean).join(`
725
+ `)).trim();return W.length>0?W:void 0}function gk($){if($==="")return'""';if(/^[a-zA-Z0-9_./:=@%+,-]+$/.test($))return $;return JSON.stringify($)}function mk($,W){return[$,...W].map((Z)=>gk(fD(Z).trim())).join(" ")}var vk=async($,W)=>new Promise((Z,Q)=>{let J=!1,j=!1,X=qk($,W,{env:process.env,shell:Ek()==="win32",stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V="",B=setTimeout(()=>{if(!J)X.kill("SIGKILL")},RX+5000),H=setTimeout(()=>{j=!0,V+=`
726
+ Timed out after ${RX/1000}s.`,X.kill("SIGTERM")},RX);B.unref?.(),H.unref?.(),X.stdout?.on("data",(G)=>{if(Y+=String(G),Y.length>O9*2)Y=Y.slice(-O9)}),X.stderr?.on("data",(G)=>{if(V+=String(G),V.length>O9*2)V=V.slice(-O9)}),X.once("error",(G)=>{clearTimeout(H),clearTimeout(B),Q(G)}),X.once("close",(G,K)=>{J=!0,clearTimeout(H),clearTimeout(B),Z({exitCode:j?124:G??(K==="SIGINT"?130:1),stdout:Y,stderr:V})})});function NX($){return`${$.type}:${$.id}`}function z9($){let W=EX($);if(W.length===0)throw Error("Marketplace install args are required.");return _9(W).name}function pQ($,W={}){let Z=z9($),Q=W.mcpSettingsPath??Ck(),J=A1(Q,(j)=>{let X=j.mcpServers&&typeof j.mcpServers==="object"&&!Array.isArray(j.mcpServers)?j.mcpServers:{},Y=Object.hasOwn(X,Z);if(Y)delete X[Z];return j.mcpServers=X,Y});return{name:Z,deleted:J}}function q9($){let W=new Set,Z=(J)=>{let j=Ik(J??"");if(j&&j!=="skill")W.add(j)};Z($.id),Z($.name);let Q=EX($);for(let J=0;J<Q.length;J++){let j=Q[J];if((j==="--skill"||j==="-s")&&Q[J+1]){Z(Q[J+1]),J++;continue}let X=j.split("@").at(1);if(X)Z(X)}return[...W]}function M9($){return[DD(wk(),"skills",$,"SKILL.md"),DD(hk(),".agents","skills",$,"SKILL.md")].filter((W,Z,Q)=>Q.indexOf(W)===Z)}function R9($){if($.type!=="skill")return;return q9($).find((W)=>M9(W).some((Z)=>_D(Z)))}function rQ($){return R9($)!==void 0}function ck($){let W=[];if($.type!=="skill")return W;for(let Z of q9($))for(let Q of M9(Z)){if(!_D(Q))continue;let J=Nk(Q);Mk(J,{recursive:!0,force:!0}),W.push(J)}return W}async function iQ($,W={}){let Z=R9($);if(!Z)return{id:$.id,type:"skill",status:"uninstalled",message:`${$.name??$.id} is not installed.`};let Q="npx",J=["-y","skills@latest","remove",Z,"-g","-y"],j=mk(Q,J),X=W.spawnCommand??vk,Y;try{Y=await X(Q,J)}catch(H){throw Error(`Failed to start ${$.name??$.id} uninstall command:
727
727
  ${j}
728
- ${H instanceof Error?H.message:String(H)}`)}let V=Ik(Y);if(Y.exitCode!==0)throw Error(`${$.name??$.id} uninstall failed with exit code ${Y.exitCode}.
728
+ ${H instanceof Error?H.message:String(H)}`)}let V=xk(Y);if(Y.exitCode!==0)throw Error(`${$.name??$.id} uninstall failed with exit code ${Y.exitCode}.
729
729
  Command:
730
730
  ${j}${V?`
731
731
 
732
- ${V}`:""}`);let B=vk($);if(pQ($))throw Error(`Skill uninstall completed, but ${$.name??$.id} is still present in Cline's global skills directories.`);return{id:$.id,type:"skill",status:"uninstalled",message:`Uninstalled ${$.name??$.id}.`,output:[V,...B.map((H)=>`Removed: ${H}`)].filter(Boolean).join(`
733
- `)||void 0}}async function iQ($,W={}){let[Z]=RX($),Q=Z?.trim()||$.id;if(!Q)throw Error("Plugin marketplace uninstalls require a plugin name.");let J=await T9({name:Q,workspaceRoot:W.workspaceRoot});return{id:$.id,type:"plugin",status:"uninstalled",message:`Uninstalled ${$.name??J.name??$.id}.`,output:[`Path: ${J.installPath}`,...J.removedPaths.map((j)=>`Removed: ${j}`)].join(`
734
- `)}}async function NX($,W={}){if($.type==="mcp"){let Z=z9($);if(W.deleteMcpServer)await W.deleteMcpServer(Z);else lQ($,W);return{id:$.id,type:$.type,status:"uninstalled",message:`Uninstalled ${$.name??Z??$.id}.`}}if($.type==="skill")return rQ($,W);if($.type==="plugin")return iQ($,W);throw Error(`Unsupported marketplace entry type: ${$.type}`)}var bD={};w(bD,{parsePluginSource:()=>Z7,isOfficialPluginSlug:()=>W7,installPlugin:()=>yX,collectPluginMcpOAuthCandidates:()=>Q7});import{spawn as ck}from"node:child_process";import{createHash as uk}from"node:crypto";import{existsSync as y1,mkdirSync as PX,readdirSync as dk,readFileSync as lk,renameSync as nQ,rmSync as sQ,statSync as SX}from"node:fs";import{cp as CX,mkdir as ED,writeFile as tQ}from"node:fs/promises";import{homedir as LD}from"node:os";import{basename as F$,dirname as TD,extname as pk,join as t,relative as ND,resolve as a$,sep as rk}from"node:path";import{isPluginModulePath as oQ,resolveClineDir as ik,resolvePluginModuleEntries as nk}from"@cline/shared/storage";var r6="_installed",eQ="package",ak="https://github.com/cline/plugins.git",OD=30000,aQ=10485760,zD="@cline/",ok=["dependencies","devDependencies","optionalDependencies","peerDependencies"],sk={name:"cline-installed-plugin",private:!0,cline:{plugins:[]}};function $7($){if($==="~")return LD();if($.startsWith("~/"))return t(LD(),$.slice(2));return $}function wD($){return $.split(rk).join("/")}function Y8($){return uk("sha256").update($).digest("hex").slice(0,12)}function tk($){let W=0;while(W<$.length&&$[W]==="-")W++;let Z=$.length;while(Z>W&&$[Z-1]==="-")Z--;return $.slice(W,Z)}function K$($){let W="",Z=!1,Q=$.startsWith("@")?$.slice(1):$;for(let j of Q.slice(0,256)){if(j>="a"&&j<="z"||j>="A"&&j<="Z"||j>="0"&&j<="9"||j==="."||j==="_"||j==="-")W+=j,Z=j==="-";else if(!Z)W+="-",Z=!0;if(W.length>=80)break}return tk(W)||"plugin"}function W7($){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test($.trim())}function ek($){return $?.trim()||ak}function qD($){let Z=$.trim().match(/^(@?[^@/]+(?:\/[^@/]+)?)(?:@.+)?$/);if(!Z?.[1])throw Error(`Invalid npm plugin source: npm:${$}`);return{name:Z[1]}}function $I($){if($.startsWith(".")||$.startsWith("/")||$==="~"||$.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test($))return!1;let[W,...Z]=$.split("/");return!!W&&Z.length>=2&&W.includes(".")&&!W.startsWith(".")&&!W.endsWith(".")}function WI($){let W=$.match(/^git@([^:]+):(.+)$/);if(W){let X=W[2]??"",Y=X.indexOf("@");if(Y<0)return{repo:$};return{repo:`git@${W[1]}:${X.slice(0,Y)}`,ref:X.slice(Y+1)||void 0}}if($.includes("://"))try{let X=new URL($),Y=X.pathname.replace(/^\/+/,""),V=Y.indexOf("@");if(V<0)return{repo:$};return X.pathname=`/${Y.slice(0,V)}`,{repo:X.toString().replace(/\/$/,""),ref:Y.slice(V+1)||void 0}}catch{return{repo:$}}let Z=$.indexOf("/");if(Z<0)return{repo:$};let Q=$.slice(0,Z),J=$.slice(Z+1),j=J.indexOf("@");if(j<0)return{repo:$};return{repo:`${Q}/${J.slice(0,j)}`,ref:J.slice(j+1)||void 0}}function ZI($){try{return decodeURIComponent($)}catch{return $}}function QI($){return F$(ZI($))||"plugin"}function JI($){let W=$.split("/").filter(Boolean);return W.length>=5&&(W[2]==="blob"||W[2]==="raw")}function MD($){if(!/^https?:\/\//i.test($))return null;let W;try{W=new URL($)}catch{return null}let Z=W.hostname.toLowerCase(),Q=QI(W.pathname),J=oQ(Q),j=(Z==="github.com"||Z==="www.github.com")&&JI(W.pathname);if(W.protocol!=="https:"){if(j||Z==="raw.githubusercontent.com"||J)throw Error(`Remote plugin file URLs must use https: ${$}`);return null}if(Z==="github.com"||Z==="www.github.com"){let X=W.pathname.split("/").filter(Boolean);if(!j)return null;if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:`https://raw.githubusercontent.com/${[X[0],X[1],...X.slice(3)].join("/")}`,filename:Q}}if(Z==="raw.githubusercontent.com"){if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:W.toString(),filename:Q}}if(!J)return null;return{type:"remote",url:W.toString(),filename:Q}}function RD($,W={}){let Z=$.trim(),Q=Z.startsWith("git:")&&!Z.startsWith("git://"),J=Q?Z.slice(4).trim():Z;if(!W.force&&!Q&&!/^(https?|ssh|git):\/\//i.test(J))return null;let{repo:j,ref:X}=WI(J),Y="",V="";if(j.startsWith("git@")){let G=j.match(/^git@([^:]+):(.+)$/);Y=G?.[1]??"",V=G?.[2]??""}else if(/^(https?|ssh|git):\/\//i.test(j)){let G=new URL(j);Y=G.hostname,V=G.pathname.replace(/^\/+/,"")}else{let G=j.indexOf("/");if(G<0)return null;Y=j.slice(0,G),V=j.slice(G+1)}let B=V.replace(/\.git$/,"").replace(/^\/+/,"");if(!Y||!B||B.split("/").length<2)return null;return{type:"git",repo:j.startsWith("git@")||/^(https?|ssh|git):\/\//i.test(j)?j:`https://${j}`,ref:X,host:Y,path:B}}function Z7($,W){let Z=$.trim();if(!Z)throw Error("plugin install requires a source");if(W==="npm"){let X=Z.startsWith("npm:")?Z.slice(4).trim():Z,{name:Y}=qD(X);return{type:"npm",spec:X,name:Y}}if(W==="git"){let X=RD(Z,{force:!0});if(!X)throw Error(`Invalid git plugin source: ${$}`);return X}if(W==="local")return{type:"local",path:$};if(W==="remote"){let X=MD(Z);if(!X)throw Error(`Invalid remote plugin source: ${$}`);return X}if(Z.startsWith("npm:")){let X=Z.slice(4).trim(),{name:Y}=qD(X);return{type:"npm",spec:X,name:Y}}if(Z.startsWith(".")||Z.startsWith("/")||Z==="~"||Z.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test(Z))return{type:"local",path:$};let J=MD(Z);if(J)return J;let j=RD(Z);if(j)return j;if(W7(Z))return{type:"official",slug:Z};if($I(Z))throw Error(`Unrecognized plugin source "${$}". Use --git for hostname-style repositories or pass an explicit local path such as ./github.com/owner/repo.`);return{type:"local",path:$}}function jI($){return $?t($,".cline","plugins"):t(ik(),"plugins")}function XI($,W,Z){if(W.type==="npm")return t($,r6,"npm",`${K$(W.name)}-${Y8(Z)}`);if(W.type==="git")return t($,r6,"git",K$(W.host),`${K$(W.path)}-${Y8(Z)}`);if(W.type==="remote")return t($,r6,"remote",`${K$(W.filename)}-${Y8(Z)}`);if(W.type==="official")return t($,r6,"official",`${K$(W.slug)}-${Y8(Z)}`);return t($,r6,"local",`${K$(F$($7(W.path)))}-${Y8(Z)}`)}function YI($,W,Z){if($.type==="npm")return`npm:${$.spec}`;if($.type==="git")return`git:${$.repo}${$.ref?`#${$.ref}`:""}`;if($.type==="remote")return`remote:${$.url}`;if($.type==="official")return`official:${Z}#plugins/${$.slug}`;return`local:${a$(W,$7($.path))}`}function VI($,W){if($.type==="npm")return $.name;if($.type==="git")return K$(F$($.path));if($.type==="remote")return K$(F$($.filename,pk($.filename)));if($.type==="official")return $.slug;return K$(F$(a$(W,$7($.path))))}async function i6($,W,Z={}){await new Promise((Q,J)=>{let j=ck($,W,{cwd:Z.cwd,stdio:["ignore","ignore","pipe"],env:process.env,windowsHide:!0}),X="";j.stderr.on("data",(Y)=>{X+=String(Y)}),j.on("error",J),j.on("close",(Y)=>{if(Y===0){Q();return}let V=X.trim();J(Error(`${$} ${W.join(" ")} failed with exit code ${Y}${V?`: ${V}`:""}`))})})}function CD($){let W=t($,"package.json");if(!y1(W))return null;try{return JSON.parse(lk(W,"utf8"))}catch{return null}}function BI($){let W=$?.cline?.plugins;if(!Array.isArray(W))return[];return W.flatMap((Z)=>{if(typeof Z==="string")return[Z];return Z.paths??[]})}async function HI($){let W=t($,"package.json"),Z=CD($);if(!Z)return;let Q=!1;for(let J of ok){let j=Z[J];if(!j||typeof j!=="object")continue;for(let X of Object.keys(j)){if(!X.startsWith(zD))continue;delete j[X],delete Z.peerDependenciesMeta?.[X],Q=!0}if(Object.keys(j).length===0)delete Z[J]}if(Z.peerDependenciesMeta){for(let J of Object.keys(Z.peerDependenciesMeta)){if(!J.startsWith(zD))continue;delete Z.peerDependenciesMeta[J],Q=!0}if(Object.keys(Z.peerDependenciesMeta).length===0)delete Z.peerDependenciesMeta}if(!Q)return;await tQ(W,`${JSON.stringify(Z,null,2)}
735
- `,"utf8")}function GI($,W){let Z=t($,"node_modules","@cline");if(!y1(Z))return;for(let Q of SD(Z)){if(`@cline/${Q.name}`===W)continue;sQ(t(Z,Q.name),{recursive:!0,force:!0})}}function PD($){let W=BI(CD($)).map((j)=>a$($,j)).filter((j)=>y1(j)&&SX(j).isFile()&&oQ(j));if(W.length>0)return W;let Z=nk($);if(Z?.length)return Z;let Q=[],J=[$];while(J.length>0){let j=J.pop();if(!j)continue;for(let X of SD(j)){let Y=t(j,X.name);if(X.name==="node_modules"||X.name===".git")continue;if(X.isDirectory()){J.push(Y);continue}if(X.isFile()&&!X.name.startsWith(".")&&oQ(Y))Q.push(Y)}}return Q.sort((j,X)=>j.localeCompare(X))}function SD($){try{return dk($,{withFileTypes:!0})}catch{return[]}}function KI($,W){let Z=PD(W);if(Z.length===0)throw Error(`No plugin entry files found in ${W}`);return Z.map((Q)=>`./${wD(ND($,Q))}`)}async function FI($,W,Z){let Q=KI($,W);return await tQ(t($,"package.json"),JSON.stringify({...sk,name:Z,cline:{plugins:[{paths:Q}]}},null,2),"utf8"),Q}async function AI($,W,Z){let Q=t(W,eQ);return await ED(Q,{recursive:!0}),await tQ(t(Q,"package.json"),JSON.stringify({name:"cline-plugin-install",private:!0},null,2),"utf8"),await i6(Z,["install",$.spec,"--prefix",Q,"--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"]),GI(Q,$.name),t(Q,"node_modules",$.name)}async function bX($,W){if(!y1(t($,"package.json")))return;await HI($),await i6(W,["install","--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"],{cwd:$})}async function UI($,W,Z){if($.ref?.startsWith("-"))throw Error(`Invalid git ref "${$.ref}".`);let Q=t(W,eQ),J=["clone","--filter=blob:none"];if($.ref)J.push("--branch",$.ref);J.push("--",$.repo,Q);try{await i6("git",J)}catch(j){if(!$.ref)throw j;await i6("git",["clone","--filter=blob:none","--",$.repo,Q]),await i6("git",["checkout","--detach",$.ref],{cwd:Q})}return await bX(Q,Z),Q}async function DI($,W,Z,Q){let J=t(W,"repo");await i6("git",["clone","--filter=blob:none","--depth","1","--",Q,J]);let j=t(J,"plugins",$.slug);if(!y1(j)||!SX(j).isDirectory())throw Error(`Official Cline plugin "${$.slug}" was not found at plugins/${$.slug} in ${Q}`);let X=t(W,eQ);return await CX(j,X,{recursive:!0,filter:(Y)=>{let V=F$(Y);return V!==".git"&&V!=="node_modules"}}),sQ(J,{recursive:!0,force:!0}),await bX(X,Z),X}function wX($){return Error(`Remote plugin file from ${$} exceeds the ${aQ} byte limit`)}function _I($){let W=$.headers.get("content-length");if(!W)return;let Z=Number(W);if(!Number.isFinite(Z)||Z<0)return;return Z}async function fI($,W){let Z=_I($);if(Z!==void 0&&Z>aQ)throw wX(W);if(!$.body){let X=Buffer.from(await $.text(),"utf8");if(X.byteLength>aQ)throw wX(W);return X}let Q=$.body.getReader(),J=[],j=0;try{while(!0){let{done:X,value:Y}=await Q.read();if(X)break;let V=Buffer.from(Y);if(j+=V.byteLength,j>aQ)throw await Q.cancel().catch(()=>{return}),wX(W);J.push(V)}return Buffer.concat(J,j)}finally{Q.releaseLock()}}async function LI($,W){let Z=new AbortController,Q=setTimeout(()=>{Z.abort()},OD);try{let J=await fetch($.url,{signal:Z.signal});if(!J.ok){let X=J.statusText?` ${J.statusText}`:"";throw Error(`Failed to download plugin file from ${$.url}: ${J.status}${X}`)}let j=await fI(J,$.url);return PX(W,{recursive:!0}),await tQ(t(W,$.filename),j),W}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error(`Timed out downloading plugin file from ${$.url} after ${OD}ms`);throw J}finally{clearTimeout(Q)}}async function TI($,W,Z,Q){let J=a$(Z,$7($.path));if(!y1(J))throw Error(`Plugin source path does not exist: ${J}`);let j=SX(J);if(j.isFile()){if(!oQ(J))throw Error(`Plugin file must be .js or .ts: ${J}`);PX(W,{recursive:!0});let Y=t(W,F$(J));return await CX(J,Y),W}if(!j.isDirectory())throw Error(`Plugin source must be a file or directory: ${J}`);let X=t(W,eQ);return await CX(J,X,{recursive:!0,filter:(Y)=>{let V=F$(Y);return V!==".git"&&V!=="node_modules"}}),await bX(X,Q),X}function OI($,W){if(y1($)&&!W)throw Error(`Plugin is already installed at ${$}. Use --force to replace it.`)}function zI($,W,Z){if(PX(TD(W),{recursive:!0}),!y1(W)){nQ($,W);return}if(!Z)throw Error(`Plugin is already installed at ${W}. Use --force to replace it.`);let Q=t(TD(W),`.replace-${F$(W)}-${Date.now()}-${process.pid}-${Y8(`${W}:${Math.random()}`)}`);nQ(W,Q);try{nQ($,W)}catch(J){if(!y1(W)&&y1(Q))nQ(Q,W);throw J}try{sQ(Q,{recursive:!0,force:!0})}catch{}}function qI($){let W=$.transport;if(W.type==="stdio")return!1;return W.headers!==void 0&&Object.keys(W.headers).length>0}function MI($){let W=$.oauth?.tokens?.access_token;return typeof W==="string"&&W.trim().length>0}function RI($){let W=$.metadata;if(!W||W.source!=="plugin"||typeof W.pluginName!=="string"||typeof W.pluginPath!=="string")return;return{pluginName:W.pluginName,pluginPath:W.pluginPath}}function Q7($){let W=new Set($.pluginPaths.map((J)=>a$(J)));if(W.size===0)return[];let Z;try{Z=t0({filePath:$.settingsPath??J0()})}catch{return[]}let Q=[];for(let J of Z){let j=RI(J);if(!j||!W.has(a$(j.pluginPath)))continue;let X=J.transport.type;if(X==="stdio")continue;if(qI(J)||MI(J))continue;Q.push({name:J.name,pluginName:j.pluginName,pluginPath:j.pluginPath,transportType:X,lastError:J.oauth?.lastError})}return Q.sort((J,j)=>J.name.localeCompare(j.name))}async function yX($){let W=$.source.trim(),Z=Z7(W,$.sourceType),Q=$.cwd?.trim(),J=Q?a$(Q):process.cwd(),j=jI(Q?J:void 0),X=ek($.officialPluginsRepo),Y=YI(Z,J,X),V=XI(j,Z,Y),B=VI(Z,J),H=t(j,r6,".tmp"),G=t(H,`${Date.now()}-${process.pid}-${Y8(`${W}:${Math.random()}`)}`),K=$.npmCommand??(process.env.CLINE_NPM_COMMAND?.trim()||"npm"),F=$.force===!0;OI(V,F),await ED(H,{recursive:!0});let A;try{if(Z.type==="npm")A=await AI(Z,G,K);else if(Z.type==="git")A=await UI(Z,G,K);else if(Z.type==="official")A=await DI(Z,G,K,X);else if(Z.type==="remote")A=await LI(Z,G);else A=await TI(Z,G,J,K);let D=(Z.type==="local"||Z.type==="remote")&&A===G?PD(G).map((_)=>`./${wD(ND(G,_))}`):await FI(G,A,B);if(D.length===0)throw Error(`No plugin entry files found for ${W}`);zI(G,V,F);let U={source:W,installPath:V,entryPaths:D.map((_)=>a$(V,_)),mcpSyncFailures:[],mcpOAuthCandidates:[]},f=await f9({pluginPaths:U.entryPaths,cwd:J,workspacePath:J});return U.mcpSyncFailures=f.failures,U.mcpOAuthCandidates=Q7({pluginPaths:U.entryPaths}),U}catch(D){throw sQ(G,{recursive:!0,force:!0}),D}}var uD={};w(uD,{writeModelsFileSync:()=>w9,writeModelsFile:()=>C9,toProviderModel:()=>mX,syncStoredProviderRegistration:()=>vX,resolveModelsRegistryPath:()=>h1,registerProviderSettingsProvider:()=>cD,registerCustomProvider:()=>B8,registerConfiguredProvidersFromSettings:()=>P9,readModelsFileSync:()=>n6,readModelsFile:()=>V8,parseModelsFile:()=>gX,ensureCustomProvidersLoadedSync:()=>S9,ensureCustomProvidersLoaded:()=>b9,emptyModelsFile:()=>N9,StoredProviderMetadataSchema:()=>hD,StoredProviderEntrySchema:()=>IX,StoredModelsFileSchema:()=>xX,StoredModelEntrySchema:()=>yD});import{existsSync as EI,mkdirSync as NI,readFileSync as wI,renameSync as CI,rmSync as PI,writeFileSync as SI}from"node:fs";import{mkdir as bI,readFile as yI,rename as hI,rm as kI,writeFile as II}from"node:fs/promises";import{dirname as kX,join as xI}from"node:path";import*as A0 from"@cline/llms";import{ApiFormatSchema as gI,ModelCapabilitySchema as mI,ProviderCapabilitySchema as vI,ProviderClientSchema as cI,ProviderProtocolSchema as uI}from"@cline/shared";import{z as e}from"zod";var hX=e.number().finite().positive().optional().catch(void 0),E9=e.number().finite().nonnegative().optional().catch(void 0),yD=e.object({id:e.string().optional(),name:e.string().optional(),maxTokens:hX,contextWindow:hX,maxInputTokens:hX,capabilities:e.array(mI).optional(),supportsVision:e.boolean().optional(),supportsAttachments:e.boolean().optional(),supportsReasoning:e.boolean().optional(),inputPrice:E9,outputPrice:E9,cacheReadsPrice:E9,cacheWritesPrice:E9,temperature:E9,apiFormat:gI.optional(),isR1FormatRequired:e.boolean().optional()}).passthrough(),hD=e.object({name:e.string(),baseUrl:e.string(),defaultModelId:e.string().optional(),protocol:uI.optional(),client:cI.optional(),capabilities:e.array(vI).optional(),modelsSourceUrl:e.string().optional()}).passthrough(),IX=e.object({provider:hD.optional(),models:e.record(e.string(),yD).optional()}).passthrough(),xX=e.object({version:e.literal(1),providers:e.record(e.string(),IX)}),dI=e.object({version:e.literal(1),providers:e.record(e.string(),e.unknown())}),J7=new Set;function kD($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function h1($){return xI(kX($.getFilePath()),"models.json")}function N9(){return{version:1,providers:{}}}function gX($){let W=dI.safeParse($);if(!W.success)return s("models.json content is not a valid models file envelope; starting from an empty registry"),N9();let Z={};for(let[Q,J]of Object.entries(W.data.providers)){let j=IX.safeParse(J);if(j.success)Z[Q]=j.data;else s(`models.json: dropping invalid entry for provider=${Q}`)}return{version:1,providers:Z}}function n6($){if(!EI($))return N9();try{let W=wI($,"utf8");return gX(JSON.parse(W))}catch{s(`models.json at ${$} exists but is unreadable or invalid JSON; treating as an empty registry`)}return N9()}async function V8($){try{let W=await yI($,"utf8");return gX(JSON.parse(W))}catch(W){if(W?.code!=="ENOENT")s(`models.json at ${$} exists but is unreadable or invalid JSON; treating as an empty registry`)}return N9()}function w9($,W){NI(kX($),{recursive:!0});let Z=xX.parse(W),Q=`${$}.${process.pid}.tmp`;try{SI(Q,`${JSON.stringify(Z,null,2)}
736
- `,"utf8"),CI(Q,$)}catch(J){throw PI(Q,{force:!0}),J}}async function C9($,W){await bI(kX($),{recursive:!0});let Z=xX.parse(W),Q=`${$}.${process.pid}.tmp`;try{await II(Q,`${JSON.stringify(Z,null,2)}
737
- `,"utf8"),await hI(Q,$)}catch(J){throw await kI(Q,{force:!0}).catch(()=>{}),J}}function mX($,W){return{id:$,name:W.name??$,supportsAttachments:W.capabilities?.includes("files"),supportsVision:W.capabilities?.includes("images"),supportsReasoning:W.capabilities?.includes("reasoning")||W.thinkingConfig!=null}}function ID($){if(!$||$.length===0)return;let W=new Set;if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("tools"))W.add("tools");return W.size>0?[...W]:void 0}function xD($){let W=new Set;if(!$||$.length===0)return[...W];if($.includes("streaming"))W.add("streaming");if($.includes("tools"))W.add("tools");if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("vision"))W.add("images"),W.add("files");return[...W]}function lI($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function gD($,W){return $??W??"openai-chat"}function mD($,W,Z){return $??Z??(W==="openai-responses"?"openai":"openai-compatible")}function vD($,W,Z){let Q=new Set(W?.capabilities??Z??[]);if(W?.supportsVision!==void 0)if(W.supportsVision)Q.add("images");else Q.delete("images");if(W?.supportsAttachments!==void 0)if(W.supportsAttachments)Q.add("files");else Q.delete("files");if(W?.supportsReasoning!==void 0)if(W.supportsReasoning)Q.add("reasoning");else Q.delete("reasoning");let J=W?.isR1FormatRequired?"r1":W?.apiFormat,j=W?.inputPrice!==void 0||W?.outputPrice!==void 0||W?.cacheReadsPrice!==void 0||W?.cacheWritesPrice!==void 0;return{id:$,name:W?.name??$,...W?.maxTokens!==void 0?{maxTokens:W.maxTokens}:{},...W?.contextWindow!==void 0?{contextWindow:W.contextWindow}:{},...W?.maxInputTokens!==void 0?{maxInputTokens:W.maxInputTokens}:{},...Q.size>0?{capabilities:[...Q]}:{},...W?.temperature!==void 0?{temperature:W.temperature}:{},...J!==void 0?{apiFormat:J}:{},...j?{pricing:{...W?.inputPrice!==void 0?{input:W.inputPrice}:{},...W?.outputPrice!==void 0?{output:W.outputPrice}:{},...W?.cacheReadsPrice!==void 0?{cacheRead:W.cacheReadsPrice}:{},...W?.cacheWritesPrice!==void 0?{cacheWrite:W.cacheWritesPrice}:{}}}:{}}}function pI($,W){for(let[Z,Q]of Object.entries(W??{})){let J=Q.id?.trim()||Z.trim();if(!J)continue;A0.registerModel($,J,vD(J,Q))}}function rI($,W,Z){return{...W??{},id:$,name:W?.name??$,capabilities:W?.capabilities??Z}}function iI($){return Object.assign({},...A0.resolveProviderModelCatalogKeys($).map((Z)=>A0.getGeneratedModelsForProvider(Z)))}function cD($){let W=$.provider.trim();if(!W||A0.isBuiltInProviderId(W))return;let Z=$.baseUrl?.trim();if(!Z)return;let Q=A0.MODEL_COLLECTIONS_BY_PROVIDER_ID[W],J=iI(W),j=xD($.capabilities),X=j.length>0?j:void 0,Y=$.model?.trim(),V={...J,...Q?.models??{}};if(Y)V[Y]=rI(Y,V[Y],X);let B=Object.keys(V).filter(Boolean),H=Y||B[0];if(!H)return;let G=gD($.protocol,Q?.provider.protocol),K=mD($.client,G,Q?.provider.client);A0.registerProvider({provider:{id:W,name:Q?.provider.name??kD(W),description:Q?.provider.description,protocol:G,client:K,baseUrl:Z,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:H,capabilities:ID($.capabilities)??Q?.provider.capabilities,source:"file"},models:V})}function P9($){for(let W of Object.values($.providers))cD(W.settings)}function B8($,W){let Z=W.models??{};if(!lI(W.provider)){pI($,Z);return}let Q=xD(W.provider.capabilities),J=Object.entries(Z).map(([B,H])=>({id:H.id?.trim()||B.trim(),model:H})).filter(({id:B})=>B.length>0),j=W.provider.defaultModelId?.trim()||J[0]?.id||"default",X=gD(W.provider.protocol,void 0),Y=mD(W.provider.client,X,void 0),V=Object.fromEntries(J.map(({id:B,model:H})=>[B,{...vD(B,H,Q.length>0?Q:void 0),status:"active"}]));A0.registerProvider({provider:{id:$,name:W.provider.name.trim()||kD($),protocol:X,client:Y,baseUrl:W.provider.baseUrl,modelsSourceUrl:W.provider.modelsSourceUrl,defaultModelId:j,capabilities:ID(W.provider.capabilities),source:"file"},models:V})}function vX($,W,Z){let Q=Z?.models??{},J=new Set;for(let[Y,V]of Object.entries(W?.models??{})){if(Object.hasOwn(Q,Y))continue;let B=V.id?.trim()||Y.trim();if(B)J.add(B),A0.unregisterModel($,B)}if(!Z)return;let j=A0.getProviderCollectionSync($);B8($,Z);let X=A0.getProviderCollectionSync($);if(j&&X&&X!==j){let Y=Object.fromEntries(Object.entries(j.models).filter(([V])=>!J.has(V)));A0.registerProvider({...X,models:{...Y,...X.models}})}}function S9($){let W=h1($);if(J7.has(W))return;let Z=n6(W);for(let[Q,J]of Object.entries(Z.providers))B8(Q,J);J7.add(W)}async function b9($){let W=h1($);if(J7.has(W))return;let Z=await V8(W);for(let[Q,J]of Object.entries(Z.providers))B8(Q,J);J7.add(W)}var sD={};w(sD,{updateLocalProvider:()=>Y7,saveLocalProviderSettings:()=>iX,saveLocalProviderOAuthCredentials:()=>sX,resolveLocalClineAuthToken:()=>eX,refreshProviderModelsFromSource:()=>nX,normalizeOAuthProvider:()=>aX,markLocalProviderEnabled:()=>lX,loginLocalProvider:()=>oX,loginAndSaveLocalProviderOAuthCredentials:()=>tX,listLocalProviders:()=>pX,getLocalProviderModels:()=>rX,ensureCustomProvidersLoaded:()=>b9,deleteLocalProvider:()=>V7,addLocalProvider:()=>dX});import*as k0 from"@cline/llms";var lD="cline-pass";function nI($){return $.apiKey??$.auth?.apiKey}function aI($){return($.auth?.accessToken?.trim()??"").length>0}function pD($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function oI($){let W=$.split(/\s+/).filter(Boolean);if(W.length===0)return"?";if(W.length===1)return W[0].slice(0,2).toUpperCase();return`${W[0][0]}${W[1][0]}`.toUpperCase()}function sI($){let W=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Z=0;for(let Q of $)Z=Z*31+Q.charCodeAt(0)>>>0;return W[Z%W.length]}function rD($){return Object.entries($).sort(([W],[Z])=>W.localeCompare(Z)).map(([W,Z])=>mX(W,Z))}async function tI($,W){let Z=await k0.getModelsForProvider($),Q=$===lD;if(!W&&!Q)return Z;let J=await R5($,{loadLatestOnInit:Q,loadPrivateOnAuth:!0,failOnError:!1},W);if($==="litellm"&&J?.knownModels)return J.knownModels;if(Q&&J?.knownModels)return J.knownModels;return J?.knownModels?{...Z,...J.knownModels}:Z}function cX($){return[...new Set(($??[]).map((W)=>W.trim()).filter(Boolean))]}function eI($){if(!$?.length)return;return[...new Set($)]}function $x($,W){return eI([...$??[],...W??[]])}function Wx($){let W=$?.popularRank;return typeof W==="number"&&Number.isFinite(W)?W:Number.MAX_SAFE_INTEGER}function Zx($){if(!$||typeof $!=="object")return!1;let W=$;return typeof W.path==="string"&&W.path.trim().length>0&&typeof W.label==="string"&&W.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(W.type))}function Qx($){let W=$?.configFields;if(!Array.isArray(W))return;return W.filter(Zx)}var j7={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},dD={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function Jx($){if(!$)return[j7];if($.source!=="system")return $.baseUrl?[j7,dD]:[j7];let W=[];if($.env?.length)W.push(j7);if($.baseUrl)W.push(dD);return W}function jx($,W){return W.split(".").reduce((Z,Q)=>{if(!Z||typeof Z!=="object")return;return Z[Q]},$)}function Xx($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function Yx($,W,Z){if(!$?.length)return;let Q={};for(let J of $){let X=Xx(J.path==="baseUrl"&&W?.baseUrl===void 0?Z?.baseUrl:jx(W,J.path))??J.defaultValue;if(X!==void 0)Q[J.path]=X}return Q}function iD($){let W=Object.entries($??{}).filter(([Z])=>Z.trim().length>0);return W.length>0?Object.fromEntries(W):void 0}function uX($,W){let Z=W?.includes("vision")??!1,Q=W?.includes("reasoning")??!1;return Object.fromEntries($.map((J)=>[J,{id:J,name:J,supportsVision:Z,supportsAttachments:Z,supportsReasoning:Q}]))}async function nD($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let W=$.modelsSourceUrl?await NZ($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...W])]}function aD($,W){let Z=$.read(),Q=!1;if(Z.providers[W])delete Z.providers[W],Q=!0;if(Z.lastUsedProvider===W)delete Z.lastUsedProvider,Q=!0;if(Q)$.write(Z);k0.unregisterProvider(W)}async function dX($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=W.baseUrl.trim(),J=W.apiKey?.trim()??"";if(!Q&&!J){let A=h1($);if((await V8(A)).providers[Z]){let U=await V7($,{providerId:Z});return{providerId:Z,settingsPath:U.settingsPath,modelsPath:U.modelsPath,modelsCount:0}}return aD($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:0}}if(k0.hasProvider(Z))throw Error(`provider "${Z}" already exists`);let j=W.name.trim();if(!j)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let X=cX(W.models),Y=W.modelsSourceUrl?.trim(),V=await nD({providerId:Z,explicitModels:X,modelsSourceUrl:Y,shouldRecompute:!0});if(V.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let B=W.defaultModelId?.trim()&&V.includes(W.defaultModelId.trim())?W.defaultModelId.trim():V[0],H=W.capabilities?.length?[...new Set(W.capabilities)]:void 0,G=iD(W.headers);$.saveProviderSettings({provider:Z,apiKey:J||void 0,baseUrl:Q,headers:G,timeout:W.timeoutMs,model:B,protocol:W.protocol,client:W.client},{setLastUsed:!1});let K=h1($),F=await V8(K);return F.providers[Z]={provider:{name:j,baseUrl:Q,defaultModelId:B,protocol:W.protocol,client:W.client,capabilities:H,modelsSourceUrl:Y},models:uX(V,H)},await C9(K,F),B8(Z,F.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:K,modelsCount:V.length}}async function Y7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=h1($),J=await V8(Q),j=J.providers[Z];if(!j){let O=$.getProviderSettings(Z);if(!O)throw Error(`provider "${Z}" does not exist`);let T=W.modelsSourceUrl?.trim(),L=cX(W.models)[0]??O.model?.trim();if(!L&&!T)throw Error(`provider "${Z}" cannot be updated because no model is configured`);j={provider:{name:W.name?.trim()||pD(Z),baseUrl:W.baseUrl?.trim()??O.baseUrl?.trim()??"",defaultModelId:L,protocol:O.protocol,client:O.client,capabilities:O.capabilities},models:L?uX([L],O.capabilities):{}}}if(!j.provider)throw Error(`provider "${Z}" cannot be updated because it is a model overlay (no provider metadata)`);let X=W.name?.trim()??j.provider.name.trim();if(!X)throw Error("name is required");let Y=W.baseUrl?.trim()??j.provider.baseUrl.trim();if(!Y)throw Error("baseUrl is required");let V=W.capabilities===void 0?j.provider.capabilities:W.capabilities===null?void 0:[...new Set(W.capabilities)],B=W.protocol===void 0?j.provider.protocol:W.protocol??void 0,H=W.client===void 0?j.provider.client:W.client??void 0,G=cX(W.models),K=W.modelsSourceUrl===void 0?j.provider.modelsSourceUrl:W.modelsSourceUrl?.trim()||void 0,F=W.models!==void 0||W.modelsSourceUrl!==void 0&&!!K,A=Object.keys(j.models??{}).map((O)=>O.trim()).filter(Boolean),D=await nD({providerId:Z,explicitModels:G,modelsSourceUrl:K,fallbackModelIds:A,shouldRecompute:F});if(D.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let U=W.defaultModelId===void 0?j.provider.defaultModelId?.trim():W.defaultModelId?.trim(),f=U&&D.includes(U)?U:D[0],R={...$.getProviderSettings(Z)??{},provider:Z,baseUrl:Y,model:f};if(B)R.protocol=B;else delete R.protocol;if(H)R.client=H;else delete R.client;if(W.apiKey!==void 0){let O=W.apiKey?.trim()??"";if(O)R.apiKey=O;else delete R.apiKey}if(W.headers!==void 0){let O=iD(W.headers);if(O)R.headers=O;else delete R.headers}if(W.timeoutMs!==void 0)if(typeof W.timeoutMs==="number")R.timeout=W.timeoutMs;else delete R.timeout;return $.saveProviderSettings(R,{setLastUsed:!1}),J.providers[Z]={provider:{name:X,baseUrl:Y,defaultModelId:f,protocol:B,client:H,capabilities:V,modelsSourceUrl:K},models:uX(D,V)},await C9(Q,J),B8(Z,J.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q,modelsCount:D.length}}async function V7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=h1($),J=await V8(Q);if(!J.providers[Z])throw Error(`provider "${Z}" does not exist`);return delete J.providers[Z],await C9(Q,J),k0.unregisterProvider(Z),aD($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q}}function lX($,W,Z={}){let Q=W.trim();if(!Q)throw Error("providerId is required");let J=$.read().providers[Q]?.settings;return $.saveProviderSettings({...J??{},provider:Q},{setLastUsed:!1,tokenSource:Z.tokenSource}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function pX($,W={}){let Z=$.read(),Q=k0.getProviderIds(),J=await Promise.all(Q.map(async(X)=>{let[Y,V]=await Promise.all([k0.getProvider(X),k0.getModelsForProvider(X)]),B=rD(V),H=Z.providers[X]?.settings,G=$.getProviderSettings(X),K=Y?.name??pD(X),F=$x(Y?.capabilities,G?.capabilities),A=Qx(Y?.metadata)??Jx(Y);return{provider:{id:X,name:K,models:B.length,color:sI(X),letter:oI(K),enabled:Boolean(H),apiKey:G?nI(G):void 0,oauthAccessTokenPresent:G?aI(G):void 0,baseUrl:G?.baseUrl??Y?.baseUrl,defaultModelId:Y?.defaultModelId,protocol:G?.protocol??Y?.protocol,client:G?.client??Y?.client,capabilities:F,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:A,configValues:Yx(A,G,Y),modelList:B},rank:Wx(Y?.metadata)}}));J.sort((X,Y)=>{if(X.rank!==Y.rank)return X.rank-Y.rank;return X.provider.name.localeCompare(Y.provider.name)||X.provider.id.localeCompare(Y.provider.id)});let j=J.map((X)=>X.provider);if(W.isClinePassEnabled!==!0)j=j.filter((X)=>X.id!==lD);return{providers:j,settingsPath:$.getFilePath()}}async function rX($,W){let Z=$.trim(),Q=await tI(Z,W),J=rD(Q);return{providerId:Z,models:J}}function X7($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function oD($,W){if(!X7(W))return X7($)?{...$}:void 0;let Z=X7($)?{...$}:{};for(let[Q,J]of Object.entries(W)){if(J==null||J===""){delete Z[Q];continue}if(X7(J)){let j=oD(Z[Q],J);if(j&&Object.keys(j).length>0)Z[Q]=j;else delete Z[Q];continue}Z[Q]=J}return Object.keys(Z).length>0?Z:void 0}function iX($,W){let Z=W.providerId.trim();if(W.enabled===!1){let j=$.read();if(delete j.providers[Z],j.lastUsedProvider===Z)delete j.lastUsedProvider;return $.write(j),{providerId:Z,enabled:!1,settingsPath:$.getFilePath()}}let J={...$.getProviderSettings(Z)??{},provider:Z};for(let j of["apiKey","baseUrl","model","region"])if(Object.hasOwn(W,j)&&typeof W[j]==="string")if(W[j].trim().length===0)delete J[j];else J[j]=W[j];for(let j of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(W,j))J[j]=W[j];for(let j of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(W,j)&&W[j]!=null){let X=oD(J[j],W[j]);if(X)J[j]=X;else delete J[j]}return $.saveProviderSettings(J,{setLastUsed:!1}),{providerId:Z,enabled:!0,settingsPath:$.getFilePath()}}async function nX($,W){let Z=W.trim(),Q=$.getProviderSettings(Z),j=k0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Z]?.provider,X=Q?.baseUrl?.trim()||j?.baseUrl?.trim(),Y=wZ(X,j?.baseUrl,j?.modelsSourceUrl);if(!Q||!j||!X||!Y)return{providerId:Z,refreshed:!1};let V=await Y7($,{providerId:Z,name:j.name,baseUrl:X,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:Y,protocol:Q.protocol??j.protocol??null,client:Q.client??j.client??null,capabilities:Q.capabilities??null});return{providerId:Z,refreshed:!0,modelsCount:V.modelsCount}}function aX($){let W=$.trim().toLowerCase(),Z=H0(W);if(Z)return Z.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function oX($,W,Z,Q){let J=H0($);if(!J)throw Error(`provider "${$}" does not support OAuth login`);let j=D6({onPrompt:async(X)=>X.defaultValue??"",openUrl:Z,onOpenUrlError:({error:X})=>{throw X instanceof Error?X:Error(String(X))}});return J.login({settings:W,callbacks:j,telemetry:Q})}function sX($,W,Z,Q,J){return F2({manager:$,providerId:W,settings:Z,credentials:Q,setLastUsed:J?.setLastUsed})}async function tX($,W,Z,Q){let J=D6({onPrompt:async(j)=>j.defaultValue??"",openUrl:Z,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return C4($,W,{callbacks:J,telemetry:Q})}function eX($){let W=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return W&&W.length>0?W:void 0}var tD={};w(tD,{getProviderConfigFields:()=>$Y});import*as B7 from"@cline/llms";var Vx=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],Bx={"openai-compatible":{description:"For Azure AI Foundry deployments, use a Base URL ending at /openai/deployments/<deployment> and set the Azure API version.",fields:{azureApiVersion:{label:"Azure API Version (optional)",placeholder:"2025-01-01-preview",note:"Required for Azure AI Foundry deployment URLs.",optional:!0}}},vertex:{mode:"replace",description:"Vertex AI can use Google Cloud Application Default Credentials with a project/region. An API key is optional for supported Gemini models.",fields:{gcpProjectId:{label:"Google Cloud Project ID",placeholder:"my-gcp-project"},gcpRegion:{label:"Google Cloud Region",placeholder:"us-central1",defaultValue:"us-central1"},apiKey:{label:"API Key (optional)",placeholder:"Leave blank to use Google Cloud credentials",optional:!0}}},bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}},sapaicore:{mode:"replace",description:"SAP AI Core uses OAuth client credentials and an AI Core API URL, not a generic API key.",fields:{baseUrl:{label:"AI Core Base URL",placeholder:"https://api.ai.<region>.aws.ml.hana.ondemand.com"},sapClientId:{label:"Client ID",placeholder:"sb-...|xsuaa_std!b..."},sapClientSecret:{label:"Client Secret",placeholder:"SAP AI Core client secret"},sapTokenUrl:{label:"Token URL",placeholder:"https://<subdomain>.authentication.sap.hana.ondemand.com"},sapResourceGroup:{label:"Resource Group",placeholder:"default",optional:!0},sapDeploymentId:{label:"Deployment ID",placeholder:"SAP AI Core deployment id",optional:!0}}}};function Hx($,W){let Z={};for(let Q of Vx){let J=$[Q],j=W[Q];if(J||j)Z[Q]={...J,...j}}return Z}function Gx($){let W=Bx[$.providerId];if(!W)return $;return{...$,description:W.description??$.description,fields:W.mode==="replace"?W.fields:Hx($.fields,W.fields)}}var Kx=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function Fx($,W){if(!W?.provider.baseUrl)return!1;if(W.provider.source!=="system")return!0;return Kx.has($)}function $Y($){let W=B7.normalizeProviderId($);if(K2(W))return{providerId:W,authMethod:"oauth",fields:{}};let Z=B7.MODEL_COLLECTIONS_BY_PROVIDER_ID[W];if(Z?.provider.capabilities?.includes("local-auth"))return{providerId:W,authMethod:"local",fields:{}};let Q=Z?.provider.baseUrl,J={apiKey:{}};if(Fx(W,Z))J.baseUrl={defaultValue:Q};return Gx({providerId:W,authMethod:"api-key",fields:J})}var Z_={};w(Z_,{resolveLegacyClineAuth:()=>QY,migrateLegacyProviderSettings:()=>y9});import{existsSync as Ax,readFileSync as Ux}from"node:fs";import{dirname as Dx,join as WY}from"node:path";import*as a6 from"@cline/llms";import{resolveClineDataDir as _x}from"@cline/shared/storage";var H7="openai",W_=a6.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,eD=128000;function QY($){let W=$?.trim();if(!W)return;try{let Z=JSON.parse(W);if(!Z)return;let Q=typeof Z.expiresAt==="number"&&Number.isFinite(Z.expiresAt)?Z.expiresAt<10000000000?Z.expiresAt*1000:Z.expiresAt:void 0;return{accessToken:Z.idToken,refreshToken:Z.refreshToken,expiresAt:Q,accountId:Z.userInfo?.id}}catch{return}}function b($){let W=$?.trim();return W?W:void 0}function fx($){return $==="credentials"?"iam":$}function $_($){if(!Ax($))return;try{let W=Ux($,"utf8"),Z=JSON.parse(W);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}function Lx($){let W=$.dataDir??_x(),Z=$.globalStatePath??WY(W,"globalState.json"),Q=$.secretsPath??WY(W,"secrets.json"),J=$_(Z),j=$_(Q);if(!J&&!j)return;return{globalState:J??{},secrets:j??{}}}function ZY($){if($===H7)return W_;return $}function Tx($,W,Z,Q){let J=Z==="plan"?"planMode":"actMode",j=W===Q?b(Z==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,Y={openrouter:`${J}OpenRouterModelId`,cline:`${J}ClineModelId`,openai:`${J}OpenAiModelId`,ollama:`${J}OllamaModelId`,lmstudio:`${J}LmStudioModelId`,litellm:`${J}LiteLlmModelId`,requesty:`${J}RequestyModelId`,together:`${J}TogetherModelId`,fireworks:`${J}FireworksModelId`,sapaicore:`${J}SapAiCoreModelId`,groq:`${J}GroqModelId`,baseten:`${J}BasetenModelId`,huggingface:`${J}HuggingFaceModelId`,"huawei-cloud-maas":`${J}HuaweiCloudMaasModelId`,oca:`${J}OcaModelId`,aihubmix:`${J}AihubmixModelId`,hicap:`${J}HicapModelId`,nousResearch:`${J}NousResearchModelId`,"vercel-ai-gateway":`${J}VercelAiGatewayModelId`}[W];return(Y?b(typeof $[Y]==="string"?$[Y]:void 0):void 0)??j}function Ox($,W,Z){let Q=Z==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,J=[...W==="oca"?[$.actModeOcaReasoningEffort,$.planModeOcaReasoningEffort]:[],...W==="gemini"?[$.geminiActModeThinkingLevel,$.geminiPlanModeThinkingLevel]:[],$.actModeReasoningEffort,$.planModeReasoningEffort].map(b).find(Boolean),j=J==="none"||J==="low"||J==="medium"||J==="high"||J==="xhigh"?J:void 0,X=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!j&&X===void 0)return;return{...j?{effort:j}:{},...X!==void 0?{budgetTokens:X}:{}}}function zx($){let W=$["openai-codex-oauth-credentials"];if(!W)return;try{let Z=JSON.parse(W),Q=b(Z.access_token),J=b(Z.refresh_token),j=b(Z.accountId);if(!Q&&!J&&!j)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...J?{refreshToken:J}:{},...j?{accountId:j}:{}}}}catch{return}}function qx($){let W=a6.getGeneratedModelsForProvider($),Q=a6.getProviderCollectionSync($)?.provider.defaultModelId;if(Q&&W[Q])return Q;return Object.keys(W)[0]??void 0}function Mx($,W,Z,Q){let J=ZY($),j=b(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),X=Tx(W,$,Q,j)??qx(J),Y=Ox(W,J,Q),V=typeof W.requestTimeoutMs==="number"&&Number.isInteger(W.requestTimeoutMs)&&W.requestTimeoutMs>0?W.requestTimeoutMs:void 0,B={anthropic:Z.apiKey,cline:Z.clineApiKey,openai:Z.openAiApiKey,"openai-native":Z.openAiNativeApiKey,openrouter:Z.openRouterApiKey,bedrock:Z.awsBedrockApiKey,gemini:Z.geminiApiKey,ollama:Z.ollamaApiKey,deepseek:Z.deepSeekApiKey,requesty:Z.requestyApiKey,together:Z.togetherApiKey,fireworks:Z.fireworksApiKey,qwen:Z.qwenApiKey,doubao:Z.doubaoApiKey,mistral:Z.mistralApiKey,litellm:Z.liteLlmApiKey,asksage:Z.asksageApiKey,xai:Z.xaiApiKey,moonshot:Z.moonshotApiKey,zai:Z.zaiApiKey,huggingface:Z.huggingFaceApiKey,nebius:Z.nebiusApiKey,sambanova:Z.sambanovaApiKey,cerebras:Z.cerebrasApiKey,groq:Z.groqApiKey,"huawei-cloud-maas":Z.huaweiCloudMaasApiKey,baseten:Z.basetenApiKey,"vercel-ai-gateway":Z.vercelAiGatewayApiKey,dify:Z.difyApiKey,minimax:Z.minimaxApiKey,hicap:Z.hicapApiKey,aihubmix:Z.aihubmixApiKey,nousResearch:Z.nousResearchApiKey,oca:Z.ocaApiKey},H={};if($==="openai-codex")Object.assign(H,zx(Z));if($==="cline")try{let f=b(Z["cline:clineAccountId"]);if(f)H.auth={...H.auth??{},...QY(f)}}catch{}if($===H7&&W.openAiHeaders)H.headers=W.openAiHeaders;if($==="bedrock"){let f=fx(W.awsAuthentication),_=f==="profile"||W.awsUseProfile===!0;H.aws={accessKey:b(Z.awsAccessKey),secretKey:b(Z.awsSecretKey),sessionToken:b(Z.awsSessionToken),region:b(W.awsRegion),authentication:f,profile:_?b(W.awsProfile):void 0,usePromptCache:W.awsBedrockUsePromptCache,useCrossRegionInference:W.awsUseCrossRegionInference,useGlobalInference:W.awsUseGlobalInference,endpoint:b(W.awsBedrockEndpoint),customModelBaseId:b(Q==="plan"?W.planModeAwsBedrockCustomModelBaseId:W.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")H.gcp={projectId:b(W.vertexProjectId),region:b(W.vertexRegion)};if($===H7&&(W.azureApiVersion||W.azureIdentity!==void 0))H.azure={apiVersion:b(W.azureApiVersion),useIdentity:W.azureIdentity};if($==="sapaicore"){let f=W.sapAiCoreUseOrchestrationMode??!0;H.sap={clientId:b(Z.sapAiCoreClientId),clientSecret:b(Z.sapAiCoreClientSecret),tokenUrl:b(W.sapAiCoreTokenUrl),resourceGroup:b(W.sapAiResourceGroup),deploymentId:f?void 0:b(Q==="plan"?W.planModeSapAiCoreDeploymentId:W.actModeSapAiCoreDeploymentId),useOrchestrationMode:f}}if($==="oca"){H.oca={mode:W.ocaMode};let f=b(Z.ocaRefreshToken);if(f)H.auth={...H.auth??{},refreshToken:f}}if($==="qwen")H.apiLine=W.qwenApiLine;if($==="moonshot")H.apiLine=W.moonshotApiLine;if($==="zai")H.apiLine=W.zaiApiLine;if($==="minimax")H.apiLine=W.minimaxApiLine;let G={anthropic:W.anthropicBaseUrl,openai:W.openAiBaseUrl,ollama:W.ollamaBaseUrl,lmstudio:W.lmStudioBaseUrl,litellm:W.liteLlmBaseUrl,gemini:W.geminiBaseUrl,requesty:W.requestyBaseUrl,asksage:W.asksageApiUrl,dify:W.difyBaseUrl,oca:W.ocaBaseUrl,aihubmix:W.aihubmixBaseUrl,sapaicore:W.sapAiCoreBaseUrl},K=b(B[$]),F=b(G[$]),A={provider:J,...K?{apiKey:K}:{},...X?{model:X}:{},...F?{baseUrl:F}:{},...Y?{reasoning:Y}:{},...V?{timeout:V}:{},...H},D=F6.safeParse(A);if(!D.success)return;return Object.keys(A).filter((f)=>f!=="provider").length>0?D.data:void 0}function Rx($,W){if($!==W_)return;if(!W.baseUrl||!W.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:W.baseUrl,defaultModelId:W.model},models:{[W.model]:{id:W.model,name:W.model,contextWindow:eD,maxInputTokens:eD,capabilities:["streaming","tools","images"]}}}}function Ex($,W){let Z=new Set;for(let J of[$.actModeApiProvider,$.planModeApiProvider]){let j=b(J);if(j)Z.add(j)}if(b(W.apiKey))Z.add("anthropic");if(b(W.openRouterApiKey))Z.add("openrouter");if(b(W.openAiApiKey))Z.add(H7);if(b(W.openAiNativeApiKey))Z.add("openai-native");if(b(W["openai-codex-oauth-credentials"]))Z.add("openai-codex");if(b(W.geminiApiKey))Z.add("gemini");if(b(W.ollamaApiKey))Z.add("ollama");if(b(W.awsAccessKey)||b(W.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||b($.awsProfile))Z.add("bedrock");if(b($.vertexProjectId)||b($.vertexRegion))Z.add("vertex");if(b(W.clineApiKey))Z.add("cline");let Q=QY(b(W["cline:clineAccountId"]));if(Q?.accessToken||Q?.refreshToken||Q?.accountId)Z.add("cline");if(b(W.ocaApiKey))Z.add("oca");if(b(W.sapAiCoreClientId)||b(W.sapAiCoreClientSecret)||b($.sapAiCoreTokenUrl)||b($.sapAiCoreBaseUrl)||b($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Z.add("sapaicore");return Z}function y9($){let W=$.providerSettingsManager.read(),Z=Lx($);if(!Z)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let{globalState:Q,secrets:J}=Z,j=Q.mode==="plan"?"plan":"act",X=Ex(Q,J),Y=v$();Y.providers={...W.providers},Y.lastUsedProvider=W.lastUsedProvider;let V=new Date().toISOString(),B=0,H=WY(Dx($.providerSettingsManager.getFilePath()),"models.json"),G=n6(H),K=0;for(let D of X){let U=ZY(D);if(Y.providers[U])continue;let f=Mx(D,Q,J,j);if(!f)continue;Y.providers[U]={settings:f,updatedAt:V,tokenSource:"migration"},B+=1;let _=Rx(U,f);if(_&&!G.providers[U])G.providers[U]=_,K+=1}if(B===0&&K===0)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let F=b(j==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),A=F?ZY(F):void 0;if(Y.lastUsedProvider=W.lastUsedProvider??(A&&Y.providers[A]?A:Object.keys(Y.providers)[0]),$.providerSettingsManager.write(Y),K>0)w9(H,G);return{migrated:B>0||K>0,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider}}bQ();R0();fW();var Q_={};w(Q_,{SessionVersioningService:()=>o$,SessionVersioningError:()=>c0});class c0 extends Error{code;constructor($,W){super(W);this.code=$;this.name="SessionVersioningError"}}function Nx($){let W=$.sessionId.trim();if(!W)throw new c0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new c0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new c0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new c0("invalid_restore","checkpointRunCount must be a positive integer");return W}class o${async restoreCheckpoint($){let W=$.restore?.messages!==!1,Z=$.restore?.workspace!==!1,Q=Nx({sessionId:$.sessionId,restoreMessages:W,restoreWorkspace:Z,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),J=await $.getSession(Q);if(!J)throw new c0("session_not_found",`Session ${Q} not found`);let j=W?await $.readMessages(Q):void 0;if(W&&j?.length===0)throw new c0("session_messages_not_found",`No messages found for session ${Q}`);let X=$X({session:J,messages:j,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:W});if(Z)await($.applyWorkspaceCheckpoint??WX)(X.cwd,X.checkpoint);let Y=N1({session:J,messages:j});if(!W)return{checkpoint:X.checkpoint,sourceSnapshot:Y};let V=tj(J,$.checkpointRunCount),B=$.restore?.omitCheckpointMessageFromSession?ej(j??[],$.checkpointRunCount):X.messages??[],H={sourceSession:J,sourceMessages:j,sourceSnapshot:Y,plan:X,restoredCheckpointMetadata:V,initialMessages:B,restoreMessages:W,restoreWorkspace:Z,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new c0("invalid_restore","start is required when restore.messages is true");let G=$.buildStartInput?await $.buildStartInput(H,$.start):$.start,K=await $.startSession(G),F=$.getStartedSessionId?.(K);if(F)await($.retainCheckpointRefs??uK)(X.cwd,F,V?.history??[]);let A=F&&$.readRestoredSession?await $.readRestoredSession(F):void 0;return{sessionId:F,startResult:K,messages:X.messages,checkpoint:X.checkpoint,sourceSnapshot:Y,...A?{restoredSnapshot:N1({session:A,messages:B})}:{}}}}var J_={};w(J_,{FileTeamPersistenceStore:()=>G7});import{appendFileSync as wx,existsSync as JY,mkdirSync as Cx,readFileSync as Px,renameSync as Sx,unlinkSync as bx,writeFileSync as yx}from"node:fs";import{join as jY}from"node:path";import{resolveTeamDataDir as hx}from"@cline/shared/storage";function kx($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class G7{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let W=kx($.teamName),Z=$.baseDir?.trim()||hx();this.dirPath=jY(Z,W),this.statePath=jY(this.dirPath,"state.json"),this.taskHistoryPath=jY(this.dirPath,"task-history.jsonl")}loadState(){if(!JY(this.statePath))return;try{let $=Px(this.statePath,"utf8"),W=JSON.parse($);if(W.version!==1||!W.teamState)return;for(let Z of W.teammates??[])this.teammateSpecs.set(Z.agentId,Z);return EU(W.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let W={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Z=`${this.statePath}.tmp`;yx(Z,`${JSON.stringify(W,null,2)}
738
- `,"utf8"),Sx(Z,this.statePath)}appendTaskHistory($){let W={};switch($.type){case"team_task_updated":W=$.task;break;case"team_message":W={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":W={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":W={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":W={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":W={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),wx(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:W})}
739
- `,"utf8")}ensureDir(){if(!JY(this.dirPath))Cx(this.dirPath,{recursive:!0})}hasPersistableState($){let W=$.exportState();if(this.teammateSpecs.size>0)return!0;if(W.members.some((Z)=>Z.role==="teammate"))return!0;return W.tasks.length>0||W.mailbox.length>0||W.missionLog.length>0}clearPersistedState(){if(JY(this.statePath))bx(this.statePath)}}var j_={};w(j_,{ChatViewStateSchema:()=>XY,ChatSummarySchema:()=>D7,ChatSessionStatusSchema:()=>F7,ChatSessionConfigSchema:()=>K7,ChatMessageSchema:()=>U7,ChatMessageRoleSchema:()=>A7});import{z as I}from"zod";var K7=I.object({workspaceRoot:I.string().min(1),cwd:I.string().optional(),provider:I.string().min(1),model:I.string().min(1),mode:I.enum(["act","plan"]).default("act"),apiKey:I.string(),systemPrompt:I.string().optional(),rules:I.string().optional(),maxIterations:I.number().int().positive().optional(),enableTools:I.boolean(),enableSpawn:I.boolean().optional(),enableTeams:I.boolean().optional(),autoApproveTools:I.boolean().optional(),missionStepInterval:I.number().int().positive().optional(),missionTimeIntervalMs:I.number().int().positive().optional()}),F7=I.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),A7=I.enum(["user","assistant","tool","system","status","error"]),U7=I.object({id:I.string().min(1),sessionId:I.string().nullable(),role:A7,content:I.string(),createdAt:I.number().int().nonnegative(),meta:I.object({stream:I.enum(["stdout","stderr"]).optional(),toolName:I.string().optional(),iteration:I.number().int().nonnegative().optional(),agentId:I.string().optional(),conversationId:I.string().optional(),hookEventName:I.string().optional(),inputTokens:I.number().int().nonnegative().optional(),outputTokens:I.number().int().nonnegative().optional(),checkpoint:I.object({ref:I.string(),createdAt:I.number().int().nonnegative(),runCount:I.number().int().positive(),kind:I.enum(["stash","commit"]).optional()}).optional()}).optional()}),D7=I.object({toolCalls:I.number().int().nonnegative(),tokensIn:I.number().int().nonnegative(),tokensOut:I.number().int().nonnegative()}),XY=I.object({sessionId:I.string().nullable(),status:F7,config:K7,messages:I.array(U7),rawTranscript:I.string(),error:I.string().nullable(),summary:D7});var X_={};w(X_,{CORE_BUILD_VERSION:()=>YY});var YY=R8;import{Agent as bg,createAgentRuntime as yg}from"@cline/agents";var Y_={};w(Y_,{fetchClineRecommendedModels:()=>BY,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>_7});import{getClineEnvironmentConfig as Ix}from"@cline/shared";var xx=5000,_7={recommended:[{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",description:"Most intelligent model for agents and coding",tags:["BEST"]},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",description:"Strong coding and agent performance",tags:["NEW"]},{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"1M context window, strong coding performance",tags:["NEW"]},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",description:"OpenAI's latest with strong coding abilities",tags:["NEW"]}],free:[{id:"kwaipilot/kat-coder-pro",name:"KwaiKAT Kat Coder Pro",description:"Advanced agentic coding model",tags:["FREE"]},{id:"arcee-ai/trinity-large-preview:free",name:"Arcee AI Trinity Large Preview",description:"Advanced large preview model",tags:["FREE"]}],clinePass:[]};function gx($){return{recommended:$.recommended.map((W)=>({...W,tags:[...W.tags]})),free:$.free.map((W)=>({...W,tags:[...W.tags]})),clinePass:$.clinePass.map((W)=>({...W,tags:[...W.tags]}))}}function VY($){if(!$||typeof $!=="object")return null;let W=$;if(typeof W.id!=="string"||W.id.length===0)return null;return{id:W.id,name:typeof W.name==="string"&&W.name.length>0?W.name:W.id,description:typeof W.description==="string"?W.description:"",tags:Array.isArray(W.tags)?W.tags.filter((Z)=>typeof Z==="string"):[]}}function mx($){if(!$||typeof $!=="object")return null;let W=$,Z=Array.isArray(W.recommended)?W.recommended:[],Q=Array.isArray(W.free)?W.free:[],J=Array.isArray(W.clinePass)?W.clinePass:[],j=Z.map(VY).filter((V)=>V!==null),X=Q.map(VY).filter((V)=>V!==null),Y=J.map(VY).filter((V)=>V!==null);if(j.length===0&&X.length===0&&Y.length===0)return null;return{recommended:j,free:X,clinePass:Y}}function vx($){let W=$.baseUrl?.trim();if(W)return W;let Z=Ix().apiBaseUrl;try{return($.providerSettingsManager??new k1).getProviderSettings("cline")?.baseUrl?.trim()||Z}catch{return Z}}async function cx($,W,Z){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await $(W,{signal:Q.signal})}finally{clearTimeout(J)}}async function BY($={}){try{let W=vx($),Z=$.fetchImpl??fetch,Q=await cx(Z,`${W}/api/v1/ai/cline/recommended-models`,$.timeoutMs??xx);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let J=await Q.json(),j=mx(J);if(j)return j}catch{}return gx(_7)}var V_={};w(V_,{loadLlmsConfigFromFile:()=>GY,defineLlmsConfig:()=>HY});import{readFile as ux}from"node:fs/promises";import dx from"node:path";function HY($){return $}async function GY($){let W=dx.resolve($),Z=await ux(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(J){let j=J instanceof Error?J.message:String(J);throw Error(`Failed to parse JSON config at "${W}": ${j}`)}return lx(Q,W)}function lx($,W){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${W}": expected an object.`);let Q=$.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${W}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${W}": "providers" cannot be empty.`);return $}var A_={};w(A_,{createLlmsSdk:()=>FY,DefaultLlmsSdk:()=>h9});import{BUILT_IN_PROVIDER_IDS as G_,createHandler as ix,createHandlerAsync as nx,getProviderCollection as ax,hasProvider as K_,registerAsyncHandler as ox,registerHandler as sx,registerModel as tx,registerProvider as F_}from"@cline/llms";function B_($){return $?{...$}:{}}function px($,W){if($)return $;if(!W)return;let Z=globalThis.process;if(!Z?.env)return;return Z.env[W]}function rx($,W){if(!W.length)throw Error(`Provider "${$}" must include at least one model.`)}function H_($){let W=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:W,defaultModel:$.collection.provider.defaultModelId,modelCount:W.length}}class KY{providers=new Map;register($){rx($.id,$.models);let W=$.defaultModel??$.models[0];if(!W)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(W))throw Error(`Default model "${W}" is not included in configured models for "${$.id}".`);let Z=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Z?.models??[],...$.models]),defaultModel:W,defaults:{...Z?.defaults??{},...B_($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:px($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...B_($.settings)}})}registerModel($,W){let Z=this.providers.get($);if(!Z){this.providers.set($,{id:$,models:new Set([W]),defaultModel:W,defaults:{}});return}Z.models.add(W)}createHandlerConfig($){let W=this.require($.providerId),Z=$.modelId??W.defaultModel;if(!W.models.has(Z))throw Error(`Model "${Z}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Z,...W.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,W){return this.providers.get($)?.models.has(W)??!1}require($){let W=this.providers.get($);if(!W)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return W}}class h9{configuredProviders=new KY;constructor($){this.applyConfig($)}createHandler($){return ix(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return nx(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(F_($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)sx($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)ox($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let W=$.exposeModels??Object.keys($.models),Z=$.defaultModel??W[0];if(!Z)throw Error(`Provider "${$.id}" must define a default model.`);F_({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Z,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:W,defaultModel:Z,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){tx($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...G_]}async getBuiltInProviders(){return(await Promise.all(G_.map((W)=>ax(W)))).filter((W)=>W!==void 0).map((W)=>H_({collection:W}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,W){return this.configuredProviders.hasModel($,W)}applyConfig($){for(let W of $.providers)this.configuredProviders.registerSelectionConfig(W);for(let W of $.models??[])this.registerModel(W);for(let W of $.customProviders??[])this.registerProvider(W);for(let W of this.configuredProviders.list()){let Z=K_(W.id),Q=this.configuredProviders.createHandlerConfig({providerId:W.id,modelId:W.defaultModel}).routingProviderId,J=typeof Q==="string"&&K_(Q);if(!Z&&!J)throw Error(`Provider "${W.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function FY($){return new h9($)}p7();async function ex(){return Promise.resolve().then(() => (bQ(),nU))}function vg(){return new Date().toISOString()}var cg="cline",ug="cline-pass";function dg($){if(z_($)!=="providers.json")return;let W=DY($);if(z_(W)!=="settings")return;return DY(W)}class k1{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??mg(),this.dataDir=$.dataDir??dg(this.filePath),this.dataDir||!$.filePath)y9({providerSettingsManager:this,dataDir:this.dataDir});if(S9(this),P9(this.read()),UY(this.filePath))try{O_(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!UY(this.filePath))return v$();try{let $=kg(this.filePath,"utf8"),W=JSON.parse($),Z=A6.safeParse(W);if(Z.success){P9(Z.data);let Q=Z.data.providers.cline?.settings?.auth;return s(`providers.read providers=[${Object.keys(Z.data.providers).join(",")}] lastUsed=${Z.data.lastUsedProvider??"none"} clineAuthPresent=${!!Q?.accessToken} clineAccessTokenHash=${N0(Q?.accessToken)} clineRefreshTokenHash=${N0(Q?.refreshToken)}`),Z.data}}catch{}return v$()}write($){let W=A6.parse($),Z=DY(this.filePath);if(!UY(Z))hg(Z,{recursive:!0,mode:448});let Q=`${this.filePath}.${process.pid}.tmp`;try{gg(Q,`${JSON.stringify(W,null,2)}
740
- `,{encoding:"utf8",mode:384}),Ig(Q,this.filePath)}catch(J){throw xg(Q,{force:!0}),J}try{O_(this.filePath,384)}catch{}P9(W)}saveProviderSettings($,W={}){let Z=F6.parse($),Q=this.read(),J=Z.provider,j=W.setLastUsed!==!1,X=Q.providers[J],Y=W.tokenSource??X?.tokenSource??"manual",V={...Q,providers:{...Q.providers,[J]:{settings:Z,updatedAt:vg(),tokenSource:Y}},lastUsedProvider:j?J:Q.lastUsedProvider};this.write(V);let B=Q.providers.cline?.settings?.auth,H=Z.provider==="cline"?Z.auth:V.providers.cline?.settings?.auth,G=!!B?.accessToken&&!H?.accessToken;return s(`providers.save providerId=${J} tokenSource=${Y} clineAuthWasPresent=${!!B?.accessToken} clineAuthIsPresent=${!!H?.accessToken} authDropped=${G}`),V}resolveProviderSettings($,W){let Z=$.providers[W]?.settings,J=H0(W)?.storageProviderId;if(!J||J===W)return Z;let j=$.providers[J]?.settings;if(!j)return Z;return F6.parse({...j.auth?{auth:j.auth}:{},...j.apiKey?{apiKey:j.apiKey}:{},...j.baseUrl?{baseUrl:j.baseUrl}:{},...Z??{},provider:W})}getProviderSettings($){let W=this.read();return this.resolveProviderSettings(W,$)}resolveLastUsedProviderId($,W){let Z=$.lastUsedProvider;if(Z===ug&&W.isClinePassEnabled===!1)return cg;return Z}getLastUsedProviderSettings($={}){let W=this.read(),Z=this.resolveLastUsedProviderId(W,$);if(!Z)return;return this.resolveProviderSettings(W,Z)}getProviderConfig($,W){let Z=this.getProviderSettings($);if(!Z)return;return s0(Z,W)}getLastUsedProviderConfig($={}){let W=this.getLastUsedProviderSettings($);if(!W)return;return s0(W,$)}async refreshCatalog(){try{await G6({})}catch{}}}R0();O8();function lg($,W){let Z=$?.expiresAt,Q=W?.expiresAt;return $?.accessToken===W?.accessToken&&$?.refreshToken===W?.refreshToken&&$?.accountId===W?.accountId&&Z===Q}class O7 extends Error{providerId;constructor($){super(`OAuth credentials for provider "${$}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=$}}class _Y{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new k1,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let W=H0($.providerId);if(!W)return null;return this.resolveWithSingleFlight(W.providerId,W.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,W,Z=!1){let Q=this.refreshInFlight.get(W);if(Q)return Q;let J=this.resolveProviderApiKeyInternal($,W,Z).catch((j)=>{throw j}).finally(()=>{this.refreshInFlight.delete(W)});return this.refreshInFlight.set(W,J),J}async resolveProviderApiKeyInternal($,W,Z){let Q=H0($);if(!Q)return null;let J=this.providerSettingsManager.getProviderSettings(W);if(!J)return s(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_settings`),null;let j=P4($,J);if(!j)return s(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_credentials`),null;s(`oauth.resolve.start providerId=${$} storageProviderId=${W} forceRefresh=${Z} accessTokenHash=${N0(j.access)} refreshTokenHash=${N0(j.refresh)}`);let X=await Q.refresh({settings:J,credentials:j,forceRefresh:Z,telemetry:this.telemetry});if(!X)throw s(`oauth.resolve providerId=${$} outcome=refresh_returned_null`),new O7($);let Y=F2({manager:this.providerSettingsManager,providerId:$,settings:J,credentials:X,setLastUsed:!1,save:!1}),V=!lg(J.auth,Y.auth);if(V)s(`oauth.resolve.refreshed providerId=${$} newAccessTokenHash=${N0(X.access)} newRefreshTokenHash=${N0(X.refresh)} savingToDisk=true`),this.providerSettingsManager.saveProviderSettings(Y,{setLastUsed:!1,tokenSource:"oauth"});else s(`oauth.resolve providerId=${$} outcome=not_refreshed`);return{apiKey:Q.getApiKey(Y)??X.access,accountId:X.accountId,refreshed:V}}}import{normalizeUserInput as pg}from"@cline/shared";import{nanoid as rg}from"nanoid";class q_{list($){return $?Q1($):[]}update($,W){if(!$)return{sessionId:W.sessionId,prompts:[],updated:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((V)=>V.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:Q1($),updated:!1};let J=$.pendingPrompts[Q];if(!J)return{sessionId:W.sessionId,prompts:Q1($),updated:!1};let j=W.prompt===void 0?J.prompt:pg(W.prompt).trim();if(!j)throw Error("prompt cannot be empty");let X=W.delivery??J.delivery,Y={...J,prompt:j,mode:W.mode??J.mode,delivery:X};return $.pendingPrompts.splice(Q,1),ig($,Y,Q,J.delivery),{sessionId:W.sessionId,prompts:Q1($),prompt:z7(Y),updated:!0}}delete($,W){if(!$)return{sessionId:W.sessionId,prompts:[],removed:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((j)=>j.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:Q1($),removed:!1};let[J]=$.pendingPrompts.splice(Q,1);return{sessionId:W.sessionId,prompts:Q1($),prompt:J?z7(J):void 0,removed:!0}}enqueue($,W){let{prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X}=W,Y=$.pendingPrompts.findIndex((V)=>V.prompt===Z);if(Y>=0){let[V]=$.pendingPrompts.splice(Y,1),B={...V,prompt:Z,mode:Q??V.mode,userImages:j??V.userImages,userFiles:X??V.userFiles};if(J==="steer"||V.delivery==="steer")$.pendingPrompts.unshift({...B,delivery:"steer"});else $.pendingPrompts.push(B)}else{let V={id:`pending_${Date.now()}_${rg(5)}`,prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X};if(J==="steer")$.pendingPrompts.unshift(V);else $.pendingPrompts.push(V)}return Q1($)}consumeSteer($){let W=$.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if(W<0)return{prompts:Q1($)};let[Z]=$.pendingPrompts.splice(W,1);return{entry:Z,prompts:Q1($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:Q1($)}}requeueFront($,W){return $.pendingPrompts.unshift(W),Q1($)}clear($){return $.pendingPrompts.length=0,[]}}class fY{deps;service=new q_;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Z=this.service.update(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}delete($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Z=this.service.delete(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}enqueue($,W){let Z=this.deps.getSession($);if(!Z||Z.aborting)return;this.service.enqueue(Z,W),this.emitPrompts(Z),this.scheduleDrain($,Z)}consumeSteer($){let W=this.deps.getSession($);if(!W)return;let{entry:Z}=this.service.consumeSteer(W);if(!Z)return;return this.emitPrompts(W),this.emitSubmitted(W,Z),Z}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:Q1($)}})}scheduleDrain($,W){if(W.pendingPrompts.length===0||W.aborting||W.drainingPendingPrompts||!W.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let W=this.deps.getSession($);if(!W)return;if(W.aborting||W.drainingPendingPrompts)return;if(!W.agent.canStartRun())return;let{entry:Z}=this.service.shiftNext(W);if(!Z)return;this.emitPrompts(W),this.emitSubmitted(W,Z),W.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:$,prompt:Z.prompt,...Z.mode?{mode:Z.mode}:{},userImages:Z.userImages,userFiles:Z.userFiles})}catch{Q=!1,this.service.requeueFront(W,Z),this.emitPrompts(W)}finally{if(W.drainingPendingPrompts=!1,Q&&W.pendingPrompts.length>0&&W.status!=="failed"&&W.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,W){let Z=z7(W);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}})}}function z7($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0),userImages:$.userImages,userFiles:$.userFiles}}function Q1($){return $.pendingPrompts.map(z7)}function ig($,W,Z,Q){if(W.delivery==="steer")$.pendingPrompts.unshift(W);else if(Q==="steer")$.pendingPrompts.push(W);else $.pendingPrompts.splice(Z,0,W)}R0();class TY{deps;constructor($){this.deps=$}dispatchAgentEvent($,W,Z){let Q=this.deps.getSession($),J={sessionId:$,config:W,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},j=TJ(Z),X=!!Q&&(!j.agentId||j.agentId===LY(Q.agent));OJ(J,Z,X?{isPrimaryAgentEvent:!0,agentId:LY(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,W){let Z=this.deps.getSession($);if(Z){if(xj(Z,W),W.type==="agent_event"){let Q={sessionId:$,config:Z.config,liveSession:Z,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};OJ(Q,W.event,{agentId:W.agentId,teamRole:"teammate",teamAgentId:W.agentId,isPrimaryAgentEvent:!1})}if(W.type==="teammate_spawned"){let Q=W$({agentId:W.teammate.runtimeAgentId??W.agentId,conversationId:W.teammate.conversationId,parentAgentId:W.teammate.parentAgentId,createdByAgentId:LY(Z.agent),teamId:Z.runtime.teamRuntime?.getTeamId(),teamName:Z.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:W.agentId});if(Q)T$(Z.config.telemetry,{ulid:$,modelId:W.teammate.modelId??Z.config.modelId,provider:Z.config.providerId,...Q})}}if(await gj($,W,this.deps.invokeBackendOptional),Z)mj(Z,$,W,this.deps.emit)}async handlePluginEvent($,W,Z){if(W.name==="plugin_log"){this.handlePluginLog($,W.payload);return}if(W.name==="automation_event"){let V=this.deps.getSession($)?.config.extensionContext?.automation??Z;if(!V)return;let B=W.payload&&typeof W.payload==="object"?W.payload:void 0;if(!B)return;await V.ingestEvent(B);return}if(W.name!=="steer_message"&&W.name!=="queue_message"&&W.name!=="pending_prompt")return;let Q=W.payload&&typeof W.payload==="object"?W.payload:void 0,J=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():$,j=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!j)return;let X=W.name==="steer_message"?"steer":W.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(J,{prompt:j,delivery:X})}handlePluginLog($,W,Z){let Q=this.deps.getSession($),J=Z??Q?.config.extensionContext?.logger??Q?.config.logger;if(!J||!W||typeof W!=="object")return;let j=W,X=typeof j.message==="string"?j.message:"";if(!X)return;let Y=j.metadata&&typeof j.metadata==="object"?{...j.metadata}:{};if(Y.sessionId??=$,typeof j.pluginName==="string"&&j.pluginName)Y.pluginName=j.pluginName;if(j.level==="debug"){J.debug(X,Y);return}if(j.level==="error"){if(J.error)J.error(X,Y);else J.log(X,{...Y,severity:"error"});return}J.log(X,Y)}}function LY($){return $.getAgentId()}function OY($){return{sessionId:$.sessionId,source:$.source,pid:process.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:Z$($.config),teamName:$.config.teamName?.trim()||void 0,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,parentSessionId:typeof $.sessionMetadata?.parentSessionId==="string"?$.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof $.sessionMetadata?.parentAgentId==="string"?$.sessionMetadata.parentAgentId:void 0,agentId:typeof $.sessionMetadata?.agentId==="string"?$.sessionMetadata.agentId:void 0,conversationId:typeof $.sessionMetadata?.conversationId==="string"?$.sessionMetadata.conversationId:void 0,isSubagent:typeof $.sessionMetadata?.isSubagent==="boolean"?$.sessionMetadata.isSubagent:!1,prompt:$.pendingPrompt,metadata:$.sessionMetadata,messagesPath:$.artifacts?.messagesPath,updatedAt:$.updatedAt??$.endedAt??$.startedAt}}function zY($,W){let Z=$[W];return typeof Z==="function"?Z:null}async function M_($,W,...Z){let Q=zY($,W);if(!Q)throw Error(`session service method not available: ${W}`);return Promise.resolve(Q.apply($,Z))}async function R_($,W,...Z){let Q=zY($,W);if(!Q)return;await Promise.resolve(Q.apply($,Z))}async function E_($,W,...Z){let Q=zY($,W);if(!Q)return;return await Promise.resolve(Q.apply($,Z))}X1();R0();function qY($,W,Z){return{onSubAgentEvent:(Q)=>$.onAgentEvent(Z,W,Q),onSubAgentStart:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:Z});let j=W$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)T$(W.telemetry,{ulid:Z,modelId:W.modelId,provider:W.providerId,...j});B4(W.telemetry,{event:"started",ulid:Z,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...j}),$.invokeBackendOptional("handleSubAgentStart",Z,Q)},onSubAgentEnd:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime,j=$.subAgentStarts.get(Q.subAgentId),X=j?Date.now()-j.startedAt:0,Y=Q.result?.text?Q.result.text.split(`
741
- `).length:0;B4(W.telemetry,{event:"ended",ulid:Z,durationMs:X,outputLines:Y,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...W$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Z,Q)}}}function MY($,W,Z,Q){let J=qY($,W,Z);return y$({configProvider:{getRuntimeConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,maxIterations:W.maxIterations,hooks:W.hooks,extensions:W.extensions,logger:W.logger,telemetry:W.telemetry},getConnectionConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let X=W.enableTools?y2({cwd:W.cwd,...a0[e1({mode:W.mode})],executors:Q}):[];if(W.enableSpawnAgent)X.push(MY($,W,Z,Q));return u1(X)},...J})}import{readFile as ng,stat as ag}from"node:fs/promises";var og=20480000;async function N_($){let W=await ag($);if(!W.isFile())throw Error("Path is not a file");if(W.size>og)throw Error("File is too large to read into context.");let Z=await ng($,"utf8");if(Z.includes("\x00"))throw Error("Cannot read binary file into context.");return Z}var w_=5000;function m9($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Jm($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=m9(W.inputTokens),Q=m9(W.outputTokens),J=m9(W.cacheReadTokens),j=m9(W.cacheWriteTokens),X=m9(W.totalCost);if(Z===void 0||Q===void 0||J===void 0||j===void 0||X===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:J,cacheWriteTokens:j,totalCost:X}}function jm($,W){return{inputTokens:Math.max($.inputTokens,W.inputTokens),outputTokens:Math.max($.outputTokens,W.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,W.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,W.cacheWriteTokens),totalCost:Math.max($.totalCost,W.totalCost)}}function C_($,W){if(!W)return!1;if($.source_message_count!==W.source_message_count)return $.source_message_count<W.source_message_count;return Date.parse($.updated_at)<Date.parse(W.updated_at)}class b1{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new Z9;sessions=new Map;manifestMutationQueues=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new o$;constructor($){let W=tg();if(W)Qm(W);let Z=x0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new d6,this.createAgentInstance=$.createAgent??((Q)=>new P$(Q)),this.defaultCapabilities=P0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new k1,this.oauthTokenManager=$.oauthTokenManager??new _Y({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Z),this.defaultFetch=$.fetch,this.pendingPromptsController=new fY({getSession:(Q)=>this.sessions.get(Q),emit:(Q)=>this.emit(Q),send:(Q)=>this.runTurn(Q)}),this.pendingPrompts={list:async(Q)=>this.pendingPromptsController.list(Q.sessionId),update:async(Q)=>this.pendingPromptsController.update(Q),delete:async(Q)=>this.pendingPromptsController.delete(Q)},this.eventBridge=new TY({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,J,j)=>{this.invoke("persistSessionMessages",Q,J,j)},enqueuePendingPrompt:(Q,J)=>this.pendingPromptsController.enqueue(Q,J),invokeBackendOptional:(Q,...J)=>this.invokeOptional(Q,...J)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let W=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!W?.apiKey)return $;return{...$,config:{...$.config,apiKey:W.apiKey}}}async startSession($){let W=$.source??F0.CLI,Z=X0(),Q=$.config.sessionId?.trim()??"",J=Q||$m(),j=await this.applyInitialOAuthCredentials($),X=j.initialMessages??[],Y=X.length>0?$6(X):z0(),V=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!V)throw Error("session service method not available: ensureSessionsDir");let B=RY(V,J),H=RY(B,`${J}.messages.json`),G=RY(B,`${J}.json`),K=Z$($.config),F=m0.parse({version:1,session_id:J,source:W,pid:process.pid,started_at:Z,status:"running",interactive:$.interactive===!0,provider:j.config.providerId,model:j.config.modelId,cwd:j.config.cwd,workspace_root:K,team_name:j.config.teamName,enable_tools:j.config.enableTools,enable_spawn:j.config.enableSpawnAgent,enable_teams:j.config.enableAgentTeams,prompt:j.prompt?.trim()||void 0,messages_path:H}),A,D;if(Q.length>0&&X.length>0&&!j.prompt?.trim()){let k=await this.invokeOptionalValue("readSessionManifest",J);if(k)F=k,A={manifestPath:G,messagesPath:k.messages_path||H,compactionPath:k.compaction_path,manifest:k},D=await this.invokeOptionalValue("readSessionCompactionState",J)}let f=await this.seedAggregateUsageFromArtifacts({initialUsage:Y,sessionDir:B,rootMessagesPath:A?.messagesPath??H,manifest:F});this.usageBySession.set(J,Y),this.aggregateUsageBySession.set(J,f);let _=P0(this.defaultCapabilities,$.capabilities),R=_?.toolExecutors??this.toolExecutors,O=$.localRuntime,T=O?.extensionContext?.logger??O?.logger,L=O?.extensionContext?.automation,C,E={getSession:(k)=>this.sessions.get(k),subAgentStarts:this.subAgentStarts,onAgentEvent:(k,W0,T0)=>this.eventBridge.dispatchAgentEvent(k,W0,T0),invokeBackendOptional:(k,...W0)=>this.invokeOptional(k,...W0)};C=await FF({input:j,localRuntime:$.localRuntime,sessionId:J,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:_,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(k)=>{if(k.name==="plugin_log"){this.eventBridge.handlePluginLog(J,k.payload,T);return}this.eventBridge.handlePluginEvent(J,k,L)},onTeamEvent:(k)=>{this.eventBridge.handleTeamEvent(J,k),C.config.onTeamEvent?.(k)},createSpawnTool:()=>MY(E,C.config,J,R),createSubAgentLifecycleCallbacks:(k)=>qY(E,k,J),readSessionMetadata:async()=>(await this.getSession(J))?.metadata,writeSessionMetadata:async(k)=>{await this.persistSessionMetadata(J,()=>k)}});let p=r9(j.sessionMetadata??A?.manifest.metadata,C.gitState);if(!A)F.metadata=p;let x=await this.runtimeBuilder.build(C.runtimeBuilderInput),P=C.config,r=C.providerConfig;if(x.teamRuntime&&!P.teamName?.trim())P.teamName=x.teamRuntime.getTeamName();let d=[...x.tools,...P.extraTools??[]],I1=x.extensions??C.extensions,$2=j.initialCompactionState,A$,I0=m4(P),U0=$2??D,D1=I0&&U0?{...U0,conversation_id:U0.conversation_id?.trim()||J}:void 0,K8=I0?v4({compact:I0,getState:()=>A$?.compactionState,saveState:async(k)=>{let W0=A$;if(!W0)return;let T0={...k,conversation_id:W0.sessionId};try{if(!(await this.persistActiveSessionCompactionState(W0,T0)).updated)P.logger?.debug?.("Skipped stale session compaction state",{sessionId:W0.sessionId,sourceMessageCount:T0.source_message_count})}catch(q0){P.logger?.error?.("Failed to persist session compaction state",{sessionId:W0.sessionId,error:q0}),s$(P.telemetry,{component:"core",operation:"session.persist_compaction_state",severity:"warn",handled:!0,error:q0,context:{sessionId:W0.sessionId,providerId:P.providerId,modelId:P.modelId}})}}}):void 0,V0={sessionId:J,providerId:r.providerId,modelId:r.modelId,apiKey:r.apiKey,baseUrl:r.baseUrl,headers:r.headers,knownModels:r.knownModels,providerConfig:r,thinking:P.thinking,reasoningEffort:P.reasoningEffort??r.reasoningEffort,thinkingBudgetTokens:P.thinkingBudgetTokens,maxTokensPerTurn:P.maxTokensPerTurn,temperature:P.temperature,systemPrompt:P.systemPrompt,maxIterations:P.maxIterations,execution:P.execution,prepareTurn:K8,tools:d,hooks:C.hooks,extensions:I1,hookErrorMode:P.hookErrorMode,initialMessages:C.effectiveInput.initialMessages,userFileContentLoader:N_,toolPolicies:C.toolPolicies,requestToolApproval:C.requestToolApproval?async(k)=>{let W0=C.requestToolApproval,T0=this.sessions.get(J);if(T0)await this.markTurnPending(T0);try{if(!W0)return{approved:!1,reason:"Tool approval callback is not configured."};return await W0(k)}finally{let q0=this.sessions.get(J);if(q0?.status==="pending")await this.markTurnRunning(q0)}}:void 0,telemetry:P.telemetry,onConsecutiveMistakeLimitReached:P.onConsecutiveMistakeLimitReached,completionPolicy:x.completionPolicy,consumePendingUserMessage:()=>{let k=this.pendingPromptsController.consumeSteer(J);return k?G9(k.prompt,k.mode??P.mode):void 0},logger:x.logger??P.logger,extensionContext:P.extensionContext,onEvent:(k)=>this.eventBridge.dispatchAgentEvent(J,P,k)};V0.hooks={...V0.hooks,onEvent:async(k)=>{if(await C.hooks?.onEvent?.(k),k.type!=="assistant-message")return;let W0=this.sessions.get(J);if(!W0)return;let T0=W0.agent.getMessages();try{await this.invoke("persistSessionMessages",J,T0,P.systemPrompt)}catch(q0){P.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:J,error:q0}),s$(P.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:q0,severity:"warn",handled:!0,context:{sessionId:J,providerId:P.providerId,modelId:P.modelId}})}}};let d0=this.createAgentInstance(V0);if(V0.onEvent)d0.subscribeEvents(V0.onEvent);x.registerLeadAgent?.(d0);let J1=W$({agentId:d0.getAgentId(),conversationId:d0.getConversationId(),teamId:x.teamRuntime?.getTeamId(),teamName:x.teamRuntime?.getTeamName(),teamRole:x.teamRuntime?"lead":void 0});if(UF(P,J,Q.length>0,K,J1),J1)T$(P.telemetry,{ulid:J,modelId:P.modelId,provider:P.providerId,...J1});if(x.teamRuntime)VW(P.telemetry,{ulid:J,teamId:x.teamRuntime.getTeamId(),teamName:x.teamRuntime.getTeamName(),leadAgentId:d0.getAgentId(),restoredFromPersistence:x.teamRestoredFromPersistence===!0});let y={sessionId:J,config:P,sessionMetadata:p,...A?{artifacts:A}:{},source:W,startedAt:A?.manifest.started_at??Z,updatedAt:A?.manifest.ended_at??A?.manifest.started_at??Z,pendingPrompt:F.prompt,runtime:x,agent:d0,started:!1,status:A?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:X,compactionState:D1,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:C.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(A$=y,y.compactionState&&!this.isCompactionStateForSession(y.sessionId,y.compactionState,y))y.config.logger?.log?.("Ignoring session compaction state for a different conversation",{severity:"warn",sessionId:y.sessionId,conversationId:y.compactionState.conversation_id}),y.compactionState=void 0;if(this.sessions.set(J,y),A)await this.refreshActiveSessionGitMetadata(y,C.gitState);if(this.emitStatus(J,"running"),X.length>0&&!A){if(await this.ensureSessionPersisted(y),await this.invoke("persistSessionMessages",y.sessionId,X,y.config.systemPrompt),y.compactionState){if(!(await this.persistActiveSessionCompactionState(y,y.compactionState)).updated)y.compactionState=void 0}if(!j.prompt?.trim())await this.updateStatus(y,"completed",0)}let j1;try{if(j.prompt?.trim())if(j1=await this.executeTurn(y,{prompt:j.prompt,userImages:j.userImages,userFiles:j.userFiles}),!y.interactive)await this.finalizeSingleRun(y,j1.finishReason);else await this.completeInteractiveTurn(y,j1.finishReason)}catch(k){if(y.interactive&&y.aborting)j1=await this.completeAbortedInteractiveTurn(y);else{s$(y.config.telemetry,{component:"core",operation:"session.start",error:k,severity:"error",handled:!1,context:{sessionId:y.sessionId,providerId:y.config.providerId,modelId:y.config.modelId}});try{await this.failSession(y)}catch(W0){y.config.logger?.error?.("Session failure cleanup threw",{sessionId:y.sessionId,error:W0})}throw k}}return{sessionId:J,manifest:F,manifestPath:G,messagesPath:H,result:j1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(W)=>this.getSession(W),readMessages:(W)=>this.readSessionMessages(W),buildStartInput:(W,Z)=>{let Q=W.restoredCheckpointMetadata?{...Z.sessionMetadata??{},checkpoint:W.restoredCheckpointMetadata}:Z.sessionMetadata;return{...Z,...Q?{sessionMetadata:Q}:{},initialMessages:W.initialMessages}},startSession:(W)=>this.startSession(W),getStartedSessionId:(W)=>W.sessionId,readRestoredSession:(W)=>this.getSession(W)})}async runTurn($){let W=this.getSessionOrThrow($.sessionId),Z=W.agent.canStartRun(),Q=$.delivery??(W.interactive&&!Z?"queue":void 0);if(W.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Q,userImages:$.userImages,userFiles:$.userFiles});return}try{let J=await this.executeTurn(W,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!W.interactive)await this.finalizeSingleRun(W,J.finishReason);else await this.completeInteractiveTurn(W,J.finishReason);if(J.finishReason==="error"||J.finishReason==="aborted")return J;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),J}catch(J){if(W.interactive&&W.aborting)return await this.completeAbortedInteractiveTurn(W);throw s$(W.config.telemetry,{component:"core",operation:"session.submit",error:J,severity:"error",handled:!1,context:{sessionId:W.sessionId,providerId:W.config.providerId,modelId:W.config.modelId}}),await this.failSession(W),J}}async getAccumulatedUsage($){let W=Ej(this.usageBySession.get($)),Z=Ej(this.aggregateUsageBySession.get($));return W||Z?{usage:W,aggregateUsage:Z}:void 0}async abort($,W){let Z=this.sessions.get($);if(!Z)return;Z.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Z.aborting=!0,this.pendingPromptsController.clearAborted(Z),Z.agent.abort(W)}async stopSession($){let W=this.sessions.get($);if(!W)return;if(W.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),W.interactive&&!K0(W.status)){await this.releaseSessionRuntime(W,"session_stop");return}if(W.interactive&&W.agent.canStartRun()){await this.shutdownSession(W,{status:this.resolveInteractiveStopStatus(W),exitCode:this.resolveInteractiveStopExitCode(W),shutdownReason:"session_stop",endReason:"stopped"});return}W.aborting=!0,W.agent.abort(Error("session_stop")),await this.shutdownSession(W,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let W=[...this.sessions.values()];if(W.length===0)return;await Promise.allSettled(W.map((Z)=>Z.interactive&&!K0(Z.status)?this.releaseSessionRuntime(Z,$):Z.interactive&&Z.agent.canStartRun()?this.shutdownSession(Z,{status:this.resolveInteractiveStopStatus(Z),exitCode:this.resolveInteractiveStopExitCode(Z),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Z,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let W=this.sessions.get($);if(W)return OY(W);let Z=$.trim();if(!Z)return;let Q=await this.getRow(Z);if(Q)return H5(Q);let J=await this.readManifest(Z);return J?LQ(J):void 0}async listSessions($=200){let Z=(await this.listRows($)).map(H5),Q=new Set(Z.map((J)=>J.sessionId));for(let J of this.sessions.values()){if(Q.has(J.sessionId))continue;Z.unshift(OY(J))}return Z.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let W=await this.invoke("deleteSession",$);if(W.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return W.deleted}async updateSession($,W){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:W.prompt,metadata:W.metadata,title:W.title}))?.updated===!0}}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=this.sessions.get(Z),J=Q?void 0:await this.getSession(Z);if(!(Q??J))return{updated:!1};if(Q){let Y=await this.readSessionMessages(Z),V=W.source_message_count>0&&Y.length>=W.source_message_count,B=V?Y:void 0;if(V){if(!await this.canPersistCompactionState(Z,W,Q,void 0,Y))return{updated:!1};Q.agent.restore(Y)}return await this.persistActiveSessionCompactionState(Q,W,B)}if(!await this.canPersistCompactionState(Z,W,void 0,J))return{updated:!1};let X=await this.invokeOptionalValue("readSessionCompactionState",Z);if(C_(W,X))return{updated:!1};return await this.invoke("persistSessionCompactionState",Z,W),{updated:!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=this.sessions.get(W);if(Z)for(;;){let Q=Z.compactionStateWriteQueue;if(!Q)return Z.compactionState;await Q.catch(()=>{return})}return await this.invokeOptionalValue("readSessionCompactionState",W)}isCompactionStateForSession($,W,Z,Q){let J=W.conversation_id?.trim();if(!J)return!0;if(J===$)return!0;let j=Z?.agent.getConversationId()?.trim()||Q?.conversationId?.trim();return j?J===j:!1}async canPersistCompactionState($,W,Z,Q,J){if(!W.conversation_id?.trim())return!1;if(!this.isCompactionStateForSession($,W,Z,Q))return!1;let j=J??Z?.agent.getMessages()??await this.readSessionMessages($);return A2(W,j)!==void 0}async persistActiveSessionCompactionState($,W,Z){if(!await this.canPersistCompactionState($.sessionId,W,$,void 0,Z))return{updated:!1};return await this.enqueueCompactionStateWrite($,async()=>{if(C_(W,$.compactionState))return{updated:!1};return await this.invoke("persistSessionCompactionState",$.sessionId,W),$.compactionState=W,{updated:!0}})}async enqueueCompactionStateWrite($,W){let Q=($.compactionStateWriteQueue??Promise.resolve()).catch(()=>{return}).then(W),J=Q.then(()=>{return},()=>{return});$.compactionStateWriteQueue=J;try{return await Q}finally{if($.compactionStateWriteQueue===J)$.compactionStateWriteQueue=void 0}}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.getRow(W);if(Z?.messagesPath)return p$(Z.messagesPath);let Q=await this.readManifest(W);return p$(Q?.messages_path)}async dispatchHookEvent($){await kA($,{queueSpawnRequest:(W)=>this.invokeOptional("queueSpawnRequest",W),upsertSubagentSessionFromHook:(W)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",W),appendSubagentHookAudit:(W,Z)=>this.invokeOptional("appendSubagentHookAudit",W,Z),applySubagentStatus:(W,Z)=>this.invokeOptional("applySubagentStatus",W,Z)})}subscribe($,W){return this.events.subscribe($,W)}async updateSessionModel($,W){await this.updateSessionConnection($,{modelId:W})}async updateSessionConnection($,W){let Z=w2(W),Q=this.getSessionOrThrow($);if(Z.providerId!==void 0)Q.config.providerId=Z.providerId;if(Z.modelId!==void 0)Q.config.modelId=Z.modelId;if(Z.apiKey!==void 0)Q.config.apiKey=Z.apiKey;if(Z.baseUrl!==void 0)Q.config.baseUrl=Z.baseUrl;if(Z.headers!==void 0)Q.config.headers=Z.headers;if(Z.providerConfig!==void 0)Q.config.providerConfig=Z.providerConfig;if(Object.hasOwn(Z,"reasoningEffort"))Q.config.reasoningEffort=Z.reasoningEffort??void 0;if(Object.hasOwn(Z,"thinkingBudgetTokens"))Q.config.thinkingBudgetTokens=Z.thinkingBudgetTokens??void 0;if(Object.hasOwn(Z,"thinking")){if(Q.config.thinking=Z.thinking??void 0,Z.thinking===!1||Z.thinking===null)Q.config.reasoningEffort=void 0,Q.config.thinkingBudgetTokens=void 0}let J={...Z.providerId!==void 0?{providerId:Z.providerId}:{},...Z.modelId!==void 0?{modelId:Z.modelId}:{},...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{},...Z.providerConfig!==void 0?{providerConfig:Z.providerConfig}:{},...Object.hasOwn(Z,"reasoningEffort")?{reasoningEffort:Z.reasoningEffort??void 0}:{},...Object.hasOwn(Z,"thinking")?{thinking:Z.thinking??void 0}:{},...Object.hasOwn(Z,"thinkingBudgetTokens")?{thinkingBudgetTokens:Z.thinkingBudgetTokens??void 0}:{}};if(Z.thinking===!1||Z.thinking===null)J.reasoningEffort=void 0,J.thinkingBudgetTokens=void 0;let j={...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{}};if(Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults(J),Q.agent.updateConnection(Z),Q.runtime.teamRuntime?.updateTeammateConnections(j),Z.providerId||Z.modelId)await this.mutateSessionManifest(Q,(X)=>{if(Z.providerId)X.provider=Z.providerId;if(Z.modelId)X.model=Z.modelId})}async mutateSessionManifest($,W){let Z=$.artifacts;if(!Z)return;let Q=$.sessionId,j=(this.manifestMutationQueues.get(Q)??Promise.resolve()).then(async()=>{let Y=await this.invokeOptionalValue("readSessionManifest",Q)??Z.manifest;return W(Y),Z.manifest=Y,await this.invoke("writeSessionManifest",Z.manifestPath,Y),Y}),X=j.then(()=>{return},()=>{return});this.manifestMutationQueues.set(Q,X);try{return await j}finally{if(this.manifestMutationQueues.get(Q)===X)this.manifestMutationQueues.delete(Q)}}handlePluginEvent($,W,Z){return this.eventBridge.handlePluginEvent($,W,Z)}async executeTurn($,W){let Z=await this.prepareTurnInput($,W),Q=Z.prompt.trim(),J=Z?.userImages?.length,j=Z?.userFiles?.length;if(!Q&&!J&&!j)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Q;await this.ensureSessionPersisted($),await this.refreshActiveSessionGitMetadata($),await this.syncOAuthCredentials($),await this.markTurnRunning($);try{let X=await this.executeAgentTurn($,Q,Z.userImages,Z.userFiles);while(vj($,X.finishReason)){let Y=await cj($);if(Y.length===0)break;let V=uj($,Y);X=await this.executeAgentTurn($,V)}return X}finally{await this.refreshActiveSessionGitMetadata($)}}async completeInteractiveTurn($,W){if(H9($))return;$.lastInteractiveTurnFinishReason=W,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let W=$.lastInteractiveTurnFinishReason;if(!W)return"cancelled";switch(W){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return W}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let W=new Date,Z=$.agent.getMessages(),Q=z0();return $.persistedMessages=Z,$.started=$.started||Z.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Q,messages:Z,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:W,endedAt:W,durationMs:0}}async executeAgentTurn($,W,Z,Q){let J=$.started||$.agent.getMessages().length>0,j=$.persistedMessages??$.agent.getMessages(),X=this.usageBySession.get($.sessionId)??z0(),Y=this.aggregateUsageBySession.get($.sessionId)??X;$.turnUsageBaseline=X,$.turnAggregateUsageBaseline=Y,$.turnPrimaryUsage=z0(),$.turnUsageByAgent=new Map,ZW($.config.telemetry,$.sessionId,$.config.mode),L8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let V=J?()=>$.agent.continue(W,Z,Q):()=>$.agent.run(W,Z,Q),B=await this.runWithAuthRetry($,V,j);$.started=!0;let H=DZ(B.messages,B,j);$.persistedMessages=H;let G=K5($.turnUsageByAgent?.values()??[]),K=L0(X,B.usage),F=L0(L0(z0(),B.usage),G),A=L0(Y,F);return this.usageBySession.set($.sessionId,K),this.aggregateUsageBySession.set($.sessionId,A),await this.persistSessionMetadata($.sessionId,(D)=>({...D??{},totalCost:K.totalCost,aggregatedAgentsCost:A.totalCost,usage:K,aggregateUsage:A})),await this.invoke("persistSessionMessages",$.sessionId,H,$.config.systemPrompt),this.observeTaskCompletionTool($,B),B}catch(V){throw s$($.config.telemetry,{component:"core",operation:"session.turn",error:V,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),V}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,W){if($.submitAndExitObserved)return;if(!W.toolCalls.some((Q)=>Q.name===O0.SUBMIT_AND_EXIT&&Q.error===void 0))return;$.submitAndExitObserved=!0,Y4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,W){let Z=Z$($.config),Q=Zm(W.prompt).trim();if(!Q)return{prompt:"",userImages:W.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles)};let J=await d8(Q,Z);DF($.config.telemetry,J);let j=G9(J.prompt,W.mode??$.config.mode),X=this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles),Y=this.resolveAbsoluteFilePaths(Z,J.matchedFiles),V=Array.from(new Set([...X,...Y]));return{prompt:j,userImages:W.userImages,userFiles:V.length>0?V:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let W=Z$($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:W,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async refreshActiveSessionGitMetadata($,W){try{let Z=W??await S7(Z$($.config));if(!Z||!$.artifacts)return;if(P7($.artifacts.manifest.metadata,Z))return;await this.persistSessionMetadata($.sessionId,(Q)=>r9({...Q??{},...$.sessionMetadata??{}},Z))}catch(Z){$.config.logger?.debug?.("Failed to refresh session git metadata",{sessionId:$.sessionId,error:Z})}}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,W){let Z=this.sessions.get($),Q=await this.invokeOptionalValue("readSessionManifest",$)??Z?.artifacts?.manifest,J=W(Q?.metadata);if(!Z?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:J}))?.updated===!1)return;Z.sessionMetadata=J,Z.artifacts.manifest.metadata=J}async finalizeSingleRun($,W){if(H9($))return;let Z=W==="aborted"||$.aborting,Q=W==="error";await this.shutdownSession($,{status:Z?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:W})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,W){if(W.status==="completed"&&!$.submitAndExitObserved)Y4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});RQ($);let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),s$($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,status:W.status,shutdownReason:W.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){await this.refreshActiveSessionGitMetadata($);try{await this.updateStatus($,W.status,W.exitCode)}catch(J){Q("update_status",J)}try{await $.agent.shutdown(W.shutdownReason)}catch(J){Q("agent_shutdown",J)}}try{await Promise.resolve($.runtime.shutdown(W.shutdownReason))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:W.endReason,ts:Date.now()}}),Z.length>0&&W.status==="failed")throw Z[0]}async releaseSessionRuntime($,W){let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),s$($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,reason:W,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(W)}catch(J){Q("agent_shutdown",J)}try{await Promise.resolve($.runtime.shutdown(W))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),Z.length>0)throw Z[0]}async updateStatus($,W,Z){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,W,Z);if(!Q.updated)return;let J=await this.mutateSessionManifest($,(j)=>{if(j.status=W,K0(W))delete j.ended_at,j.exit_code=null;else j.ended_at=Q.endedAt??X0(),j.exit_code=typeof Z==="number"?Z:null});if(!J)return;$.status=W,$.updatedAt=Q.endedAt??X0(),$.endedAt=K0(W)?null:J.ended_at,$.exitCode=J.exit_code,this.emitStatus($.sessionId,W)}async runWithAuthRetry($,W,Z){try{return await W()}catch(Q){if(!K2($.config.providerId)||!Wm(Q))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Z),W()}}async syncOAuthCredentials($,W){let Z=null;try{Z=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:W?.forceRefresh})}catch(Q){if(Q instanceof O7)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!Z?.apiKey||$.config.apiKey===Z.apiKey)return;$.config.apiKey=Z.apiKey,$.agent.updateConnection({apiKey:Z.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Z.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Z.apiKey})}getSessionOrThrow($){let W=this.sessions.get($);if(!W){let Z=new l1($);throw s$(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Z,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Z}return W}resolveAbsoluteFilePaths($,W){if(!W||W.length===0)return[];let Z=W.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>eg(Q)?Q:EY($,Q));return Array.from(new Set(Z))}getSessionAgentTelemetryIdentity($){return W$({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let W=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Z=L0($.initialUsage,W);return this.withPersistedAggregateUsageFloor(Z,$.manifest)}async summarizePersistedTeammateUsage($,W,Z){let Q=EY(W),J=`${Z}.messages.json`,j;try{j=sg($)}catch{return z0()}let X=z0();for(let Y of j){if(!Y.endsWith(".messages.json"))continue;if(Y===J)continue;let V=EY($,Y);if(V===Q)continue;let B=await p$(V);if(B.length===0)continue;X=L0(X,$6(B))}return X}withPersistedAggregateUsageFloor($,W){let Z=Jm(W.metadata?.aggregateUsage);if(Z)return jm($,Z);let Q=W.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=$.totalCost)return $;return{...$,totalCost:Q}}emitStatus($,W){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:W}})}async emitSessionSnapshot($){let W=await this.getSession($);if(!W)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:N1({session:W,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),w_))}async getRow($){let W=$.trim();if(!W)return;return(await this.listRows(w_)).find((Q)=>Q.sessionId===W)}async readManifest($){let W=$.trim();if(!W)return;return await this.invokeOptionalValue("readSessionManifest",W)}invoke($,...W){return M_(this.sessionService,$,...W)}invokeOptional($,...W){return R_(this.sessionService,$,...W)}invokeOptionalValue($,...W){return E_(this.sessionService,$,...W)}}function Ym($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function Vm($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function __($={}){let W=new b1({sessionService:new S1(new C1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||F0.CLI,interactive:!1,config:{providerId:Xm(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:Vm(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content)});if(!J)throw Error("local hub schedule runtime returned no turn result");return{result:Ym(J)}},async abortSession(Z){return await W.abort(Z,Error("hub schedule abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}import{resolveClineBuildEnv as Sf}from"@cline/shared";function Bm($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Z)=>{if(Z&&typeof Z==="object"&&"type"in Z&&Z.type==="text"&&"text"in Z&&typeof Z.text==="string")return Z.text.trim();return""}).filter(Boolean).join(`
742
- `).trim()||void 0}var P_=120,NY="...";function k9($){let W=$.trim();if(!W)return"";if(Buffer.byteLength(W,"utf8")<=P_)return W;let Z=P_-Buffer.byteLength(NY,"utf8");if(Z<=0)return NY;let Q="";for(let J of W){if(Buffer.byteLength(Q+J,"utf8")>Z)break;Q+=J}return`${Q}${NY}`}async function S_($){let W=$?.sessionId?.trim()||"unknown",Z=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,J=[...await p$(Z)].reverse().find((V)=>V.role==="assistant"),j=J?Bm(J.content):void 0,X=$?.workspaceRoot?.trim()||"workspace",Y=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():X;return{title:`Task completed (${W})`,body:k9(j&&j.length>0?j:Y.length>0?Y:X),severity:"info"}}import{captureSdkError as E7,createSessionId as Hv}from"@cline/shared";import{createSessionId as Fm}from"@cline/shared";import{createSessionId as Km}from"@cline/shared";function Hm($){switch($){case"idle":return"idle";case"pending":return"pending";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function Gm($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())W.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())W.parentAgentId=$.parentAgentId;if($.agentId?.trim())W.agentId=$.agentId;if($.conversationId?.trim())W.conversationId=$.conversationId;if($.messagesPath?.trim())W.messagesPath=$.messagesPath;if($.prompt?.trim())W.prompt=$.prompt;if($.provider?.trim())W.provider=$.provider;if($.model?.trim())W.model=$.model;if($.source?.trim())W.source=$.source;if(typeof $.pid==="number")W.pid=$.pid;return Object.keys(W).length>0?W:void 0}function q7($,W,Z,Q){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:W?.createdByClientId??"hub",status:Hm($.status),participants:W?[...W.participants.values()]:[],metadata:Gm($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...Z?{usage:{...Z}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function u($,W){return{version:$.version,requestId:$.requestId,ok:!0,...W!==void 0?{payload:W}:{}}}function h($,W,Z){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:W,message:Z}}}function s6($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function S0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function H8($,W,Z){return{version:"v1",event:$,eventId:Km("hevt_"),sessionId:Z,timestamp:Date.now(),payload:W}}async function b0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let Q=await $.sessionHost.getAccumulatedUsage?.(W);return q7(Z,$.sessionState.get(W),Q?.usage,Q?.aggregateUsage)}async function u0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let[Q,J]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(W):[],$.sessionHost.getAccumulatedUsage?.(W)]);return N1({session:Z,messages:Q,usage:J?.usage,aggregateUsage:J?.aggregateUsage})}function wY($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(Q==="creator"&&!j.createdByClientId)j.createdByClientId=Z;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={createdByClientId:Z,interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}function b_($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}async function CY($,W){let Z=Fm("approval_"),Q=W.sessionId;if($.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((j)=>{$.pendingApprovals.set(Z,{sessionId:Q,resolve:j}),$.publish($.buildEvent("approval.requested",{approvalId:Z,sessionId:W.sessionId,agentId:W.agentId,conversationId:W.conversationId,iteration:W.iteration,toolCallId:W.toolCallId,toolName:W.toolName,inputJson:JSON.stringify(W.input??null),policy:W.policy},Q))})}function PY($,W,Z){let Q=$.pendingApprovals.get(W);if(!Q)return;return $.pendingApprovals.delete(W),Q.resolve(Z),{sessionId:Q.sessionId}}function SY($,W,Z){let Q=0;for(let[J,j]of[...$.pendingApprovals.entries()]){if(!W({approvalId:J,sessionId:j.sessionId}))continue;$.pendingApprovals.delete(J),j.resolve({approved:!1,reason:Z}),$.publish($.buildEvent("approval.resolved",{approvalId:J,approved:!1,cancelled:!0,reason:Z},j.sessionId)),Q+=1}return Q}async function y_($,W){let Z=typeof W.payload?.approvalId==="string"?W.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Z))return h(W,"approval_not_found",`Unknown approval: ${Z}`);let J=typeof W.payload?.reason==="string"?W.payload.reason:W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)&&typeof W.payload.payload.reason==="string"?W.payload.payload.reason:void 0,j=W.payload?.approved===!0,X=PY($,Z,{approved:j,reason:J});if(!X)return h(W,"approval_not_found",`Unknown approval: ${Z}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:j,reason:J},X.sessionId)),u(W,{approvalId:Z,approved:j})}import{createSessionId as Dm}from"@cline/shared";function Am($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var h_={debug:10,info:20,warn:30,error:40,silent:50};function Um(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function i($,W,Z={}){if(h_[$]<h_[Um()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:W,...Object.fromEntries(Object.entries(Z).map(([J,j])=>[J,Am(j)]).filter(([,J])=>J!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function bY($,W){let Z=W instanceof Error?W.stack||W.message:String(W);i("error",$,{error:Z})}async function k_($,W,Z,Q,J,j){let X=Dm("capreq_"),Y=performance.now();return i("info","capability.request.start",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J}),await new Promise((V,B)=>{$.pendingCapabilityRequests.set(X,{sessionId:W,targetClientId:J,capabilityName:Z,onProgress:j,resolve:(H)=>{if(i(H.ok?"info":"warn","capability.request.end",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J,ok:H.ok,error:H.error,durationMs:Math.round(performance.now()-Y)}),!H.ok){B(Error(H.error||`Capability ${Z} was rejected by ${J}.`));return}V(H.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:X,targetClientId:J,capabilityName:Z,payload:Q},W)),i("info","capability.request.published",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J})})}function I_($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);if((W.clientId?.trim()||"")!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{};return Q.onProgress?.(j),u(W,{requestId:Z})}function t$($,W,Z){let Q=0;for(let[J,j]of[...$.pendingCapabilityRequests.entries()]){if(!W({requestId:J,...j}))continue;$.pendingCapabilityRequests.delete(J),i("warn","capability.request.cancelled",{requestId:J,sessionId:j.sessionId,capabilityName:j.capabilityName,targetClientId:j.targetClientId,reason:Z}),j.resolve({ok:!1,error:Z}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:j.capabilityName,targetClientId:j.targetClientId,ok:!1,cancelled:!0,error:Z},j.sessionId)),Q+=1}return Q}async function x_($,W){let Z=typeof W.payload?.sessionId==="string"?W.payload.sessionId.trim():W.sessionId?.trim()||"",Q=typeof W.payload?.capabilityName==="string"?W.payload.capabilityName.trim():"",J=typeof W.payload?.targetClientId==="string"?W.payload.targetClientId.trim():"";if(!Z||!Q||!J)return h(W,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{},X=await $.requestCapability(Z,Q,j,J);return u(W,X)}catch(j){return h(W,"capability_request_failed",j instanceof Error?j.message:String(j))}}function g_($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);let J=W.clientId?.trim()||"";if(J!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);$.pendingCapabilityRequests.delete(Z);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:void 0,X=typeof W.payload?.error==="string"?W.payload.error:void 0,Y=W.payload?.ok===!0;return i(Y?"info":"warn","capability.respond",{requestId:Z,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,error:X}),Q.resolve({ok:Y,payload:j,error:X}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,payload:j,error:X},Q.sessionId)),u(W,{requestId:Z,ok:Y})}import{createSessionId as _m}from"@cline/shared";function m_($,W){let Z=W.payload,Q=Z?.clientId?.trim()||W.clientId?.trim()||_m("client_");return $.clients.set(Q,{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,actorKind:Z?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Z?.transport??"native",capabilities:Z?.capabilities??[],metadata:Z?.metadata,workspaceContext:Z?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,connectedAt:Date.now()})),u(W,{clientId:Q})}function v_($,W){let Z=W.clientId?.trim(),Q=Z?$.clients.get(Z):void 0;if(!Z||!Q)return h(W,"client_not_found","Client is not registered with this hub.");let J=s6(W.payload?.metadata);if(Q.lastSeenAt=Date.now(),J)Q.metadata=JSON.parse(JSON.stringify(J));return u(W)}function c_($,W,Z){let Q=W.clientId?.trim();if(Q)$.clients.delete(Q),Z(Q),$.publish($.buildEvent("hub.client.disconnected",{clientId:Q}));return u(W)}function u_($,W){return u(W,{clients:[...$.clients.values()]})}R0();import{existsSync as p_,mkdirSync as fm,readdirSync as Lm,readFileSync as Tm,rmSync as Om,writeFileSync as zm}from"node:fs";import{dirname as qm,join as d_}from"node:path";import{CONNECTOR_PLATFORMS as Mm,connectorChannelsFromPlatforms as Rm,listConnectorCatalog as r_,shouldIncludeConnectorField as Em}from"@cline/shared";import{resolveConnectorDataDir as Nm,resolveConnectorSettingsPath as hY}from"@cline/shared/storage";var wm=1,l_={startedAt:($)=>typeof $.startedAt==="string"?$.startedAt:void 0,port:($)=>typeof $.port==="number"?$.port:void 0,baseUrl:($)=>typeof $.baseUrl==="string"?$.baseUrl:void 0,connectionMode:($)=>typeof $.connectionMode==="string"?$.connectionMode:void 0,userName:($)=>typeof $.userName==="string"?$.userName:void 0,botUsername:($)=>typeof $.botUsername==="string"?$.botUsername:void 0,applicationId:($)=>typeof $.applicationId==="string"?$.applicationId:void 0,phoneNumberId:($)=>typeof $.phoneNumberId==="string"?$.phoneNumberId:void 0},Cm={discord:{required:["userName","applicationId"],optional:["startedAt","port","baseUrl"]},telegram:{required:["botUsername"],optional:["startedAt"]},gchat:{required:["userName"],optional:["startedAt","port","baseUrl"]},linear:{required:["userName"],optional:["startedAt","port","baseUrl"]},slack:{required:["userName"],optional:["startedAt","connectionMode","port","baseUrl"]},whatsapp:{required:["userName"],optional:["startedAt","phoneNumberId","port","baseUrl"]}};function e$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function v9($){return typeof $==="string"?$.trim():void 0}function i_($){if(!p_($))return;try{let W=JSON.parse(Tm($,"utf8"));return e$(W)?W:void 0}catch{return}}function kY(){let $=i_(hY()),W=e$($?.connectors)?$.connectors:{},Z={};for(let[Q,J]of Object.entries(W)){if(!e$(J))continue;let j=v9(J.type),X=v9(J.configuredAt),Y=v9(J.updatedAt);if(!j||!X||!Y)continue;let V=M7(J.values),B=e$(J.security)?{enabled:J.security.enabled===!0,values:M7(J.security.values)}:void 0;Z[Q]={type:j,values:V,security:B,configuredAt:X,updatedAt:Y}}return{version:wm,connectors:Z}}function n_($){let W=hY();fm(qm(W),{recursive:!0}),zm(W,`${JSON.stringify($,null,2)}
743
- `,"utf8")}function M7($){if(!e$($))return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q.trim();return W}function Pm($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function Sm($){let W=d_(Nm(),$);if(!p_(W))return[];return Lm(W).filter((Z)=>Z.endsWith(".json")&&!Z.endsWith(".threads.json")).map((Z)=>d_(W,Z))}function bm($,W,Z){let Q=W.botUsername??W.userName??W.applicationId??W.phoneNumberId??String(Z);return`${$}:${Q}`}function ym($,W){let Z=i_(W);if(!Z)return;let Q=typeof Z.pid==="number"?Z.pid:void 0,J=typeof Z.hubUrl==="string"?Z.hubUrl:typeof Z.rpcAddress==="string"?Z.rpcAddress:void 0;if(!Q||!J||!Pm(Q))return;let j=Cm[$];if(!j)return;let X={};for(let Y of j.required){let V=l_[Y](Z);if(!V||typeof V==="string"&&!V.trim())return;X[Y]=V}for(let Y of j.optional){let V=l_[Y](Z);if(V!==void 0)X[Y]=V}return{id:bm($,X,Q),type:$,pid:Q,hubUrl:J,...X}}function hm(){let $=[];for(let{name:W}of r_())for(let Z of Sm(W)){let Q=ym(W,Z);if(Q)$.push(Q)}return $.sort((W,Z)=>{if(W.type!==Z.type)return W.type.localeCompare(Z.type);let Q=W.botUsername??W.userName??"",J=Z.botUsername??Z.userName??"";return Q.localeCompare(J)})}function km(){let $=kY();return Object.entries($.connectors).map(([W,Z])=>({id:W,type:Z.type,configuredAt:Z.configuredAt,updatedAt:Z.updatedAt})).sort((W,Z)=>W.type.localeCompare(Z.type))}function IY(){return{available:Rm(),active:hm(),configured:km()}}function Im($,W){if($.required&&!W[$.flag]?.trim())throw Error(`${$.label} is required`)}function xm($,W){let Z={};for(let J of $.fields)Z[J.flag]=W[J.flag]??J.initialValue??"";let Q={};for(let J of $.fields){if(!Em(J,Z))continue;Im(J,Z),Q[J.flag]=Z[J.flag]}return Q}function gm($){if(!e$($))throw Error("connector.configure payload must be an object.");let W=v9($.channel);if(!W)throw Error("channel is required");let Z=Mm.find((K)=>K.id===W);if(!Z)throw Error(`unknown connector channel: ${W}`);if(!new Set(r_().map((K)=>K.name)).has(Z.id))throw Error(`connector channel is not available: ${W}`);let J=M7($.values),j=xm(Z,J),X=e$($.security)?$.security:{},Y=X.enabled===!0,V=M7(X.values);if(Y&&Z.security)for(let K of Z.security.fields){let F=V[K.key];if(!F)throw Error(K.requiredMessage);let A=K.validate?.(F);if(A)throw Error(A)}let B=kY(),H=new Date().toISOString(),G=B.connectors[W];return B.connectors[W]={type:W,values:j,security:Y?{enabled:!0,values:V}:{enabled:!1,values:{}},configuredAt:G?.configuredAt??H,updatedAt:H},n_(B),IY()}function mm($){if(!e$($))throw Error("connector.delete_config payload must be an object.");let W=v9($.channel);if(!W)throw Error("channel is required");let Z=kY();if(delete Z.connectors[W],Object.keys(Z.connectors).length>0)n_(Z);else Om(hY(),{force:!0});return IY()}function vm($){return $==="connector.configure"||$==="connector.delete_config"}function yY($,W,Z){if(!vm(W.command))return;T8($.telemetry,{ulid:W.sessionId??W.requestId??"hub",tool:W.command,success:Z})}async function a_($,W){try{if(W.command==="connector.channels")return u(W,IY());if(W.command==="connector.configure"){let Z=gm(W.payload);return yY($,W,!0),u(W,Z)}if(W.command==="connector.delete_config"){let Z=mm(W.payload);return yY($,W,!0),u(W,Z)}return h(W,"unsupported_connector_command",`unsupported connector command: ${W.command}`)}catch(Z){return yY($,W,!1),h(W,"connector_command_failed",Z instanceof Error?Z.message:String(Z))}}var cm=30000;function um($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function dm($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function lm($,W,Z){let Q=Z instanceof Error&&Z.message.trim()?Z.message:`Unknown session: ${W}`;return h($,X2,Q)}function pm($){return $?$:void 0}function rm($){let W=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(W&&Number.isFinite(W)&&W>0)return Math.floor(W);let Z=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Z&&Number.isFinite(Z)&&Z>0)return Math.floor(Z*1000);return}async function im($,W,Z,Q){let J=performance.now(),j=!1,X={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z.sessionId,timeoutMs:Q},Y=setInterval(()=>{if(j)return;let H=Math.round(performance.now()-J);i("warn","run.heartbeat",{...X,elapsedMs:H}),$.publish($.buildEvent("run.heartbeat",{requestId:W.requestId,elapsedMs:H,...Q?{timeoutMs:Q}:{}},Z.sessionId))},cm),V=$.sessionHost.runTurn(Z);V.then((H)=>{if(!j)return;i("warn","run.late_end",{...X,elapsedMs:Math.round(performance.now()-J),finishReason:H?.finishReason})},(H)=>{if(!j)return;i("error","run.late_error",{...X,elapsedMs:Math.round(performance.now()-J),error:H})});let B;try{if(!Q)return await V;return await Promise.race([V,new Promise((H,G)=>{B=setTimeout(()=>{let K=`Hub run ${W.command} timed out after ${Q}ms.`;j=!0,clearInterval(Y),G(Error(K)),i("error","run.timeout",{...X,elapsedMs:Math.round(performance.now()-J)}),SY($,(F)=>F.sessionId===Z.sessionId,K),t$($,(F)=>F.sessionId===Z.sessionId,K),$.sessionHost.abort(Z.sessionId,K).catch((F)=>{i("error","run.timeout_abort_failed",{...X,error:F})})},Q)})])}finally{if(j=!0,clearInterval(Y),B)clearTimeout(B)}}async function o_($,W){let Z=S0(W),Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!J.trim())return h(W,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Z));let j=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,X=Array.isArray(j?.userFiles)?j.userFiles.filter((H)=>typeof H==="string"):void 0,Y=rm(Q);$.suppressNextTerminalEventBySession.set(Z,"run.start.reply");let V;try{V=await im($,W,{sessionId:Z,prompt:J,mode:pm(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(j?.userImages)?j.userImages:void 0,userFiles:X,timeoutMs:Y},Y)}catch(H){if($.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z);if(p1(H))return lm(W,Z,H);throw $.publish($.buildEvent("run.failed",{reason:"error",error:H instanceof Error?H.message:String(H)},Z)),H}if(V){let H=await u0($,Z),G=dm(V);if($.publish($.buildEvent(um(V.finishReason),{reason:V.finishReason,...G?{error:G}:{},result:V,...H?{snapshot:H}:{}},Z)),$.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z)}else $.suppressNextTerminalEventBySession.delete(Z);let B=await u0($,Z);return u(W,V||B?{...V?{result:V}:{},...B?{snapshot:B}:{}}:void 0)}async function s_($,W){let Z=S0(W),Q=typeof W.payload?.reason==="string"?W.payload.reason:"Run was aborted before pending approval or capability request was resolved.";SY($,(J)=>J.sessionId===Z,Q);try{await $.sessionHost.abort(Z,W.payload?.reason)}catch(J){i("warn","run.abort_failed",{command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z,error:J})}finally{t$($,(J)=>J.sessionId===Z,Q)}return u(W,{applied:!0})}async function t_($,W){let Z=m6(W.payload?.payload);if(!Z)return h(W,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Z),u(W,{applied:!0})}async function e_($,W){switch(W.type){case"chunk":return;case"agent_event":await nm($,W);return;case"hook":if(W.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:W.payload.toolName},W.payload.sessionId));else if(W.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:W.payload.toolName},W.payload.sessionId));return;case"team_progress":{let Z={type:"team_progress_projection",version:1,sessionId:W.payload.sessionId,summary:W.payload.summary,lastEvent:W.payload.lifecycle};$.publish($.buildEvent("team.progress",Z,W.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:W.payload.sessionId,prompts:W.payload.prompts},W.payload.sessionId));return;case"pending_prompt_submitted":{let Z={id:W.payload.id,prompt:W.payload.prompt,delivery:W.payload.delivery,attachmentCount:W.payload.attachmentCount,userImages:W.payload.userImages,userFiles:W.payload.userFiles};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:W.payload.sessionId,prompt:Z},W.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:W.payload.sessionId,snapshot:W.payload.snapshot},W.payload.sessionId));return;case"status":{let[Z,Q]=await Promise.all([b0($,W.payload.sessionId),u0($,W.payload.sessionId)]);if(Z)$.publish($.buildEvent("session.updated",{session:Z,...Q?{snapshot:Q}:{}},W.payload.sessionId));return}case"ended":await am($,W);return;default:return}}async function nm($,W){let{sessionId:Z,event:Q}=W.payload;if(Q.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Q.iteration},Z));return}if(Q.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},Z));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Q.text},Z));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Z));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},Z));return}if(Q.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},Z));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Q.text},Z));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Q.reasoning},Z));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},Z));break}return}if(Q.type==="notice"){$.publish($.buildEvent("session.notice",{sessionId:Z,message:Q.message,noticeType:Q.noticeType,...Q.displayRole?{displayRole:Q.displayRole}:{},...Q.reason?{reason:Q.reason}:{},...Q.metadata?{metadata:Q.metadata}:{},agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="usage"){let J;try{J=await $.sessionHost.getAccumulatedUsage?.(Z)}catch{J=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Z,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:J?.usage,aggregateUsage:J?.aggregateUsage,agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="done")$.publish($.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},Z))}async function am($,W){let Z=$.suppressNextTerminalEventBySession.get(W.payload.sessionId),Q=Z===W.payload.reason||Z==="run.start.reply";if(Q)$.suppressNextTerminalEventBySession.delete(W.payload.sessionId);let[J,j]=await Promise.all([b0($,W.payload.sessionId),u0($,W.payload.sessionId)]);if(W.payload.reason==="completed"){let X=await S_(J);$.publish($.buildEvent("ui.notify",X,W.payload.sessionId))}if(Q)return;$.publish($.buildEvent(W.payload.reason==="aborted"?"run.aborted":W.payload.reason==="error"||W.payload.reason==="failed"?"run.failed":"run.completed",{reason:W.payload.reason,...j?{snapshot:j}:{}},W.payload.sessionId))}import{createSessionId as Qf,parseRuntimeConfigExtensions as Jf}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as d20,HUB_COMPACTION_CAPABILITY as l20,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as p20,HUB_HOOK_CAPABILITY_PREFIX as r20,HUB_MISTAKE_LIMIT_CAPABILITY as i20,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as n20,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as a20,isHubToolExecutorName as om}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as W80,HUB_COMPACTION_CAPABILITY as Z80,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Q80,HUB_HOOK_CAPABILITY_PREFIX as J80,HUB_MISTAKE_LIMIT_CAPABILITY as j80,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as X80,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Y80}from"@cline/shared";var sm=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function G8($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function tm($,W){let Z=typeof $.name==="string"?$.name.trim():"",Q=typeof $.description==="string"?$.description:"",J=typeof $.capabilityName==="string"?$.capabilityName.trim():"",j=G8($.inputSchema);if(!Z||!Q||!j||!J||W.has(J))return;return W.add(J),{kind:"tool",capabilityName:J,name:Z,description:Q,inputSchema:j,...G8($.lifecycle)?{lifecycle:G8($.lifecycle)}:{}}}function gY($){if(!Array.isArray($))return[];let W=[],Z=new Set;for(let Q of $){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let J=Q,j=J.kind,X=typeof J.capabilityName==="string"?J.capabilityName.trim():"";if(!X||Z.has(X))continue;if(j==="tool"){let Y=tm(J,Z);if(Y)W.push(Y);continue}if(j==="toolExecutor"){let Y=J.executor;if(!om(Y))continue;Z.add(X),W.push({kind:"toolExecutor",capabilityName:X,executor:Y});continue}if(j==="hook"){let Y=typeof J.name==="string"?J.name.trim():"";if(!Y)continue;Z.add(X),W.push({kind:"hook",capabilityName:X,name:Y});continue}if(j==="compaction"){Z.add(X),W.push({kind:"compaction",capabilityName:X,...G8(J.config)?{config:G8(J.config)}:{}});continue}if(j==="checkpoint"){Z.add(X),W.push({kind:"checkpoint",capabilityName:X,...G8(J.config)?{config:G8(J.config)}:{}});continue}if(j==="mistakeLimit"){Z.add(X),W.push({kind:"mistakeLimit",capabilityName:X});continue}if(j==="userInstructionService")Z.add(X),W.push({kind:"userInstructionService",capabilityName:X})}return W}function Wf($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W[iW];return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:W&&Object.keys(W).length>0?W:void 0}}function em($){return Object.hasOwn($,"update")?$.update:$}function c9($){return $.trim().replace(/^\/+/,"").toLowerCase()}function $v($){let W=($??[]).map(c9).filter(Boolean);return W.length>0?new Set(W):void 0}function Wv($,W,Z){if(!Z)return!0;let Q=c9($),J=c9(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function xY($,W){let Z=$v(W);return $.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>Wv(Q.id,Q.name,Z))}function $f($,W){let Z=async(Q,J)=>{let j=c9(Q),Y=xY($,W).filter((K)=>K.id===j||c9(K.name)===j||K.id.endsWith(`:${j}`)).filter((K)=>!K.disabled);if(Y.length!==1)return Y.length>1?`Skill "${Q}" is ambiguous. Use one of: ${Y.map((K)=>K.id).join(", ")}`:`Skill "${Q}" not found.`;let V=Y[0].skill,B=J?.trim(),H=B?`
732
+ ${V}`:""}`);let B=ck($);if(rQ($))throw Error(`Skill uninstall completed, but ${$.name??$.id} is still present in Cline's global skills directories.`);return{id:$.id,type:"skill",status:"uninstalled",message:`Uninstalled ${$.name??$.id}.`,output:[V,...B.map((H)=>`Removed: ${H}`)].filter(Boolean).join(`
733
+ `)||void 0}}async function nQ($,W={}){let[Z]=EX($),Q=Z?.trim()||$.id;if(!Q)throw Error("Plugin marketplace uninstalls require a plugin name.");let J=await T9({name:Q,workspaceRoot:W.workspaceRoot});return{id:$.id,type:"plugin",status:"uninstalled",message:`Uninstalled ${$.name??J.name??$.id}.`,output:[`Path: ${J.installPath}`,...J.removedPaths.map((j)=>`Removed: ${j}`)].join(`
734
+ `)}}async function wX($,W={}){if($.type==="mcp"){let Z=z9($);if(W.deleteMcpServer)await W.deleteMcpServer(Z);else pQ($,W);return{id:$.id,type:$.type,status:"uninstalled",message:`Uninstalled ${$.name??Z??$.id}.`}}if($.type==="skill")return iQ($,W);if($.type==="plugin")return nQ($,W);throw Error(`Unsupported marketplace entry type: ${$.type}`)}var yD={};w(yD,{parsePluginSource:()=>Q7,isOfficialPluginSlug:()=>Z7,installPlugin:()=>hX,collectPluginMcpOAuthCandidates:()=>J7});import{spawn as uk}from"node:child_process";import{createHash as dk}from"node:crypto";import{existsSync as y1,mkdirSync as SX,readdirSync as lk,readFileSync as pk,renameSync as aQ,rmSync as tQ,statSync as bX}from"node:fs";import{cp as PX,mkdir as ND,writeFile as eQ}from"node:fs/promises";import{homedir as TD}from"node:os";import{basename as F$,dirname as OD,extname as rk,join as t,relative as wD,resolve as a$,sep as ik}from"node:path";import{isPluginModulePath as sQ,resolveClineDir as nk,resolvePluginModuleEntries as ak}from"@cline/shared/storage";var r6="_installed",$7="package",ok="https://github.com/cline/plugins.git",zD=30000,oQ=10485760,qD="@cline/",sk=["dependencies","devDependencies","optionalDependencies","peerDependencies"],tk={name:"cline-installed-plugin",private:!0,cline:{plugins:[]}};function W7($){if($==="~")return TD();if($.startsWith("~/"))return t(TD(),$.slice(2));return $}function CD($){return $.split(ik).join("/")}function Y8($){return dk("sha256").update($).digest("hex").slice(0,12)}function ek($){let W=0;while(W<$.length&&$[W]==="-")W++;let Z=$.length;while(Z>W&&$[Z-1]==="-")Z--;return $.slice(W,Z)}function K$($){let W="",Z=!1,Q=$.startsWith("@")?$.slice(1):$;for(let j of Q.slice(0,256)){if(j>="a"&&j<="z"||j>="A"&&j<="Z"||j>="0"&&j<="9"||j==="."||j==="_"||j==="-")W+=j,Z=j==="-";else if(!Z)W+="-",Z=!0;if(W.length>=80)break}return ek(W)||"plugin"}function Z7($){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test($.trim())}function $I($){return $?.trim()||ok}function MD($){let Z=$.trim().match(/^(@?[^@/]+(?:\/[^@/]+)?)(?:@.+)?$/);if(!Z?.[1])throw Error(`Invalid npm plugin source: npm:${$}`);return{name:Z[1]}}function WI($){if($.startsWith(".")||$.startsWith("/")||$==="~"||$.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test($))return!1;let[W,...Z]=$.split("/");return!!W&&Z.length>=2&&W.includes(".")&&!W.startsWith(".")&&!W.endsWith(".")}function ZI($){let W=$.match(/^git@([^:]+):(.+)$/);if(W){let X=W[2]??"",Y=X.indexOf("@");if(Y<0)return{repo:$};return{repo:`git@${W[1]}:${X.slice(0,Y)}`,ref:X.slice(Y+1)||void 0}}if($.includes("://"))try{let X=new URL($),Y=X.pathname.replace(/^\/+/,""),V=Y.indexOf("@");if(V<0)return{repo:$};return X.pathname=`/${Y.slice(0,V)}`,{repo:X.toString().replace(/\/$/,""),ref:Y.slice(V+1)||void 0}}catch{return{repo:$}}let Z=$.indexOf("/");if(Z<0)return{repo:$};let Q=$.slice(0,Z),J=$.slice(Z+1),j=J.indexOf("@");if(j<0)return{repo:$};return{repo:`${Q}/${J.slice(0,j)}`,ref:J.slice(j+1)||void 0}}function QI($){try{return decodeURIComponent($)}catch{return $}}function JI($){return F$(QI($))||"plugin"}function jI($){let W=$.split("/").filter(Boolean);return W.length>=5&&(W[2]==="blob"||W[2]==="raw")}function RD($){if(!/^https?:\/\//i.test($))return null;let W;try{W=new URL($)}catch{return null}let Z=W.hostname.toLowerCase(),Q=JI(W.pathname),J=sQ(Q),j=(Z==="github.com"||Z==="www.github.com")&&jI(W.pathname);if(W.protocol!=="https:"){if(j||Z==="raw.githubusercontent.com"||J)throw Error(`Remote plugin file URLs must use https: ${$}`);return null}if(Z==="github.com"||Z==="www.github.com"){let X=W.pathname.split("/").filter(Boolean);if(!j)return null;if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:`https://raw.githubusercontent.com/${[X[0],X[1],...X.slice(3)].join("/")}`,filename:Q}}if(Z==="raw.githubusercontent.com"){if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:W.toString(),filename:Q}}if(!J)return null;return{type:"remote",url:W.toString(),filename:Q}}function ED($,W={}){let Z=$.trim(),Q=Z.startsWith("git:")&&!Z.startsWith("git://"),J=Q?Z.slice(4).trim():Z;if(!W.force&&!Q&&!/^(https?|ssh|git):\/\//i.test(J))return null;let{repo:j,ref:X}=ZI(J),Y="",V="";if(j.startsWith("git@")){let G=j.match(/^git@([^:]+):(.+)$/);Y=G?.[1]??"",V=G?.[2]??""}else if(/^(https?|ssh|git):\/\//i.test(j)){let G=new URL(j);Y=G.hostname,V=G.pathname.replace(/^\/+/,"")}else{let G=j.indexOf("/");if(G<0)return null;Y=j.slice(0,G),V=j.slice(G+1)}let B=V.replace(/\.git$/,"").replace(/^\/+/,"");if(!Y||!B||B.split("/").length<2)return null;return{type:"git",repo:j.startsWith("git@")||/^(https?|ssh|git):\/\//i.test(j)?j:`https://${j}`,ref:X,host:Y,path:B}}function Q7($,W){let Z=$.trim();if(!Z)throw Error("plugin install requires a source");if(W==="npm"){let X=Z.startsWith("npm:")?Z.slice(4).trim():Z,{name:Y}=MD(X);return{type:"npm",spec:X,name:Y}}if(W==="git"){let X=ED(Z,{force:!0});if(!X)throw Error(`Invalid git plugin source: ${$}`);return X}if(W==="local")return{type:"local",path:$};if(W==="remote"){let X=RD(Z);if(!X)throw Error(`Invalid remote plugin source: ${$}`);return X}if(Z.startsWith("npm:")){let X=Z.slice(4).trim(),{name:Y}=MD(X);return{type:"npm",spec:X,name:Y}}if(Z.startsWith(".")||Z.startsWith("/")||Z==="~"||Z.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test(Z))return{type:"local",path:$};let J=RD(Z);if(J)return J;let j=ED(Z);if(j)return j;if(Z7(Z))return{type:"official",slug:Z};if(WI(Z))throw Error(`Unrecognized plugin source "${$}". Use --git for hostname-style repositories or pass an explicit local path such as ./github.com/owner/repo.`);return{type:"local",path:$}}function XI($){return $?t($,".cline","plugins"):t(nk(),"plugins")}function YI($,W,Z){if(W.type==="npm")return t($,r6,"npm",`${K$(W.name)}-${Y8(Z)}`);if(W.type==="git")return t($,r6,"git",K$(W.host),`${K$(W.path)}-${Y8(Z)}`);if(W.type==="remote")return t($,r6,"remote",`${K$(W.filename)}-${Y8(Z)}`);if(W.type==="official")return t($,r6,"official",`${K$(W.slug)}-${Y8(Z)}`);return t($,r6,"local",`${K$(F$(W7(W.path)))}-${Y8(Z)}`)}function VI($,W,Z){if($.type==="npm")return`npm:${$.spec}`;if($.type==="git")return`git:${$.repo}${$.ref?`#${$.ref}`:""}`;if($.type==="remote")return`remote:${$.url}`;if($.type==="official")return`official:${Z}#plugins/${$.slug}`;return`local:${a$(W,W7($.path))}`}function BI($,W){if($.type==="npm")return $.name;if($.type==="git")return K$(F$($.path));if($.type==="remote")return K$(F$($.filename,rk($.filename)));if($.type==="official")return $.slug;return K$(F$(a$(W,W7($.path))))}async function i6($,W,Z={}){await new Promise((Q,J)=>{let j=uk($,W,{cwd:Z.cwd,stdio:["ignore","ignore","pipe"],env:process.env,windowsHide:!0}),X="";j.stderr.on("data",(Y)=>{X+=String(Y)}),j.on("error",J),j.on("close",(Y)=>{if(Y===0){Q();return}let V=X.trim();J(Error(`${$} ${W.join(" ")} failed with exit code ${Y}${V?`: ${V}`:""}`))})})}function PD($){let W=t($,"package.json");if(!y1(W))return null;try{return JSON.parse(pk(W,"utf8"))}catch{return null}}function HI($){let W=$?.cline?.plugins;if(!Array.isArray(W))return[];return W.flatMap((Z)=>{if(typeof Z==="string")return[Z];return Z.paths??[]})}async function GI($){let W=t($,"package.json"),Z=PD($);if(!Z)return;let Q=!1;for(let J of sk){let j=Z[J];if(!j||typeof j!=="object")continue;for(let X of Object.keys(j)){if(!X.startsWith(qD))continue;delete j[X],delete Z.peerDependenciesMeta?.[X],Q=!0}if(Object.keys(j).length===0)delete Z[J]}if(Z.peerDependenciesMeta){for(let J of Object.keys(Z.peerDependenciesMeta)){if(!J.startsWith(qD))continue;delete Z.peerDependenciesMeta[J],Q=!0}if(Object.keys(Z.peerDependenciesMeta).length===0)delete Z.peerDependenciesMeta}if(!Q)return;await eQ(W,`${JSON.stringify(Z,null,2)}
735
+ `,"utf8")}function KI($,W){let Z=t($,"node_modules","@cline");if(!y1(Z))return;for(let Q of bD(Z)){if(`@cline/${Q.name}`===W)continue;tQ(t(Z,Q.name),{recursive:!0,force:!0})}}function SD($){let W=HI(PD($)).map((j)=>a$($,j)).filter((j)=>y1(j)&&bX(j).isFile()&&sQ(j));if(W.length>0)return W;let Z=ak($);if(Z?.length)return Z;let Q=[],J=[$];while(J.length>0){let j=J.pop();if(!j)continue;for(let X of bD(j)){let Y=t(j,X.name);if(X.name==="node_modules"||X.name===".git")continue;if(X.isDirectory()){J.push(Y);continue}if(X.isFile()&&!X.name.startsWith(".")&&sQ(Y))Q.push(Y)}}return Q.sort((j,X)=>j.localeCompare(X))}function bD($){try{return lk($,{withFileTypes:!0})}catch{return[]}}function FI($,W){let Z=SD(W);if(Z.length===0)throw Error(`No plugin entry files found in ${W}`);return Z.map((Q)=>`./${CD(wD($,Q))}`)}async function AI($,W,Z){let Q=FI($,W);return await eQ(t($,"package.json"),JSON.stringify({...tk,name:Z,cline:{plugins:[{paths:Q}]}},null,2),"utf8"),Q}async function UI($,W,Z){let Q=t(W,$7);return await ND(Q,{recursive:!0}),await eQ(t(Q,"package.json"),JSON.stringify({name:"cline-plugin-install",private:!0},null,2),"utf8"),await i6(Z,["install",$.spec,"--prefix",Q,"--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"]),KI(Q,$.name),t(Q,"node_modules",$.name)}async function yX($,W){if(!y1(t($,"package.json")))return;await GI($),await i6(W,["install","--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"],{cwd:$})}async function DI($,W,Z){if($.ref?.startsWith("-"))throw Error(`Invalid git ref "${$.ref}".`);let Q=t(W,$7),J=["clone","--filter=blob:none"];if($.ref)J.push("--branch",$.ref);J.push("--",$.repo,Q);try{await i6("git",J)}catch(j){if(!$.ref)throw j;await i6("git",["clone","--filter=blob:none","--",$.repo,Q]),await i6("git",["checkout","--detach",$.ref],{cwd:Q})}return await yX(Q,Z),Q}async function _I($,W,Z,Q){let J=t(W,"repo");await i6("git",["clone","--filter=blob:none","--depth","1","--",Q,J]);let j=t(J,"plugins",$.slug);if(!y1(j)||!bX(j).isDirectory())throw Error(`Official Cline plugin "${$.slug}" was not found at plugins/${$.slug} in ${Q}`);let X=t(W,$7);return await PX(j,X,{recursive:!0,filter:(Y)=>{let V=F$(Y);return V!==".git"&&V!=="node_modules"}}),tQ(J,{recursive:!0,force:!0}),await yX(X,Z),X}function CX($){return Error(`Remote plugin file from ${$} exceeds the ${oQ} byte limit`)}function fI($){let W=$.headers.get("content-length");if(!W)return;let Z=Number(W);if(!Number.isFinite(Z)||Z<0)return;return Z}async function LI($,W){let Z=fI($);if(Z!==void 0&&Z>oQ)throw CX(W);if(!$.body){let X=Buffer.from(await $.text(),"utf8");if(X.byteLength>oQ)throw CX(W);return X}let Q=$.body.getReader(),J=[],j=0;try{while(!0){let{done:X,value:Y}=await Q.read();if(X)break;let V=Buffer.from(Y);if(j+=V.byteLength,j>oQ)throw await Q.cancel().catch(()=>{return}),CX(W);J.push(V)}return Buffer.concat(J,j)}finally{Q.releaseLock()}}async function TI($,W){let Z=new AbortController,Q=setTimeout(()=>{Z.abort()},zD);try{let J=await fetch($.url,{signal:Z.signal});if(!J.ok){let X=J.statusText?` ${J.statusText}`:"";throw Error(`Failed to download plugin file from ${$.url}: ${J.status}${X}`)}let j=await LI(J,$.url);return SX(W,{recursive:!0}),await eQ(t(W,$.filename),j),W}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error(`Timed out downloading plugin file from ${$.url} after ${zD}ms`);throw J}finally{clearTimeout(Q)}}async function OI($,W,Z,Q){let J=a$(Z,W7($.path));if(!y1(J))throw Error(`Plugin source path does not exist: ${J}`);let j=bX(J);if(j.isFile()){if(!sQ(J))throw Error(`Plugin file must be .js or .ts: ${J}`);SX(W,{recursive:!0});let Y=t(W,F$(J));return await PX(J,Y),W}if(!j.isDirectory())throw Error(`Plugin source must be a file or directory: ${J}`);let X=t(W,$7);return await PX(J,X,{recursive:!0,filter:(Y)=>{let V=F$(Y);return V!==".git"&&V!=="node_modules"}}),await yX(X,Q),X}function zI($,W){if(y1($)&&!W)throw Error(`Plugin is already installed at ${$}. Use --force to replace it.`)}function qI($,W,Z){if(SX(OD(W),{recursive:!0}),!y1(W)){aQ($,W);return}if(!Z)throw Error(`Plugin is already installed at ${W}. Use --force to replace it.`);let Q=t(OD(W),`.replace-${F$(W)}-${Date.now()}-${process.pid}-${Y8(`${W}:${Math.random()}`)}`);aQ(W,Q);try{aQ($,W)}catch(J){if(!y1(W)&&y1(Q))aQ(Q,W);throw J}try{tQ(Q,{recursive:!0,force:!0})}catch{}}function MI($){let W=$.transport;if(W.type==="stdio")return!1;return W.headers!==void 0&&Object.keys(W.headers).length>0}function RI($){let W=$.oauth?.tokens?.access_token;return typeof W==="string"&&W.trim().length>0}function EI($){let W=$.metadata;if(!W||W.source!=="plugin"||typeof W.pluginName!=="string"||typeof W.pluginPath!=="string")return;return{pluginName:W.pluginName,pluginPath:W.pluginPath}}function J7($){let W=new Set($.pluginPaths.map((J)=>a$(J)));if(W.size===0)return[];let Z;try{Z=t0({filePath:$.settingsPath??J0()})}catch{return[]}let Q=[];for(let J of Z){let j=EI(J);if(!j||!W.has(a$(j.pluginPath)))continue;let X=J.transport.type;if(X==="stdio")continue;if(MI(J)||RI(J))continue;Q.push({name:J.name,pluginName:j.pluginName,pluginPath:j.pluginPath,transportType:X,lastError:J.oauth?.lastError})}return Q.sort((J,j)=>J.name.localeCompare(j.name))}async function hX($){let W=$.source.trim(),Z=Q7(W,$.sourceType),Q=$.cwd?.trim(),J=Q?a$(Q):process.cwd(),j=XI(Q?J:void 0),X=$I($.officialPluginsRepo),Y=VI(Z,J,X),V=YI(j,Z,Y),B=BI(Z,J),H=t(j,r6,".tmp"),G=t(H,`${Date.now()}-${process.pid}-${Y8(`${W}:${Math.random()}`)}`),K=$.npmCommand??(process.env.CLINE_NPM_COMMAND?.trim()||"npm"),F=$.force===!0;zI(V,F),await ND(H,{recursive:!0});let A;try{if(Z.type==="npm")A=await UI(Z,G,K);else if(Z.type==="git")A=await DI(Z,G,K);else if(Z.type==="official")A=await _I(Z,G,K,X);else if(Z.type==="remote")A=await TI(Z,G);else A=await OI(Z,G,J,K);let D=(Z.type==="local"||Z.type==="remote")&&A===G?SD(G).map((_)=>`./${CD(wD(G,_))}`):await AI(G,A,B);if(D.length===0)throw Error(`No plugin entry files found for ${W}`);qI(G,V,F);let U={source:W,installPath:V,entryPaths:D.map((_)=>a$(V,_)),mcpSyncFailures:[],mcpOAuthCandidates:[]},f=await f9({pluginPaths:U.entryPaths,cwd:J,workspacePath:J});return U.mcpSyncFailures=f.failures,U.mcpOAuthCandidates=J7({pluginPaths:U.entryPaths}),U}catch(D){throw tQ(G,{recursive:!0,force:!0}),D}}var dD={};w(dD,{writeModelsFileSync:()=>w9,writeModelsFile:()=>C9,toProviderModel:()=>vX,syncStoredProviderRegistration:()=>cX,resolveModelsRegistryPath:()=>h1,registerProviderSettingsProvider:()=>uD,registerCustomProvider:()=>B8,registerConfiguredProvidersFromSettings:()=>P9,readModelsFileSync:()=>n6,readModelsFile:()=>V8,parseModelsFile:()=>mX,ensureCustomProvidersLoadedSync:()=>S9,ensureCustomProvidersLoaded:()=>b9,emptyModelsFile:()=>N9,StoredProviderMetadataSchema:()=>kD,StoredProviderEntrySchema:()=>xX,StoredModelsFileSchema:()=>gX,StoredModelEntrySchema:()=>hD});import{existsSync as NI,mkdirSync as wI,readFileSync as CI,renameSync as PI,rmSync as SI,writeFileSync as bI}from"node:fs";import{mkdir as yI,readFile as hI,rename as kI,rm as II,writeFile as xI}from"node:fs/promises";import{dirname as IX,join as gI}from"node:path";import*as A0 from"@cline/llms";import{ApiFormatSchema as mI,ModelCapabilitySchema as vI,ProviderCapabilitySchema as cI,ProviderClientSchema as uI,ProviderProtocolSchema as dI}from"@cline/shared";import{z as e}from"zod";var kX=e.number().finite().positive().optional().catch(void 0),E9=e.number().finite().nonnegative().optional().catch(void 0),hD=e.object({id:e.string().optional(),name:e.string().optional(),maxTokens:kX,contextWindow:kX,maxInputTokens:kX,capabilities:e.array(vI).optional(),supportsVision:e.boolean().optional(),supportsAttachments:e.boolean().optional(),supportsReasoning:e.boolean().optional(),inputPrice:E9,outputPrice:E9,cacheReadsPrice:E9,cacheWritesPrice:E9,temperature:E9,apiFormat:mI.optional(),isR1FormatRequired:e.boolean().optional()}).passthrough(),kD=e.object({name:e.string(),baseUrl:e.string(),defaultModelId:e.string().optional(),protocol:dI.optional(),client:uI.optional(),capabilities:e.array(cI).optional(),modelsSourceUrl:e.string().optional()}).passthrough(),xX=e.object({provider:kD.optional(),models:e.record(e.string(),hD).optional()}).passthrough(),gX=e.object({version:e.literal(1),providers:e.record(e.string(),xX)}),lI=e.object({version:e.literal(1),providers:e.record(e.string(),e.unknown())}),j7=new Set;function ID($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function h1($){return gI(IX($.getFilePath()),"models.json")}function N9(){return{version:1,providers:{}}}function mX($){let W=lI.safeParse($);if(!W.success)return s("models.json content is not a valid models file envelope; starting from an empty registry"),N9();let Z={};for(let[Q,J]of Object.entries(W.data.providers)){let j=xX.safeParse(J);if(j.success)Z[Q]=j.data;else s(`models.json: dropping invalid entry for provider=${Q}`)}return{version:1,providers:Z}}function n6($){if(!NI($))return N9();try{let W=CI($,"utf8");return mX(JSON.parse(W))}catch{s(`models.json at ${$} exists but is unreadable or invalid JSON; treating as an empty registry`)}return N9()}async function V8($){try{let W=await hI($,"utf8");return mX(JSON.parse(W))}catch(W){if(W?.code!=="ENOENT")s(`models.json at ${$} exists but is unreadable or invalid JSON; treating as an empty registry`)}return N9()}function w9($,W){wI(IX($),{recursive:!0});let Z=gX.parse(W),Q=`${$}.${process.pid}.tmp`;try{bI(Q,`${JSON.stringify(Z,null,2)}
736
+ `,"utf8"),PI(Q,$)}catch(J){throw SI(Q,{force:!0}),J}}async function C9($,W){await yI(IX($),{recursive:!0});let Z=gX.parse(W),Q=`${$}.${process.pid}.tmp`;try{await xI(Q,`${JSON.stringify(Z,null,2)}
737
+ `,"utf8"),await kI(Q,$)}catch(J){throw await II(Q,{force:!0}).catch(()=>{}),J}}function vX($,W){return{id:$,name:W.name??$,supportsAttachments:W.capabilities?.includes("files"),supportsVision:W.capabilities?.includes("images"),supportsReasoning:W.capabilities?.includes("reasoning")||W.thinkingConfig!=null}}function xD($){if(!$||$.length===0)return;let W=new Set;if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("tools"))W.add("tools");return W.size>0?[...W]:void 0}function gD($){let W=new Set;if(!$||$.length===0)return[...W];if($.includes("streaming"))W.add("streaming");if($.includes("tools"))W.add("tools");if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("vision"))W.add("images"),W.add("files");return[...W]}function pI($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function mD($,W){return $??W??"openai-chat"}function vD($,W,Z){return $??Z??(W==="openai-responses"?"openai":"openai-compatible")}function cD($,W,Z){let Q=new Set(W?.capabilities??Z??[]);if(W?.supportsVision!==void 0)if(W.supportsVision)Q.add("images");else Q.delete("images");if(W?.supportsAttachments!==void 0)if(W.supportsAttachments)Q.add("files");else Q.delete("files");if(W?.supportsReasoning!==void 0)if(W.supportsReasoning)Q.add("reasoning");else Q.delete("reasoning");let J=W?.isR1FormatRequired?"r1":W?.apiFormat,j=W?.inputPrice!==void 0||W?.outputPrice!==void 0||W?.cacheReadsPrice!==void 0||W?.cacheWritesPrice!==void 0;return{id:$,name:W?.name??$,...W?.maxTokens!==void 0?{maxTokens:W.maxTokens}:{},...W?.contextWindow!==void 0?{contextWindow:W.contextWindow}:{},...W?.maxInputTokens!==void 0?{maxInputTokens:W.maxInputTokens}:{},...Q.size>0?{capabilities:[...Q]}:{},...W?.temperature!==void 0?{temperature:W.temperature}:{},...J!==void 0?{apiFormat:J}:{},...j?{pricing:{...W?.inputPrice!==void 0?{input:W.inputPrice}:{},...W?.outputPrice!==void 0?{output:W.outputPrice}:{},...W?.cacheReadsPrice!==void 0?{cacheRead:W.cacheReadsPrice}:{},...W?.cacheWritesPrice!==void 0?{cacheWrite:W.cacheWritesPrice}:{}}}:{}}}function rI($,W){for(let[Z,Q]of Object.entries(W??{})){let J=Q.id?.trim()||Z.trim();if(!J)continue;A0.registerModel($,J,cD(J,Q))}}function iI($,W,Z){return{...W??{},id:$,name:W?.name??$,capabilities:W?.capabilities??Z}}function nI($){return Object.assign({},...A0.resolveProviderModelCatalogKeys($).map((Z)=>A0.getGeneratedModelsForProvider(Z)))}function uD($){let W=$.provider.trim();if(!W||A0.isBuiltInProviderId(W))return;let Z=$.baseUrl?.trim();if(!Z)return;let Q=A0.MODEL_COLLECTIONS_BY_PROVIDER_ID[W],J=nI(W),j=gD($.capabilities),X=j.length>0?j:void 0,Y=$.model?.trim(),V={...J,...Q?.models??{}};if(Y)V[Y]=iI(Y,V[Y],X);let B=Object.keys(V).filter(Boolean),H=Y||B[0];if(!H)return;let G=mD($.protocol,Q?.provider.protocol),K=vD($.client,G,Q?.provider.client);A0.registerProvider({provider:{id:W,name:Q?.provider.name??ID(W),description:Q?.provider.description,protocol:G,client:K,baseUrl:Z,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:H,capabilities:xD($.capabilities)??Q?.provider.capabilities,source:"file"},models:V})}function P9($){for(let W of Object.values($.providers))uD(W.settings)}function B8($,W){let Z=W.models??{};if(!pI(W.provider)){rI($,Z);return}let Q=gD(W.provider.capabilities),J=Object.entries(Z).map(([B,H])=>({id:H.id?.trim()||B.trim(),model:H})).filter(({id:B})=>B.length>0),j=W.provider.defaultModelId?.trim()||J[0]?.id||"default",X=mD(W.provider.protocol,void 0),Y=vD(W.provider.client,X,void 0),V=Object.fromEntries(J.map(({id:B,model:H})=>[B,{...cD(B,H,Q.length>0?Q:void 0),status:"active"}]));A0.registerProvider({provider:{id:$,name:W.provider.name.trim()||ID($),protocol:X,client:Y,baseUrl:W.provider.baseUrl,modelsSourceUrl:W.provider.modelsSourceUrl,defaultModelId:j,capabilities:xD(W.provider.capabilities),source:"file"},models:V})}function cX($,W,Z){let Q=Z?.models??{},J=new Set;for(let[Y,V]of Object.entries(W?.models??{})){if(Object.hasOwn(Q,Y))continue;let B=V.id?.trim()||Y.trim();if(B)J.add(B),A0.unregisterModel($,B)}if(!Z)return;let j=A0.getProviderCollectionSync($);B8($,Z);let X=A0.getProviderCollectionSync($);if(j&&X&&X!==j){let Y=Object.fromEntries(Object.entries(j.models).filter(([V])=>!J.has(V)));A0.registerProvider({...X,models:{...Y,...X.models}})}}function S9($){let W=h1($);if(j7.has(W))return;let Z=n6(W);for(let[Q,J]of Object.entries(Z.providers))B8(Q,J);j7.add(W)}async function b9($){let W=h1($);if(j7.has(W))return;let Z=await V8(W);for(let[Q,J]of Object.entries(Z.providers))B8(Q,J);j7.add(W)}var tD={};w(tD,{updateLocalProvider:()=>V7,saveLocalProviderSettings:()=>nX,saveLocalProviderOAuthCredentials:()=>tX,resolveLocalClineAuthToken:()=>$Y,refreshProviderModelsFromSource:()=>aX,normalizeOAuthProvider:()=>oX,markLocalProviderEnabled:()=>pX,loginLocalProvider:()=>sX,loginAndSaveLocalProviderOAuthCredentials:()=>eX,listLocalProviders:()=>rX,getLocalProviderModels:()=>iX,ensureCustomProvidersLoaded:()=>b9,deleteLocalProvider:()=>B7,addLocalProvider:()=>lX});import*as k0 from"@cline/llms";var pD="cline-pass";function aI($){return $.apiKey??$.auth?.apiKey}function oI($){return($.auth?.accessToken?.trim()??"").length>0}function rD($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function sI($){let W=$.split(/\s+/).filter(Boolean);if(W.length===0)return"?";if(W.length===1)return W[0].slice(0,2).toUpperCase();return`${W[0][0]}${W[1][0]}`.toUpperCase()}function tI($){let W=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Z=0;for(let Q of $)Z=Z*31+Q.charCodeAt(0)>>>0;return W[Z%W.length]}function iD($){return Object.entries($).sort(([W],[Z])=>W.localeCompare(Z)).map(([W,Z])=>vX(W,Z))}async function eI($,W){let Z=await k0.getModelsForProvider($),Q=$===pD;if(!W&&!Q)return Z;let J=await R5($,{loadLatestOnInit:Q,loadPrivateOnAuth:!0,failOnError:!1},W);if($==="litellm"&&J?.knownModels)return J.knownModels;if(Q&&J?.knownModels)return J.knownModels;return J?.knownModels?{...Z,...J.knownModels}:Z}function uX($){return[...new Set(($??[]).map((W)=>W.trim()).filter(Boolean))]}function $x($){if(!$?.length)return;return[...new Set($)]}function Wx($,W){return $x([...$??[],...W??[]])}function Zx($){let W=$?.popularRank;return typeof W==="number"&&Number.isFinite(W)?W:Number.MAX_SAFE_INTEGER}function Qx($){if(!$||typeof $!=="object")return!1;let W=$;return typeof W.path==="string"&&W.path.trim().length>0&&typeof W.label==="string"&&W.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(W.type))}function Jx($){let W=$?.configFields;if(!Array.isArray(W))return;return W.filter(Qx)}var X7={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},lD={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function jx($){if(!$)return[X7];if($.source!=="system")return $.baseUrl?[X7,lD]:[X7];let W=[];if($.env?.length)W.push(X7);if($.baseUrl)W.push(lD);return W}function Xx($,W){return W.split(".").reduce((Z,Q)=>{if(!Z||typeof Z!=="object")return;return Z[Q]},$)}function Yx($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function Vx($,W,Z){if(!$?.length)return;let Q={};for(let J of $){let X=Yx(J.path==="baseUrl"&&W?.baseUrl===void 0?Z?.baseUrl:Xx(W,J.path))??J.defaultValue;if(X!==void 0)Q[J.path]=X}return Q}function nD($){let W=Object.entries($??{}).filter(([Z])=>Z.trim().length>0);return W.length>0?Object.fromEntries(W):void 0}function dX($,W){let Z=W?.includes("vision")??!1,Q=W?.includes("reasoning")??!1;return Object.fromEntries($.map((J)=>[J,{id:J,name:J,supportsVision:Z,supportsAttachments:Z,supportsReasoning:Q}]))}async function aD($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let W=$.modelsSourceUrl?await wZ($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...W])]}function oD($,W){let Z=$.read(),Q=!1;if(Z.providers[W])delete Z.providers[W],Q=!0;if(Z.lastUsedProvider===W)delete Z.lastUsedProvider,Q=!0;if(Q)$.write(Z);k0.unregisterProvider(W)}async function lX($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=W.baseUrl.trim(),J=W.apiKey?.trim()??"";if(!Q&&!J){let A=h1($);if((await V8(A)).providers[Z]){let U=await B7($,{providerId:Z});return{providerId:Z,settingsPath:U.settingsPath,modelsPath:U.modelsPath,modelsCount:0}}return oD($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:0}}if(k0.hasProvider(Z))throw Error(`provider "${Z}" already exists`);let j=W.name.trim();if(!j)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let X=uX(W.models),Y=W.modelsSourceUrl?.trim(),V=await aD({providerId:Z,explicitModels:X,modelsSourceUrl:Y,shouldRecompute:!0});if(V.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let B=W.defaultModelId?.trim()&&V.includes(W.defaultModelId.trim())?W.defaultModelId.trim():V[0],H=W.capabilities?.length?[...new Set(W.capabilities)]:void 0,G=nD(W.headers);$.saveProviderSettings({provider:Z,apiKey:J||void 0,baseUrl:Q,headers:G,timeout:W.timeoutMs,model:B,protocol:W.protocol,client:W.client},{setLastUsed:!1});let K=h1($),F=await V8(K);return F.providers[Z]={provider:{name:j,baseUrl:Q,defaultModelId:B,protocol:W.protocol,client:W.client,capabilities:H,modelsSourceUrl:Y},models:dX(V,H)},await C9(K,F),B8(Z,F.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:K,modelsCount:V.length}}async function V7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=h1($),J=await V8(Q),j=J.providers[Z];if(!j){let O=$.getProviderSettings(Z);if(!O)throw Error(`provider "${Z}" does not exist`);let T=W.modelsSourceUrl?.trim(),L=uX(W.models)[0]??O.model?.trim();if(!L&&!T)throw Error(`provider "${Z}" cannot be updated because no model is configured`);j={provider:{name:W.name?.trim()||rD(Z),baseUrl:W.baseUrl?.trim()??O.baseUrl?.trim()??"",defaultModelId:L,protocol:O.protocol,client:O.client,capabilities:O.capabilities},models:L?dX([L],O.capabilities):{}}}if(!j.provider)throw Error(`provider "${Z}" cannot be updated because it is a model overlay (no provider metadata)`);let X=W.name?.trim()??j.provider.name.trim();if(!X)throw Error("name is required");let Y=W.baseUrl?.trim()??j.provider.baseUrl.trim();if(!Y)throw Error("baseUrl is required");let V=W.capabilities===void 0?j.provider.capabilities:W.capabilities===null?void 0:[...new Set(W.capabilities)],B=W.protocol===void 0?j.provider.protocol:W.protocol??void 0,H=W.client===void 0?j.provider.client:W.client??void 0,G=uX(W.models),K=W.modelsSourceUrl===void 0?j.provider.modelsSourceUrl:W.modelsSourceUrl?.trim()||void 0,F=W.models!==void 0||W.modelsSourceUrl!==void 0&&!!K,A=Object.keys(j.models??{}).map((O)=>O.trim()).filter(Boolean),D=await aD({providerId:Z,explicitModels:G,modelsSourceUrl:K,fallbackModelIds:A,shouldRecompute:F});if(D.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let U=W.defaultModelId===void 0?j.provider.defaultModelId?.trim():W.defaultModelId?.trim(),f=U&&D.includes(U)?U:D[0],R={...$.getProviderSettings(Z)??{},provider:Z,baseUrl:Y,model:f};if(B)R.protocol=B;else delete R.protocol;if(H)R.client=H;else delete R.client;if(W.apiKey!==void 0){let O=W.apiKey?.trim()??"";if(O)R.apiKey=O;else delete R.apiKey}if(W.headers!==void 0){let O=nD(W.headers);if(O)R.headers=O;else delete R.headers}if(W.timeoutMs!==void 0)if(typeof W.timeoutMs==="number")R.timeout=W.timeoutMs;else delete R.timeout;return $.saveProviderSettings(R,{setLastUsed:!1}),J.providers[Z]={provider:{name:X,baseUrl:Y,defaultModelId:f,protocol:B,client:H,capabilities:V,modelsSourceUrl:K},models:dX(D,V)},await C9(Q,J),B8(Z,J.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q,modelsCount:D.length}}async function B7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=h1($),J=await V8(Q);if(!J.providers[Z])throw Error(`provider "${Z}" does not exist`);return delete J.providers[Z],await C9(Q,J),k0.unregisterProvider(Z),oD($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q}}function pX($,W,Z={}){let Q=W.trim();if(!Q)throw Error("providerId is required");let J=$.read().providers[Q]?.settings;return $.saveProviderSettings({...J??{},provider:Q},{setLastUsed:!1,tokenSource:Z.tokenSource}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function rX($,W={}){let Z=$.read(),Q=k0.getProviderIds(),J=await Promise.all(Q.map(async(X)=>{let[Y,V]=await Promise.all([k0.getProvider(X),k0.getModelsForProvider(X)]),B=iD(V),H=Z.providers[X]?.settings,G=$.getProviderSettings(X),K=Y?.name??rD(X),F=Wx(Y?.capabilities,G?.capabilities),A=Jx(Y?.metadata)??jx(Y);return{provider:{id:X,name:K,models:B.length,color:tI(X),letter:sI(K),enabled:Boolean(H),apiKey:G?aI(G):void 0,oauthAccessTokenPresent:G?oI(G):void 0,baseUrl:G?.baseUrl??Y?.baseUrl,defaultModelId:Y?.defaultModelId,protocol:G?.protocol??Y?.protocol,client:G?.client??Y?.client,capabilities:F,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:A,configValues:Vx(A,G,Y),modelList:B},rank:Zx(Y?.metadata)}}));J.sort((X,Y)=>{if(X.rank!==Y.rank)return X.rank-Y.rank;return X.provider.name.localeCompare(Y.provider.name)||X.provider.id.localeCompare(Y.provider.id)});let j=J.map((X)=>X.provider);if(W.isClinePassEnabled!==!0)j=j.filter((X)=>X.id!==pD);return{providers:j,settingsPath:$.getFilePath()}}async function iX($,W){let Z=$.trim(),Q=await eI(Z,W),J=iD(Q);return{providerId:Z,models:J}}function Y7($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function sD($,W){if(!Y7(W))return Y7($)?{...$}:void 0;let Z=Y7($)?{...$}:{};for(let[Q,J]of Object.entries(W)){if(J==null||J===""){delete Z[Q];continue}if(Y7(J)){let j=sD(Z[Q],J);if(j&&Object.keys(j).length>0)Z[Q]=j;else delete Z[Q];continue}Z[Q]=J}return Object.keys(Z).length>0?Z:void 0}function nX($,W){let Z=W.providerId.trim();if(W.enabled===!1){let j=$.read();if(delete j.providers[Z],j.lastUsedProvider===Z)delete j.lastUsedProvider;return $.write(j),{providerId:Z,enabled:!1,settingsPath:$.getFilePath()}}let J={...$.getProviderSettings(Z)??{},provider:Z};for(let j of["apiKey","baseUrl","model","region"])if(Object.hasOwn(W,j)&&typeof W[j]==="string")if(W[j].trim().length===0)delete J[j];else J[j]=W[j];for(let j of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(W,j))J[j]=W[j];for(let j of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(W,j)&&W[j]!=null){let X=sD(J[j],W[j]);if(X)J[j]=X;else delete J[j]}return $.saveProviderSettings(J,{setLastUsed:!1}),{providerId:Z,enabled:!0,settingsPath:$.getFilePath()}}async function aX($,W){let Z=W.trim(),Q=$.getProviderSettings(Z),j=k0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Z]?.provider,X=Q?.baseUrl?.trim()||j?.baseUrl?.trim(),Y=CZ(X,j?.baseUrl,j?.modelsSourceUrl);if(!Q||!j||!X||!Y)return{providerId:Z,refreshed:!1};let V=await V7($,{providerId:Z,name:j.name,baseUrl:X,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:Y,protocol:Q.protocol??j.protocol??null,client:Q.client??j.client??null,capabilities:Q.capabilities??null});return{providerId:Z,refreshed:!0,modelsCount:V.modelsCount}}function oX($){let W=$.trim().toLowerCase(),Z=H0(W);if(Z)return Z.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function sX($,W,Z,Q){let J=H0($);if(!J)throw Error(`provider "${$}" does not support OAuth login`);let j=D6({onPrompt:async(X)=>X.defaultValue??"",openUrl:Z,onOpenUrlError:({error:X})=>{throw X instanceof Error?X:Error(String(X))}});return J.login({settings:W,callbacks:j,telemetry:Q})}function tX($,W,Z,Q,J){return F2({manager:$,providerId:W,settings:Z,credentials:Q,setLastUsed:J?.setLastUsed})}async function eX($,W,Z,Q){let J=D6({onPrompt:async(j)=>j.defaultValue??"",openUrl:Z,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return C4($,W,{callbacks:J,telemetry:Q})}function $Y($){let W=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return W&&W.length>0?W:void 0}var eD={};w(eD,{getProviderConfigFields:()=>WY});import*as H7 from"@cline/llms";var Bx=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],Hx={"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 Gx($,W){let Z={};for(let Q of Bx){let J=$[Q],j=W[Q];if(J||j)Z[Q]={...J,...j}}return Z}function Kx($){let W=Hx[$.providerId];if(!W)return $;return{...$,description:W.description??$.description,fields:W.mode==="replace"?W.fields:Gx($.fields,W.fields)}}var Fx=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function Ax($,W){if(!W?.provider.baseUrl)return!1;if(W.provider.source!=="system")return!0;return Fx.has($)}function WY($){let W=H7.normalizeProviderId($);if(K2(W))return{providerId:W,authMethod:"oauth",fields:{}};let Z=H7.MODEL_COLLECTIONS_BY_PROVIDER_ID[W];if(Z?.provider.capabilities?.includes("local-auth"))return{providerId:W,authMethod:"local",fields:{}};let Q=Z?.provider.baseUrl,J={apiKey:{}};if(Ax(W,Z))J.baseUrl={defaultValue:Q};return Kx({providerId:W,authMethod:"api-key",fields:J})}var Q_={};w(Q_,{resolveLegacyClineAuth:()=>JY,migrateLegacyProviderSettings:()=>y9});import{existsSync as Ux,readFileSync as Dx}from"node:fs";import{dirname as _x,join as ZY}from"node:path";import*as a6 from"@cline/llms";import{resolveClineDataDir as fx}from"@cline/shared/storage";var G7="openai",Z_=a6.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,$_=128000;function JY($){let W=$?.trim();if(!W)return;try{let Z=JSON.parse(W);if(!Z)return;let Q=typeof Z.expiresAt==="number"&&Number.isFinite(Z.expiresAt)?Z.expiresAt<10000000000?Z.expiresAt*1000:Z.expiresAt:void 0;return{accessToken:Z.idToken,refreshToken:Z.refreshToken,expiresAt:Q,accountId:Z.userInfo?.id}}catch{return}}function b($){let W=$?.trim();return W?W:void 0}function Lx($){return $==="credentials"?"iam":$}function W_($){if(!Ux($))return;try{let W=Dx($,"utf8"),Z=JSON.parse(W);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}function Tx($){let W=$.dataDir??fx(),Z=$.globalStatePath??ZY(W,"globalState.json"),Q=$.secretsPath??ZY(W,"secrets.json"),J=W_(Z),j=W_(Q);if(!J&&!j)return;return{globalState:J??{},secrets:j??{}}}function QY($){if($===G7)return Z_;return $}function Ox($,W,Z,Q){let J=Z==="plan"?"planMode":"actMode",j=W===Q?b(Z==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,Y={openrouter:`${J}OpenRouterModelId`,cline:`${J}ClineModelId`,openai:`${J}OpenAiModelId`,ollama:`${J}OllamaModelId`,lmstudio:`${J}LmStudioModelId`,litellm:`${J}LiteLlmModelId`,requesty:`${J}RequestyModelId`,together:`${J}TogetherModelId`,fireworks:`${J}FireworksModelId`,sapaicore:`${J}SapAiCoreModelId`,groq:`${J}GroqModelId`,baseten:`${J}BasetenModelId`,huggingface:`${J}HuggingFaceModelId`,"huawei-cloud-maas":`${J}HuaweiCloudMaasModelId`,oca:`${J}OcaModelId`,aihubmix:`${J}AihubmixModelId`,hicap:`${J}HicapModelId`,nousResearch:`${J}NousResearchModelId`,"vercel-ai-gateway":`${J}VercelAiGatewayModelId`}[W];return(Y?b(typeof $[Y]==="string"?$[Y]:void 0):void 0)??j}function zx($,W,Z){let Q=Z==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,J=[...W==="oca"?[$.actModeOcaReasoningEffort,$.planModeOcaReasoningEffort]:[],...W==="gemini"?[$.geminiActModeThinkingLevel,$.geminiPlanModeThinkingLevel]:[],$.actModeReasoningEffort,$.planModeReasoningEffort].map(b).find(Boolean),j=J==="none"||J==="low"||J==="medium"||J==="high"||J==="xhigh"?J:void 0,X=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!j&&X===void 0)return;return{...j?{effort:j}:{},...X!==void 0?{budgetTokens:X}:{}}}function qx($){let W=$["openai-codex-oauth-credentials"];if(!W)return;try{let Z=JSON.parse(W),Q=b(Z.access_token),J=b(Z.refresh_token),j=b(Z.accountId);if(!Q&&!J&&!j)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...J?{refreshToken:J}:{},...j?{accountId:j}:{}}}}catch{return}}function Mx($){let W=a6.getGeneratedModelsForProvider($),Q=a6.getProviderCollectionSync($)?.provider.defaultModelId;if(Q&&W[Q])return Q;return Object.keys(W)[0]??void 0}function Rx($,W,Z,Q){let J=QY($),j=b(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),X=Ox(W,$,Q,j)??Mx(J),Y=zx(W,J,Q),V=typeof W.requestTimeoutMs==="number"&&Number.isInteger(W.requestTimeoutMs)&&W.requestTimeoutMs>0?W.requestTimeoutMs:void 0,B={anthropic:Z.apiKey,cline:Z.clineApiKey,openai:Z.openAiApiKey,"openai-native":Z.openAiNativeApiKey,openrouter:Z.openRouterApiKey,bedrock:Z.awsBedrockApiKey,gemini:Z.geminiApiKey,ollama:Z.ollamaApiKey,deepseek:Z.deepSeekApiKey,requesty:Z.requestyApiKey,together:Z.togetherApiKey,fireworks:Z.fireworksApiKey,qwen:Z.qwenApiKey,doubao:Z.doubaoApiKey,mistral:Z.mistralApiKey,litellm:Z.liteLlmApiKey,asksage:Z.asksageApiKey,xai:Z.xaiApiKey,moonshot:Z.moonshotApiKey,zai:Z.zaiApiKey,huggingface:Z.huggingFaceApiKey,nebius:Z.nebiusApiKey,sambanova:Z.sambanovaApiKey,cerebras:Z.cerebrasApiKey,groq:Z.groqApiKey,"huawei-cloud-maas":Z.huaweiCloudMaasApiKey,baseten:Z.basetenApiKey,"vercel-ai-gateway":Z.vercelAiGatewayApiKey,dify:Z.difyApiKey,minimax:Z.minimaxApiKey,hicap:Z.hicapApiKey,aihubmix:Z.aihubmixApiKey,nousResearch:Z.nousResearchApiKey,oca:Z.ocaApiKey},H={};if($==="openai-codex")Object.assign(H,qx(Z));if($==="cline")try{let f=b(Z["cline:clineAccountId"]);if(f)H.auth={...H.auth??{},...JY(f)}}catch{}if($===G7&&W.openAiHeaders)H.headers=W.openAiHeaders;if($==="bedrock"){let f=Lx(W.awsAuthentication),_=f==="profile"||W.awsUseProfile===!0;H.aws={accessKey:b(Z.awsAccessKey),secretKey:b(Z.awsSecretKey),sessionToken:b(Z.awsSessionToken),region:b(W.awsRegion),authentication:f,profile:_?b(W.awsProfile):void 0,usePromptCache:W.awsBedrockUsePromptCache,useCrossRegionInference:W.awsUseCrossRegionInference,useGlobalInference:W.awsUseGlobalInference,endpoint:b(W.awsBedrockEndpoint),customModelBaseId:b(Q==="plan"?W.planModeAwsBedrockCustomModelBaseId:W.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")H.gcp={projectId:b(W.vertexProjectId),region:b(W.vertexRegion)};if($===G7&&(W.azureApiVersion||W.azureIdentity!==void 0))H.azure={apiVersion:b(W.azureApiVersion),useIdentity:W.azureIdentity};if($==="sapaicore"){let f=W.sapAiCoreUseOrchestrationMode??!0;H.sap={clientId:b(Z.sapAiCoreClientId),clientSecret:b(Z.sapAiCoreClientSecret),tokenUrl:b(W.sapAiCoreTokenUrl),resourceGroup:b(W.sapAiResourceGroup),deploymentId:f?void 0:b(Q==="plan"?W.planModeSapAiCoreDeploymentId:W.actModeSapAiCoreDeploymentId),useOrchestrationMode:f}}if($==="oca"){H.oca={mode:W.ocaMode};let f=b(Z.ocaRefreshToken);if(f)H.auth={...H.auth??{},refreshToken:f}}if($==="qwen")H.apiLine=W.qwenApiLine;if($==="moonshot")H.apiLine=W.moonshotApiLine;if($==="zai")H.apiLine=W.zaiApiLine;if($==="minimax")H.apiLine=W.minimaxApiLine;let G={anthropic:W.anthropicBaseUrl,openai:W.openAiBaseUrl,ollama:W.ollamaBaseUrl,lmstudio:W.lmStudioBaseUrl,litellm:W.liteLlmBaseUrl,gemini:W.geminiBaseUrl,requesty:W.requestyBaseUrl,asksage:W.asksageApiUrl,dify:W.difyBaseUrl,oca:W.ocaBaseUrl,aihubmix:W.aihubmixBaseUrl,sapaicore:W.sapAiCoreBaseUrl},K=b(B[$]),F=b(G[$]),A={provider:J,...K?{apiKey:K}:{},...X?{model:X}:{},...F?{baseUrl:F}:{},...Y?{reasoning:Y}:{},...V?{timeout:V}:{},...H},D=F6.safeParse(A);if(!D.success)return;return Object.keys(A).filter((f)=>f!=="provider").length>0?D.data:void 0}function Ex($,W){if($!==Z_)return;if(!W.baseUrl||!W.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:W.baseUrl,defaultModelId:W.model},models:{[W.model]:{id:W.model,name:W.model,contextWindow:$_,maxInputTokens:$_,capabilities:["streaming","tools","images"]}}}}function Nx($,W){let Z=new Set;for(let J of[$.actModeApiProvider,$.planModeApiProvider]){let j=b(J);if(j)Z.add(j)}if(b(W.apiKey))Z.add("anthropic");if(b(W.openRouterApiKey))Z.add("openrouter");if(b(W.openAiApiKey))Z.add(G7);if(b(W.openAiNativeApiKey))Z.add("openai-native");if(b(W["openai-codex-oauth-credentials"]))Z.add("openai-codex");if(b(W.geminiApiKey))Z.add("gemini");if(b(W.ollamaApiKey))Z.add("ollama");if(b(W.awsAccessKey)||b(W.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||b($.awsProfile))Z.add("bedrock");if(b($.vertexProjectId)||b($.vertexRegion))Z.add("vertex");if(b(W.clineApiKey))Z.add("cline");let Q=JY(b(W["cline:clineAccountId"]));if(Q?.accessToken||Q?.refreshToken||Q?.accountId)Z.add("cline");if(b(W.ocaApiKey))Z.add("oca");if(b(W.sapAiCoreClientId)||b(W.sapAiCoreClientSecret)||b($.sapAiCoreTokenUrl)||b($.sapAiCoreBaseUrl)||b($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Z.add("sapaicore");return Z}function y9($){let W=$.providerSettingsManager.read(),Z=Tx($);if(!Z)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let{globalState:Q,secrets:J}=Z,j=Q.mode==="plan"?"plan":"act",X=Nx(Q,J),Y=v$();Y.providers={...W.providers},Y.lastUsedProvider=W.lastUsedProvider;let V=new Date().toISOString(),B=0,H=ZY(_x($.providerSettingsManager.getFilePath()),"models.json"),G=n6(H),K=0;for(let D of X){let U=QY(D);if(Y.providers[U])continue;let f=Rx(D,Q,J,j);if(!f)continue;Y.providers[U]={settings:f,updatedAt:V,tokenSource:"migration"},B+=1;let _=Ex(U,f);if(_&&!G.providers[U])G.providers[U]=_,K+=1}if(B===0&&K===0)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let F=b(j==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),A=F?QY(F):void 0;if(Y.lastUsedProvider=W.lastUsedProvider??(A&&Y.providers[A]?A:Object.keys(Y.providers)[0]),$.providerSettingsManager.write(Y),K>0)w9(H,G);return{migrated:B>0||K>0,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider}}yQ();z0();LW();var J_={};w(J_,{SessionVersioningService:()=>o$,SessionVersioningError:()=>c0});class c0 extends Error{code;constructor($,W){super(W);this.code=$;this.name="SessionVersioningError"}}function wx($){let W=$.sessionId.trim();if(!W)throw new c0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new c0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new c0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new c0("invalid_restore","checkpointRunCount must be a positive integer");return W}class o${async restoreCheckpoint($){let W=$.restore?.messages!==!1,Z=$.restore?.workspace!==!1,Q=wx({sessionId:$.sessionId,restoreMessages:W,restoreWorkspace:Z,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),J=await $.getSession(Q);if(!J)throw new c0("session_not_found",`Session ${Q} not found`);let j=W?await $.readMessages(Q):void 0;if(W&&j?.length===0)throw new c0("session_messages_not_found",`No messages found for session ${Q}`);let X=WX({session:J,messages:j,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:W});if(Z)await($.applyWorkspaceCheckpoint??ZX)(X.cwd,X.checkpoint);let Y=N1({session:J,messages:j});if(!W)return{checkpoint:X.checkpoint,sourceSnapshot:Y};let V=ej(J,$.checkpointRunCount),B=$.restore?.omitCheckpointMessageFromSession?$X(j??[],$.checkpointRunCount):X.messages??[],H={sourceSession:J,sourceMessages:j,sourceSnapshot:Y,plan:X,restoredCheckpointMetadata:V,initialMessages:B,restoreMessages:W,restoreWorkspace:Z,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new c0("invalid_restore","start is required when restore.messages is true");let G=$.buildStartInput?await $.buildStartInput(H,$.start):$.start,K=await $.startSession(G),F=$.getStartedSessionId?.(K);if(F)await($.retainCheckpointRefs??dK)(X.cwd,F,V?.history??[]);let A=F&&$.readRestoredSession?await $.readRestoredSession(F):void 0;return{sessionId:F,startResult:K,messages:X.messages,checkpoint:X.checkpoint,sourceSnapshot:Y,...A?{restoredSnapshot:N1({session:A,messages:B})}:{}}}}var j_={};w(j_,{FileTeamPersistenceStore:()=>K7});import{appendFileSync as Cx,existsSync as jY,mkdirSync as Px,readFileSync as Sx,renameSync as bx,unlinkSync as yx,writeFileSync as hx}from"node:fs";import{join as XY}from"node:path";import{resolveTeamDataDir as kx}from"@cline/shared/storage";function Ix($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class K7{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let W=Ix($.teamName),Z=$.baseDir?.trim()||kx();this.dirPath=XY(Z,W),this.statePath=XY(this.dirPath,"state.json"),this.taskHistoryPath=XY(this.dirPath,"task-history.jsonl")}loadState(){if(!jY(this.statePath))return;try{let $=Sx(this.statePath,"utf8"),W=JSON.parse($);if(W.version!==1||!W.teamState)return;for(let Z of W.teammates??[])this.teammateSpecs.set(Z.agentId,Z);return NU(W.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let W={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Z=`${this.statePath}.tmp`;hx(Z,`${JSON.stringify(W,null,2)}
738
+ `,"utf8"),bx(Z,this.statePath)}appendTaskHistory($){let W={};switch($.type){case"team_task_updated":W=$.task;break;case"team_message":W={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":W={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":W={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":W={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":W={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),Cx(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:W})}
739
+ `,"utf8")}ensureDir(){if(!jY(this.dirPath))Px(this.dirPath,{recursive:!0})}hasPersistableState($){let W=$.exportState();if(this.teammateSpecs.size>0)return!0;if(W.members.some((Z)=>Z.role==="teammate"))return!0;return W.tasks.length>0||W.mailbox.length>0||W.missionLog.length>0}clearPersistedState(){if(jY(this.statePath))yx(this.statePath)}}var X_={};w(X_,{ChatViewStateSchema:()=>YY,ChatSummarySchema:()=>_7,ChatSessionStatusSchema:()=>A7,ChatSessionConfigSchema:()=>F7,ChatMessageSchema:()=>D7,ChatMessageRoleSchema:()=>U7});import{z as I}from"zod";var F7=I.object({workspaceRoot:I.string().min(1),cwd:I.string().optional(),provider:I.string().min(1),model:I.string().min(1),mode:I.enum(["act","plan"]).default("act"),apiKey:I.string(),systemPrompt:I.string().optional(),rules:I.string().optional(),maxIterations:I.number().int().positive().optional(),enableTools:I.boolean(),enableSpawn:I.boolean().optional(),enableTeams:I.boolean().optional(),autoApproveTools:I.boolean().optional(),missionStepInterval:I.number().int().positive().optional(),missionTimeIntervalMs:I.number().int().positive().optional()}),A7=I.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),U7=I.enum(["user","assistant","tool","system","status","error"]),D7=I.object({id:I.string().min(1),sessionId:I.string().nullable(),role:U7,content:I.string(),createdAt:I.number().int().nonnegative(),meta:I.object({stream:I.enum(["stdout","stderr"]).optional(),toolName:I.string().optional(),iteration:I.number().int().nonnegative().optional(),agentId:I.string().optional(),conversationId:I.string().optional(),hookEventName:I.string().optional(),inputTokens:I.number().int().nonnegative().optional(),outputTokens:I.number().int().nonnegative().optional(),checkpoint:I.object({ref:I.string(),createdAt:I.number().int().nonnegative(),runCount:I.number().int().positive(),kind:I.enum(["stash","commit"]).optional()}).optional()}).optional()}),_7=I.object({toolCalls:I.number().int().nonnegative(),tokensIn:I.number().int().nonnegative(),tokensOut:I.number().int().nonnegative()}),YY=I.object({sessionId:I.string().nullable(),status:A7,config:F7,messages:I.array(D7),rawTranscript:I.string(),error:I.string().nullable(),summary:_7});var Y_={};w(Y_,{CORE_BUILD_VERSION:()=>VY});var VY=R8;import{Agent as yg,createAgentRuntime as hg}from"@cline/agents";var V_={};w(V_,{fetchClineRecommendedModels:()=>HY,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>f7});import{getClineEnvironmentConfig as xx}from"@cline/shared";var gx=5000,f7={recommended:[{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",description:"Most intelligent model for agents and coding",tags:["BEST"]},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",description:"Strong coding and agent performance",tags:["NEW"]},{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"1M context window, strong coding performance",tags:["NEW"]},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",description:"OpenAI's latest with strong coding abilities",tags:["NEW"]}],free:[{id:"kwaipilot/kat-coder-pro",name:"KwaiKAT Kat Coder Pro",description:"Advanced agentic coding model",tags:["FREE"]},{id:"arcee-ai/trinity-large-preview:free",name:"Arcee AI Trinity Large Preview",description:"Advanced large preview model",tags:["FREE"]}],clinePass:[]};function mx($){return{recommended:$.recommended.map((W)=>({...W,tags:[...W.tags]})),free:$.free.map((W)=>({...W,tags:[...W.tags]})),clinePass:$.clinePass.map((W)=>({...W,tags:[...W.tags]}))}}function BY($){if(!$||typeof $!=="object")return null;let W=$;if(typeof W.id!=="string"||W.id.length===0)return null;return{id:W.id,name:typeof W.name==="string"&&W.name.length>0?W.name:W.id,description:typeof W.description==="string"?W.description:"",tags:Array.isArray(W.tags)?W.tags.filter((Z)=>typeof Z==="string"):[]}}function vx($){if(!$||typeof $!=="object")return null;let W=$,Z=Array.isArray(W.recommended)?W.recommended:[],Q=Array.isArray(W.free)?W.free:[],J=Array.isArray(W.clinePass)?W.clinePass:[],j=Z.map(BY).filter((V)=>V!==null),X=Q.map(BY).filter((V)=>V!==null),Y=J.map(BY).filter((V)=>V!==null);if(j.length===0&&X.length===0&&Y.length===0)return null;return{recommended:j,free:X,clinePass:Y}}function cx($){let W=$.baseUrl?.trim();if(W)return W;let Z=xx().apiBaseUrl;try{return($.providerSettingsManager??new k1).getProviderSettings("cline")?.baseUrl?.trim()||Z}catch{return Z}}async function ux($,W,Z){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await $(W,{signal:Q.signal})}finally{clearTimeout(J)}}async function HY($={}){try{let W=cx($),Z=$.fetchImpl??fetch,Q=await ux(Z,`${W}/api/v1/ai/cline/recommended-models`,$.timeoutMs??gx);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let J=await Q.json(),j=vx(J);if(j)return j}catch{}return mx(f7)}var B_={};w(B_,{loadLlmsConfigFromFile:()=>KY,defineLlmsConfig:()=>GY});import{readFile as dx}from"node:fs/promises";import lx from"node:path";function GY($){return $}async function KY($){let W=lx.resolve($),Z=await dx(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(J){let j=J instanceof Error?J.message:String(J);throw Error(`Failed to parse JSON config at "${W}": ${j}`)}return px(Q,W)}function px($,W){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${W}": expected an object.`);let Q=$.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${W}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${W}": "providers" cannot be empty.`);return $}var U_={};w(U_,{createLlmsSdk:()=>AY,DefaultLlmsSdk:()=>h9});import{BUILT_IN_PROVIDER_IDS as K_,createHandler as nx,createHandlerAsync as ax,getProviderCollection as ox,hasProvider as F_,registerAsyncHandler as sx,registerHandler as tx,registerModel as ex,registerProvider as A_}from"@cline/llms";function H_($){return $?{...$}:{}}function rx($,W){if($)return $;if(!W)return;let Z=globalThis.process;if(!Z?.env)return;return Z.env[W]}function ix($,W){if(!W.length)throw Error(`Provider "${$}" must include at least one model.`)}function G_($){let W=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:W,defaultModel:$.collection.provider.defaultModelId,modelCount:W.length}}class FY{providers=new Map;register($){ix($.id,$.models);let W=$.defaultModel??$.models[0];if(!W)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(W))throw Error(`Default model "${W}" is not included in configured models for "${$.id}".`);let Z=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Z?.models??[],...$.models]),defaultModel:W,defaults:{...Z?.defaults??{},...H_($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:rx($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...H_($.settings)}})}registerModel($,W){let Z=this.providers.get($);if(!Z){this.providers.set($,{id:$,models:new Set([W]),defaultModel:W,defaults:{}});return}Z.models.add(W)}createHandlerConfig($){let W=this.require($.providerId),Z=$.modelId??W.defaultModel;if(!W.models.has(Z))throw Error(`Model "${Z}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Z,...W.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,W){return this.providers.get($)?.models.has(W)??!1}require($){let W=this.providers.get($);if(!W)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return W}}class h9{configuredProviders=new FY;constructor($){this.applyConfig($)}createHandler($){return nx(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return ax(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(A_($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)tx($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)sx($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let W=$.exposeModels??Object.keys($.models),Z=$.defaultModel??W[0];if(!Z)throw Error(`Provider "${$.id}" must define a default model.`);A_({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Z,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:W,defaultModel:Z,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){ex($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...K_]}async getBuiltInProviders(){return(await Promise.all(K_.map((W)=>ox(W)))).filter((W)=>W!==void 0).map((W)=>G_({collection:W}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,W){return this.configuredProviders.hasModel($,W)}applyConfig($){for(let W of $.providers)this.configuredProviders.registerSelectionConfig(W);for(let W of $.models??[])this.registerModel(W);for(let W of $.customProviders??[])this.registerProvider(W);for(let W of this.configuredProviders.list()){let Z=F_(W.id),Q=this.configuredProviders.createHandlerConfig({providerId:W.id,modelId:W.defaultModel}).routingProviderId,J=typeof Q==="string"&&F_(Q);if(!Z&&!J)throw Error(`Provider "${W.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function AY($){return new h9($)}r7();async function $g(){return Promise.resolve().then(() => (yQ(),aU))}function cg(){return new Date().toISOString()}var ug="cline",dg="cline-pass";function lg($){if(q_($)!=="providers.json")return;let W=_Y($);if(q_(W)!=="settings")return;return _Y(W)}class k1{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??vg(),this.dataDir=$.dataDir??lg(this.filePath),this.dataDir||!$.filePath)y9({providerSettingsManager:this,dataDir:this.dataDir});if(S9(this),P9(this.read()),DY(this.filePath))try{z_(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!DY(this.filePath))return v$();try{let $=Ig(this.filePath,"utf8"),W=JSON.parse($),Z=A6.safeParse(W);if(Z.success){P9(Z.data);let Q=Z.data.providers.cline?.settings?.auth;return s(`providers.read providers=[${Object.keys(Z.data.providers).join(",")}] lastUsed=${Z.data.lastUsedProvider??"none"} clineAuthPresent=${!!Q?.accessToken} clineAccessTokenHash=${N0(Q?.accessToken)} clineRefreshTokenHash=${N0(Q?.refreshToken)}`),Z.data}}catch{}return v$()}write($){let W=A6.parse($),Z=_Y(this.filePath);if(!DY(Z))kg(Z,{recursive:!0,mode:448});let Q=`${this.filePath}.${process.pid}.tmp`;try{mg(Q,`${JSON.stringify(W,null,2)}
740
+ `,{encoding:"utf8",mode:384}),xg(Q,this.filePath)}catch(J){throw gg(Q,{force:!0}),J}try{z_(this.filePath,384)}catch{}P9(W)}saveProviderSettings($,W={}){let Z=F6.parse($),Q=this.read(),J=Z.provider,j=W.setLastUsed!==!1,X=Q.providers[J],Y=W.tokenSource??X?.tokenSource??"manual",V={...Q,providers:{...Q.providers,[J]:{settings:Z,updatedAt:cg(),tokenSource:Y}},lastUsedProvider:j?J:Q.lastUsedProvider};this.write(V);let B=Q.providers.cline?.settings?.auth,H=Z.provider==="cline"?Z.auth:V.providers.cline?.settings?.auth,G=!!B?.accessToken&&!H?.accessToken;return s(`providers.save providerId=${J} tokenSource=${Y} clineAuthWasPresent=${!!B?.accessToken} clineAuthIsPresent=${!!H?.accessToken} authDropped=${G}`),V}resolveProviderSettings($,W){let Z=$.providers[W]?.settings,J=H0(W)?.storageProviderId;if(!J||J===W)return Z;let j=$.providers[J]?.settings;if(!j)return Z;return F6.parse({...j.auth?{auth:j.auth}:{},...j.apiKey?{apiKey:j.apiKey}:{},...j.baseUrl?{baseUrl:j.baseUrl}:{},...Z??{},provider:W})}getProviderSettings($){let W=this.read();return this.resolveProviderSettings(W,$)}resolveLastUsedProviderId($,W){let Z=$.lastUsedProvider;if(Z===dg&&W.isClinePassEnabled===!1)return ug;return Z}getLastUsedProviderSettings($={}){let W=this.read(),Z=this.resolveLastUsedProviderId(W,$);if(!Z)return;return this.resolveProviderSettings(W,Z)}getProviderConfig($,W){let Z=this.getProviderSettings($);if(!Z)return;return s0(Z,W)}getLastUsedProviderConfig($={}){let W=this.getLastUsedProviderSettings($);if(!W)return;return s0(W,$)}async refreshCatalog(){try{await G6({})}catch{}}}z0();O8();function pg($,W){let Z=$?.expiresAt,Q=W?.expiresAt;return $?.accessToken===W?.accessToken&&$?.refreshToken===W?.refreshToken&&$?.accountId===W?.accountId&&Z===Q}class z7 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 fY{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new k1,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let W=H0($.providerId);if(!W)return null;return this.resolveWithSingleFlight(W.providerId,W.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,W,Z=!1){let Q=this.refreshInFlight.get(W);if(Q)return Q;let J=this.resolveProviderApiKeyInternal($,W,Z).catch((j)=>{throw j}).finally(()=>{this.refreshInFlight.delete(W)});return this.refreshInFlight.set(W,J),J}async resolveProviderApiKeyInternal($,W,Z){let Q=H0($);if(!Q)return null;let J=this.providerSettingsManager.getProviderSettings(W);if(!J)return s(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_settings`),null;let j=P4($,J);if(!j)return s(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_credentials`),null;s(`oauth.resolve.start providerId=${$} storageProviderId=${W} forceRefresh=${Z} accessTokenHash=${N0(j.access)} refreshTokenHash=${N0(j.refresh)}`);let X=await Q.refresh({settings:J,credentials:j,forceRefresh:Z,telemetry:this.telemetry});if(!X)throw s(`oauth.resolve providerId=${$} outcome=refresh_returned_null`),new z7($);let Y=F2({manager:this.providerSettingsManager,providerId:$,settings:J,credentials:X,setLastUsed:!1,save:!1}),V=!pg(J.auth,Y.auth);if(V)s(`oauth.resolve.refreshed providerId=${$} newAccessTokenHash=${N0(X.access)} newRefreshTokenHash=${N0(X.refresh)} savingToDisk=true`),this.providerSettingsManager.saveProviderSettings(Y,{setLastUsed:!1,tokenSource:"oauth"});else s(`oauth.resolve providerId=${$} outcome=not_refreshed`);return{apiKey:Q.getApiKey(Y)??X.access,accountId:X.accountId,refreshed:V}}}import{normalizeUserInput as rg}from"@cline/shared";import{nanoid as ig}from"nanoid";class M_{list($){return $?Q1($):[]}update($,W){if(!$)return{sessionId:W.sessionId,prompts:[],updated:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((V)=>V.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:Q1($),updated:!1};let J=$.pendingPrompts[Q];if(!J)return{sessionId:W.sessionId,prompts:Q1($),updated:!1};let j=W.prompt===void 0?J.prompt:rg(W.prompt).trim();if(!j)throw Error("prompt cannot be empty");let X=W.delivery??J.delivery,Y={...J,prompt:j,mode:W.mode??J.mode,delivery:X};return $.pendingPrompts.splice(Q,1),ng($,Y,Q,J.delivery),{sessionId:W.sessionId,prompts:Q1($),prompt:q7(Y),updated:!0}}delete($,W){if(!$)return{sessionId:W.sessionId,prompts:[],removed:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((j)=>j.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:Q1($),removed:!1};let[J]=$.pendingPrompts.splice(Q,1);return{sessionId:W.sessionId,prompts:Q1($),prompt:J?q7(J):void 0,removed:!0}}enqueue($,W){let{prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X}=W,Y=$.pendingPrompts.findIndex((V)=>V.prompt===Z);if(Y>=0){let[V]=$.pendingPrompts.splice(Y,1),B={...V,prompt:Z,mode:Q??V.mode,userImages:j??V.userImages,userFiles:X??V.userFiles};if(J==="steer"||V.delivery==="steer")$.pendingPrompts.unshift({...B,delivery:"steer"});else $.pendingPrompts.push(B)}else{let V={id:`pending_${Date.now()}_${ig(5)}`,prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X};if(J==="steer")$.pendingPrompts.unshift(V);else $.pendingPrompts.push(V)}return Q1($)}consumeSteer($){let W=$.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if(W<0)return{prompts:Q1($)};let[Z]=$.pendingPrompts.splice(W,1);return{entry:Z,prompts:Q1($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:Q1($)}}requeueFront($,W){return $.pendingPrompts.unshift(W),Q1($)}clear($){return $.pendingPrompts.length=0,[]}}class LY{deps;service=new M_;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Z=this.service.update(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}delete($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Z=this.service.delete(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}enqueue($,W){let Z=this.deps.getSession($);if(!Z||Z.aborting)return;this.service.enqueue(Z,W),this.emitPrompts(Z),this.scheduleDrain($,Z)}consumeSteer($){let W=this.deps.getSession($);if(!W)return;let{entry:Z}=this.service.consumeSteer(W);if(!Z)return;return this.emitPrompts(W),this.emitSubmitted(W,Z),Z}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:Q1($)}})}scheduleDrain($,W){if(W.pendingPrompts.length===0||W.aborting||W.drainingPendingPrompts||!W.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let W=this.deps.getSession($);if(!W)return;if(W.aborting||W.drainingPendingPrompts)return;if(!W.agent.canStartRun())return;let{entry:Z}=this.service.shiftNext(W);if(!Z)return;this.emitPrompts(W),this.emitSubmitted(W,Z),W.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:$,prompt:Z.prompt,...Z.mode?{mode:Z.mode}:{},userImages:Z.userImages,userFiles:Z.userFiles})}catch{Q=!1,this.service.requeueFront(W,Z),this.emitPrompts(W)}finally{if(W.drainingPendingPrompts=!1,Q&&W.pendingPrompts.length>0&&W.status!=="failed"&&W.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,W){let Z=q7(W);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}})}}function q7($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0),userImages:$.userImages,userFiles:$.userFiles}}function Q1($){return $.pendingPrompts.map(q7)}function ng($,W,Z,Q){if(W.delivery==="steer")$.pendingPrompts.unshift(W);else if(Q==="steer")$.pendingPrompts.push(W);else $.pendingPrompts.splice(Z,0,W)}z0();class OY{deps;constructor($){this.deps=$}dispatchAgentEvent($,W,Z){let Q=this.deps.getSession($),J={sessionId:$,config:W,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},j=OJ(Z),X=!!Q&&(!j.agentId||j.agentId===TY(Q.agent));zJ(J,Z,X?{isPrimaryAgentEvent:!0,agentId:TY(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,W){let Z=this.deps.getSession($);if(Z){if(gj(Z,W),W.type==="agent_event"){let Q={sessionId:$,config:Z.config,liveSession:Z,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};zJ(Q,W.event,{agentId:W.agentId,teamRole:"teammate",teamAgentId:W.agentId,isPrimaryAgentEvent:!1})}if(W.type==="teammate_spawned"){let Q=W$({agentId:W.teammate.runtimeAgentId??W.agentId,conversationId:W.teammate.conversationId,parentAgentId:W.teammate.parentAgentId,createdByAgentId:TY(Z.agent),teamId:Z.runtime.teamRuntime?.getTeamId(),teamName:Z.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:W.agentId});if(Q)T$(Z.config.telemetry,{ulid:$,modelId:W.teammate.modelId??Z.config.modelId,provider:Z.config.providerId,...Q})}}if(await mj($,W,this.deps.invokeBackendOptional),Z)vj(Z,$,W,this.deps.emit)}async handlePluginEvent($,W,Z){if(W.name==="plugin_log"){this.handlePluginLog($,W.payload);return}if(W.name==="automation_event"){let V=this.deps.getSession($)?.config.extensionContext?.automation??Z;if(!V)return;let B=W.payload&&typeof W.payload==="object"?W.payload:void 0;if(!B)return;await V.ingestEvent(B);return}if(W.name!=="steer_message"&&W.name!=="queue_message"&&W.name!=="pending_prompt")return;let Q=W.payload&&typeof W.payload==="object"?W.payload:void 0,J=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():$,j=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!j)return;let X=W.name==="steer_message"?"steer":W.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(J,{prompt:j,delivery:X})}handlePluginLog($,W,Z){let Q=this.deps.getSession($),J=Z??Q?.config.extensionContext?.logger??Q?.config.logger;if(!J||!W||typeof W!=="object")return;let j=W,X=typeof j.message==="string"?j.message:"";if(!X)return;let Y=j.metadata&&typeof j.metadata==="object"?{...j.metadata}:{};if(Y.sessionId??=$,typeof j.pluginName==="string"&&j.pluginName)Y.pluginName=j.pluginName;if(j.level==="debug"){J.debug(X,Y);return}if(j.level==="error"){if(J.error)J.error(X,Y);else J.log(X,{...Y,severity:"error"});return}J.log(X,Y)}}function TY($){return $.getAgentId()}function zY($){return{sessionId:$.sessionId,source:$.source,pid:process.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:Z$($.config),teamName:$.config.teamName?.trim()||void 0,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,parentSessionId:typeof $.sessionMetadata?.parentSessionId==="string"?$.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof $.sessionMetadata?.parentAgentId==="string"?$.sessionMetadata.parentAgentId:void 0,agentId:typeof $.sessionMetadata?.agentId==="string"?$.sessionMetadata.agentId:void 0,conversationId:typeof $.sessionMetadata?.conversationId==="string"?$.sessionMetadata.conversationId:void 0,isSubagent:typeof $.sessionMetadata?.isSubagent==="boolean"?$.sessionMetadata.isSubagent:!1,prompt:$.pendingPrompt,metadata:$.sessionMetadata,messagesPath:$.artifacts?.messagesPath,updatedAt:$.updatedAt??$.endedAt??$.startedAt}}function qY($,W){let Z=$[W];return typeof Z==="function"?Z:null}async function R_($,W,...Z){let Q=qY($,W);if(!Q)throw Error(`session service method not available: ${W}`);return Promise.resolve(Q.apply($,Z))}async function E_($,W,...Z){let Q=qY($,W);if(!Q)return;await Promise.resolve(Q.apply($,Z))}async function N_($,W,...Z){let Q=qY($,W);if(!Q)return;return await Promise.resolve(Q.apply($,Z))}X1();z0();function MY($,W,Z){return{onSubAgentEvent:(Q)=>$.onAgentEvent(Z,W,Q),onSubAgentStart:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:Z});let j=W$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)T$(W.telemetry,{ulid:Z,modelId:W.modelId,provider:W.providerId,...j});B4(W.telemetry,{event:"started",ulid:Z,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...j}),$.invokeBackendOptional("handleSubAgentStart",Z,Q)},onSubAgentEnd:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime,j=$.subAgentStarts.get(Q.subAgentId),X=j?Date.now()-j.startedAt:0,Y=Q.result?.text?Q.result.text.split(`
741
+ `).length:0;B4(W.telemetry,{event:"ended",ulid:Z,durationMs:X,outputLines:Y,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...W$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Z,Q)}}}function RY($,W,Z,Q){let J=MY($,W,Z);return y$({configProvider:{getRuntimeConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,maxIterations:W.maxIterations,hooks:W.hooks,extensions:W.extensions,logger:W.logger,telemetry:W.telemetry},getConnectionConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let X=W.enableTools?y2({cwd:W.cwd,...a0[e1({mode:W.mode})],executors:Q}):[];if(W.enableSpawnAgent)X.push(RY($,W,Z,Q));return u1(X)},...J})}import{readFile as ag,stat as og}from"node:fs/promises";var sg=20480000;async function w_($){let W=await og($);if(!W.isFile())throw Error("Path is not a file");if(W.size>sg)throw Error("File is too large to read into context.");let Z=await ag($,"utf8");if(Z.includes("\x00"))throw Error("Cannot read binary file into context.");return Z}var C_=5000;function m9($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function jm($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=m9(W.inputTokens),Q=m9(W.outputTokens),J=m9(W.cacheReadTokens),j=m9(W.cacheWriteTokens),X=m9(W.totalCost);if(Z===void 0||Q===void 0||J===void 0||j===void 0||X===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:J,cacheWriteTokens:j,totalCost:X}}function Xm($,W){return{inputTokens:Math.max($.inputTokens,W.inputTokens),outputTokens:Math.max($.outputTokens,W.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,W.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,W.cacheWriteTokens),totalCost:Math.max($.totalCost,W.totalCost)}}function P_($,W){if(!W)return!1;if($.source_message_count!==W.source_message_count)return $.source_message_count<W.source_message_count;return Date.parse($.updated_at)<Date.parse(W.updated_at)}class b1{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new Z9;sessions=new Map;manifestMutationQueues=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new o$;constructor($){let W=eg();if(W)Jm(W);let Z=x0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new d6,this.createAgentInstance=$.createAgent??((Q)=>new P$(Q)),this.defaultCapabilities=P0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new k1,this.oauthTokenManager=$.oauthTokenManager??new fY({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Z),this.defaultFetch=$.fetch,this.pendingPromptsController=new LY({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 OY({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,J,j)=>{this.invoke("persistSessionMessages",Q,J,j)},enqueuePendingPrompt:(Q,J)=>this.pendingPromptsController.enqueue(Q,J),invokeBackendOptional:(Q,...J)=>this.invokeOptional(Q,...J)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let W=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!W?.apiKey)return $;return{...$,config:{...$.config,apiKey:W.apiKey}}}async startSession($){let W=$.source??F0.CLI,Z=X0(),Q=$.config.sessionId?.trim()??"",J=Q||Wm(),j=await this.applyInitialOAuthCredentials($),X=j.initialMessages??[],Y=X.length>0?$6(X):q0(),V=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!V)throw Error("session service method not available: ensureSessionsDir");let B=EY(V,J),H=EY(B,`${J}.messages.json`),G=EY(B,`${J}.json`),K=Z$($.config),F=m0.parse({version:1,session_id:J,source:W,pid:process.pid,started_at:Z,status:"running",interactive:$.interactive===!0,provider:j.config.providerId,model:j.config.modelId,cwd:j.config.cwd,workspace_root:K,team_name:j.config.teamName,enable_tools:j.config.enableTools,enable_spawn:j.config.enableSpawnAgent,enable_teams:j.config.enableAgentTeams,prompt:j.prompt?.trim()||void 0,messages_path:H}),A,D;if(Q.length>0&&X.length>0&&!j.prompt?.trim()){let k=await this.invokeOptionalValue("readSessionManifest",J);if(k)F=k,A={manifestPath:G,messagesPath:k.messages_path||H,compactionPath:k.compaction_path,manifest:k},D=await this.invokeOptionalValue("readSessionCompactionState",J)}let f=await this.seedAggregateUsageFromArtifacts({initialUsage:Y,sessionDir:B,rootMessagesPath:A?.messagesPath??H,manifest:F});this.usageBySession.set(J,Y),this.aggregateUsageBySession.set(J,f);let _=P0(this.defaultCapabilities,$.capabilities),R=_?.toolExecutors??this.toolExecutors,O=$.localRuntime,T=O?.extensionContext?.logger??O?.logger,L=O?.extensionContext?.automation,C,E={getSession:(k)=>this.sessions.get(k),subAgentStarts:this.subAgentStarts,onAgentEvent:(k,W0,T0)=>this.eventBridge.dispatchAgentEvent(k,W0,T0),invokeBackendOptional:(k,...W0)=>this.invokeOptional(k,...W0)};C=await AF({input:j,localRuntime:$.localRuntime,sessionId:J,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:_,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(k)=>{if(k.name==="plugin_log"){this.eventBridge.handlePluginLog(J,k.payload,T);return}this.eventBridge.handlePluginEvent(J,k,L)},onTeamEvent:(k)=>{this.eventBridge.handleTeamEvent(J,k),C.config.onTeamEvent?.(k)},createSpawnTool:()=>RY(E,C.config,J,R),createSubAgentLifecycleCallbacks:(k)=>MY(E,k,J),readSessionMetadata:async()=>(await this.getSession(J))?.metadata,writeSessionMetadata:async(k)=>{await this.persistSessionMetadata(J,()=>k)}});let p=r9(j.sessionMetadata??A?.manifest.metadata,C.gitState);if(!A)F.metadata=p;let x=await this.runtimeBuilder.build(C.runtimeBuilderInput),P=C.config,r=C.providerConfig;if(x.teamRuntime&&!P.teamName?.trim())P.teamName=x.teamRuntime.getTeamName();let d=[...x.tools,...P.extraTools??[]],I1=x.extensions??C.extensions,$2=j.initialCompactionState,A$,I0=m4(P),U0=$2??D,D1=I0&&U0?{...U0,conversation_id:U0.conversation_id?.trim()||J}:void 0,K8=I0?v4({compact:I0,getState:()=>A$?.compactionState,saveState:async(k)=>{let W0=A$;if(!W0)return;let T0={...k,conversation_id:W0.sessionId};try{if(!(await this.persistActiveSessionCompactionState(W0,T0)).updated)P.logger?.debug?.("Skipped stale session compaction state",{sessionId:W0.sessionId,sourceMessageCount:T0.source_message_count})}catch(M0){P.logger?.error?.("Failed to persist session compaction state",{sessionId:W0.sessionId,error:M0}),s$(P.telemetry,{component:"core",operation:"session.persist_compaction_state",severity:"warn",handled:!0,error:M0,context:{sessionId:W0.sessionId,providerId:P.providerId,modelId:P.modelId}})}}}):void 0,V0={sessionId:J,providerId:r.providerId,modelId:r.modelId,apiKey:r.apiKey,baseUrl:r.baseUrl,headers:r.headers,knownModels:r.knownModels,providerConfig:r,thinking:P.thinking,reasoningEffort:P.reasoningEffort??r.reasoningEffort,thinkingBudgetTokens:P.thinkingBudgetTokens,maxTokensPerTurn:P.maxTokensPerTurn,temperature:P.temperature,systemPrompt:P.systemPrompt,maxIterations:P.maxIterations,execution:P.execution,prepareTurn:K8,tools:d,hooks:C.hooks,extensions:I1,hookErrorMode:P.hookErrorMode,initialMessages:C.effectiveInput.initialMessages,userFileContentLoader:w_,toolPolicies:C.toolPolicies,requestToolApproval:C.requestToolApproval?async(k)=>{let W0=C.requestToolApproval,T0=this.sessions.get(J);if(T0)await this.markTurnPending(T0);try{if(!W0)return{approved:!1,reason:"Tool approval callback is not configured."};return await W0(k)}finally{let M0=this.sessions.get(J);if(M0?.status==="pending")await this.markTurnRunning(M0)}}:void 0,telemetry:P.telemetry,onConsecutiveMistakeLimitReached:P.onConsecutiveMistakeLimitReached,completionPolicy:x.completionPolicy,consumePendingUserMessage:()=>{let k=this.pendingPromptsController.consumeSteer(J);return k?G9(k.prompt,k.mode??P.mode):void 0},logger:x.logger??P.logger,extensionContext:P.extensionContext,onEvent:(k)=>this.eventBridge.dispatchAgentEvent(J,P,k)};V0.hooks={...V0.hooks,onEvent:async(k)=>{if(await C.hooks?.onEvent?.(k),k.type!=="assistant-message")return;let W0=this.sessions.get(J);if(!W0)return;let T0=W0.agent.getMessages();try{await this.invoke("persistSessionMessages",J,T0,P.systemPrompt)}catch(M0){P.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:J,error:M0}),s$(P.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:M0,severity:"warn",handled:!0,context:{sessionId:J,providerId:P.providerId,modelId:P.modelId}})}}};let d0=this.createAgentInstance(V0);if(V0.onEvent)d0.subscribeEvents(V0.onEvent);x.registerLeadAgent?.(d0);let J1=W$({agentId:d0.getAgentId(),conversationId:d0.getConversationId(),teamId:x.teamRuntime?.getTeamId(),teamName:x.teamRuntime?.getTeamName(),teamRole:x.teamRuntime?"lead":void 0});if(DF(P,J,Q.length>0,K,J1),J1)T$(P.telemetry,{ulid:J,modelId:P.modelId,provider:P.providerId,...J1});if(x.teamRuntime)BW(P.telemetry,{ulid:J,teamId:x.teamRuntime.getTeamId(),teamName:x.teamRuntime.getTeamName(),leadAgentId:d0.getAgentId(),restoredFromPersistence:x.teamRestoredFromPersistence===!0});let y={sessionId:J,config:P,sessionMetadata:p,...A?{artifacts:A}:{},source:W,startedAt:A?.manifest.started_at??Z,updatedAt:A?.manifest.ended_at??A?.manifest.started_at??Z,pendingPrompt:F.prompt,runtime:x,agent:d0,started:!1,status:A?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:X,compactionState:D1,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:C.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(A$=y,y.compactionState&&!this.isCompactionStateForSession(y.sessionId,y.compactionState,y))y.config.logger?.log?.("Ignoring session compaction state for a different conversation",{severity:"warn",sessionId:y.sessionId,conversationId:y.compactionState.conversation_id}),y.compactionState=void 0;if(this.sessions.set(J,y),A)await this.refreshActiveSessionGitMetadata(y,C.gitState);if(this.emitStatus(J,"running"),X.length>0&&!A){if(await this.ensureSessionPersisted(y),await this.invoke("persistSessionMessages",y.sessionId,X,y.config.systemPrompt),y.compactionState){if(!(await this.persistActiveSessionCompactionState(y,y.compactionState)).updated)y.compactionState=void 0}if(!j.prompt?.trim())await this.updateStatus(y,"completed",0)}let j1;try{if(j.prompt?.trim())if(j1=await this.executeTurn(y,{prompt:j.prompt,userImages:j.userImages,userFiles:j.userFiles}),!y.interactive)await this.finalizeSingleRun(y,j1.finishReason);else await this.completeInteractiveTurn(y,j1.finishReason)}catch(k){if(y.interactive&&y.aborting)j1=await this.completeAbortedInteractiveTurn(y);else{s$(y.config.telemetry,{component:"core",operation:"session.start",error:k,severity:"error",handled:!1,context:{sessionId:y.sessionId,providerId:y.config.providerId,modelId:y.config.modelId}});try{await this.failSession(y)}catch(W0){y.config.logger?.error?.("Session failure cleanup threw",{sessionId:y.sessionId,error:W0})}throw k}}return{sessionId:J,manifest:F,manifestPath:G,messagesPath:H,result:j1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(W)=>this.getSession(W),readMessages:(W)=>this.readSessionMessages(W),buildStartInput:(W,Z)=>{let Q=W.restoredCheckpointMetadata?{...Z.sessionMetadata??{},checkpoint:W.restoredCheckpointMetadata}:Z.sessionMetadata;return{...Z,...Q?{sessionMetadata:Q}:{},initialMessages:W.initialMessages}},startSession:(W)=>this.startSession(W),getStartedSessionId:(W)=>W.sessionId,readRestoredSession:(W)=>this.getSession(W)})}async runTurn($){let W=this.getSessionOrThrow($.sessionId),Z=W.agent.canStartRun(),Q=$.delivery??(W.interactive&&!Z?"queue":void 0);if(W.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Q,userImages:$.userImages,userFiles:$.userFiles});return}try{let J=await this.executeTurn(W,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!W.interactive)await this.finalizeSingleRun(W,J.finishReason);else await this.completeInteractiveTurn(W,J.finishReason);if(J.finishReason==="error"||J.finishReason==="aborted")return J;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),J}catch(J){if(W.interactive&&W.aborting)return await this.completeAbortedInteractiveTurn(W);throw s$(W.config.telemetry,{component:"core",operation:"session.submit",error:J,severity:"error",handled:!1,context:{sessionId:W.sessionId,providerId:W.config.providerId,modelId:W.config.modelId}}),await this.failSession(W),J}}async getAccumulatedUsage($){let W=Nj(this.usageBySession.get($)),Z=Nj(this.aggregateUsageBySession.get($));return W||Z?{usage:W,aggregateUsage:Z}:void 0}async abort($,W){let Z=this.sessions.get($);if(!Z)return;Z.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Z.aborting=!0,this.pendingPromptsController.clearAborted(Z),Z.agent.abort(W)}async stopSession($){let W=this.sessions.get($);if(!W)return;if(W.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),W.interactive&&!K0(W.status)){await this.releaseSessionRuntime(W,"session_stop");return}if(W.interactive&&W.agent.canStartRun()){await this.shutdownSession(W,{status:this.resolveInteractiveStopStatus(W),exitCode:this.resolveInteractiveStopExitCode(W),shutdownReason:"session_stop",endReason:"stopped"});return}W.aborting=!0,W.agent.abort(Error("session_stop")),await this.shutdownSession(W,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let W=[...this.sessions.values()];if(W.length===0)return;await Promise.allSettled(W.map((Z)=>Z.interactive&&!K0(Z.status)?this.releaseSessionRuntime(Z,$):Z.interactive&&Z.agent.canStartRun()?this.shutdownSession(Z,{status:this.resolveInteractiveStopStatus(Z),exitCode:this.resolveInteractiveStopExitCode(Z),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Z,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let W=this.sessions.get($);if(W)return zY(W);let Z=$.trim();if(!Z)return;let Q=await this.getRow(Z);if(Q)return H5(Q);let J=await this.readManifest(Z);return J?TQ(J):void 0}async listSessions($=200){let Z=(await this.listRows($)).map(H5),Q=new Set(Z.map((J)=>J.sessionId));for(let J of this.sessions.values()){if(Q.has(J.sessionId))continue;Z.unshift(zY(J))}return Z.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let W=await this.invoke("deleteSession",$);if(W.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return W.deleted}async updateSession($,W){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:W.prompt,metadata:W.metadata,title:W.title}))?.updated===!0}}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=this.sessions.get(Z),J=Q?void 0:await this.getSession(Z);if(!(Q??J))return{updated:!1};if(Q){let Y=await this.readSessionMessages(Z),V=W.source_message_count>0&&Y.length>=W.source_message_count,B=V?Y:void 0;if(V){if(!await this.canPersistCompactionState(Z,W,Q,void 0,Y))return{updated:!1};Q.agent.restore(Y)}return await this.persistActiveSessionCompactionState(Q,W,B)}if(!await this.canPersistCompactionState(Z,W,void 0,J))return{updated:!1};let X=await this.invokeOptionalValue("readSessionCompactionState",Z);if(P_(W,X))return{updated:!1};return await this.invoke("persistSessionCompactionState",Z,W),{updated:!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=this.sessions.get(W);if(Z)for(;;){let Q=Z.compactionStateWriteQueue;if(!Q)return Z.compactionState;await Q.catch(()=>{return})}return await this.invokeOptionalValue("readSessionCompactionState",W)}isCompactionStateForSession($,W,Z,Q){let J=W.conversation_id?.trim();if(!J)return!0;if(J===$)return!0;let j=Z?.agent.getConversationId()?.trim()||Q?.conversationId?.trim();return j?J===j:!1}async canPersistCompactionState($,W,Z,Q,J){if(!W.conversation_id?.trim())return!1;if(!this.isCompactionStateForSession($,W,Z,Q))return!1;let j=J??Z?.agent.getMessages()??await this.readSessionMessages($);return A2(W,j)!==void 0}async persistActiveSessionCompactionState($,W,Z){if(!await this.canPersistCompactionState($.sessionId,W,$,void 0,Z))return{updated:!1};return await this.enqueueCompactionStateWrite($,async()=>{if(P_(W,$.compactionState))return{updated:!1};return await this.invoke("persistSessionCompactionState",$.sessionId,W),$.compactionState=W,{updated:!0}})}async enqueueCompactionStateWrite($,W){let Q=($.compactionStateWriteQueue??Promise.resolve()).catch(()=>{return}).then(W),J=Q.then(()=>{return},()=>{return});$.compactionStateWriteQueue=J;try{return await Q}finally{if($.compactionStateWriteQueue===J)$.compactionStateWriteQueue=void 0}}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.getRow(W);if(Z?.messagesPath)return p$(Z.messagesPath);let Q=await this.readManifest(W);return p$(Q?.messages_path)}async dispatchHookEvent($){await IA($,{queueSpawnRequest:(W)=>this.invokeOptional("queueSpawnRequest",W),upsertSubagentSessionFromHook:(W)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",W),appendSubagentHookAudit:(W,Z)=>this.invokeOptional("appendSubagentHookAudit",W,Z),applySubagentStatus:(W,Z)=>this.invokeOptional("applySubagentStatus",W,Z)})}subscribe($,W){return this.events.subscribe($,W)}async updateSessionModel($,W){await this.updateSessionConnection($,{modelId:W})}async updateSessionConnection($,W){let Z=w2(W),Q=this.getSessionOrThrow($);if(Z.providerId!==void 0)Q.config.providerId=Z.providerId;if(Z.modelId!==void 0)Q.config.modelId=Z.modelId;if(Z.apiKey!==void 0)Q.config.apiKey=Z.apiKey;if(Z.baseUrl!==void 0)Q.config.baseUrl=Z.baseUrl;if(Z.headers!==void 0)Q.config.headers=Z.headers;if(Z.providerConfig!==void 0)Q.config.providerConfig=Z.providerConfig;if(Object.hasOwn(Z,"reasoningEffort"))Q.config.reasoningEffort=Z.reasoningEffort??void 0;if(Object.hasOwn(Z,"thinkingBudgetTokens"))Q.config.thinkingBudgetTokens=Z.thinkingBudgetTokens??void 0;if(Object.hasOwn(Z,"thinking")){if(Q.config.thinking=Z.thinking??void 0,Z.thinking===!1||Z.thinking===null)Q.config.reasoningEffort=void 0,Q.config.thinkingBudgetTokens=void 0}let J={...Z.providerId!==void 0?{providerId:Z.providerId}:{},...Z.modelId!==void 0?{modelId:Z.modelId}:{},...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{},...Z.providerConfig!==void 0?{providerConfig:Z.providerConfig}:{},...Object.hasOwn(Z,"reasoningEffort")?{reasoningEffort:Z.reasoningEffort??void 0}:{},...Object.hasOwn(Z,"thinking")?{thinking:Z.thinking??void 0}:{},...Object.hasOwn(Z,"thinkingBudgetTokens")?{thinkingBudgetTokens:Z.thinkingBudgetTokens??void 0}:{}};if(Z.thinking===!1||Z.thinking===null)J.reasoningEffort=void 0,J.thinkingBudgetTokens=void 0;let j={...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{}};if(Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults(J),Q.agent.updateConnection(Z),Q.runtime.teamRuntime?.updateTeammateConnections(j),Z.providerId||Z.modelId)await this.mutateSessionManifest(Q,(X)=>{if(Z.providerId)X.provider=Z.providerId;if(Z.modelId)X.model=Z.modelId})}async mutateSessionManifest($,W){let Z=$.artifacts;if(!Z)return;let Q=$.sessionId,j=(this.manifestMutationQueues.get(Q)??Promise.resolve()).then(async()=>{let Y=await this.invokeOptionalValue("readSessionManifest",Q)??Z.manifest;return W(Y),Z.manifest=Y,await this.invoke("writeSessionManifest",Z.manifestPath,Y),Y}),X=j.then(()=>{return},()=>{return});this.manifestMutationQueues.set(Q,X);try{return await j}finally{if(this.manifestMutationQueues.get(Q)===X)this.manifestMutationQueues.delete(Q)}}handlePluginEvent($,W,Z){return this.eventBridge.handlePluginEvent($,W,Z)}async executeTurn($,W){let Z=await this.prepareTurnInput($,W),Q=Z.prompt.trim(),J=Z?.userImages?.length,j=Z?.userFiles?.length;if(!Q&&!J&&!j)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Q;await this.ensureSessionPersisted($),await this.refreshActiveSessionGitMetadata($),await this.syncOAuthCredentials($),await this.markTurnRunning($);try{let X=await this.executeAgentTurn($,Q,Z.userImages,Z.userFiles);while(cj($,X.finishReason)){let Y=await uj($);if(Y.length===0)break;let V=dj($,Y);X=await this.executeAgentTurn($,V)}return X}finally{await this.refreshActiveSessionGitMetadata($)}}async completeInteractiveTurn($,W){if(H9($))return;$.lastInteractiveTurnFinishReason=W,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let W=$.lastInteractiveTurnFinishReason;if(!W)return"cancelled";switch(W){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return W}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let W=new Date,Z=$.agent.getMessages(),Q=q0();return $.persistedMessages=Z,$.started=$.started||Z.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Q,messages:Z,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:W,endedAt:W,durationMs:0}}async executeAgentTurn($,W,Z,Q){let J=$.started||$.agent.getMessages().length>0,j=$.persistedMessages??$.agent.getMessages(),X=this.usageBySession.get($.sessionId)??q0(),Y=this.aggregateUsageBySession.get($.sessionId)??X;$.turnUsageBaseline=X,$.turnAggregateUsageBaseline=Y,$.turnPrimaryUsage=q0(),$.turnUsageByAgent=new Map,ZW($.config.telemetry,$.sessionId,$.config.mode),L8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let V=J?()=>$.agent.continue(W,Z,Q):()=>$.agent.run(W,Z,Q),B=await this.runWithAuthRetry($,V,j);$.started=!0;let H=_Z(B.messages,B,j);$.persistedMessages=H;let G=K5($.turnUsageByAgent?.values()??[]),K=L0(X,B.usage),F=L0(L0(q0(),B.usage),G),A=L0(Y,F);return this.usageBySession.set($.sessionId,K),this.aggregateUsageBySession.set($.sessionId,A),await this.persistSessionMetadata($.sessionId,(D)=>({...D??{},totalCost:K.totalCost,aggregatedAgentsCost:A.totalCost,usage:K,aggregateUsage:A})),await this.invoke("persistSessionMessages",$.sessionId,H,$.config.systemPrompt),this.observeTaskCompletionTool($,B),B}catch(V){throw s$($.config.telemetry,{component:"core",operation:"session.turn",error:V,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),V}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,W){if($.submitAndExitObserved)return;if(!W.toolCalls.some((Q)=>Q.name===O0.SUBMIT_AND_EXIT&&Q.error===void 0))return;$.submitAndExitObserved=!0,Y4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,W){let Z=Z$($.config),Q=Qm(W.prompt).trim();if(!Q)return{prompt:"",userImages:W.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles)};let J=await d8(Q,Z);_F($.config.telemetry,J);let j=G9(J.prompt,W.mode??$.config.mode),X=this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles),Y=this.resolveAbsoluteFilePaths(Z,J.matchedFiles),V=Array.from(new Set([...X,...Y]));return{prompt:j,userImages:W.userImages,userFiles:V.length>0?V:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let W=Z$($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:W,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async refreshActiveSessionGitMetadata($,W){try{let Z=W??await b7(Z$($.config));if(!Z||!$.artifacts)return;if(S7($.artifacts.manifest.metadata,Z))return;await this.persistSessionMetadata($.sessionId,(Q)=>r9({...Q??{},...$.sessionMetadata??{}},Z))}catch(Z){$.config.logger?.debug?.("Failed to refresh session git metadata",{sessionId:$.sessionId,error:Z})}}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,W){let Z=this.sessions.get($),Q=await this.invokeOptionalValue("readSessionManifest",$)??Z?.artifacts?.manifest,J=W(Q?.metadata);if(!Z?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:J}))?.updated===!1)return;Z.sessionMetadata=J,Z.artifacts.manifest.metadata=J}async finalizeSingleRun($,W){if(H9($))return;let Z=W==="aborted"||$.aborting,Q=W==="error";await this.shutdownSession($,{status:Z?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:W})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,W){if(W.status==="completed"&&!$.submitAndExitObserved)Y4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});EQ($);let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),s$($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,status:W.status,shutdownReason:W.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){await this.refreshActiveSessionGitMetadata($);try{await this.updateStatus($,W.status,W.exitCode)}catch(J){Q("update_status",J)}try{await $.agent.shutdown(W.shutdownReason)}catch(J){Q("agent_shutdown",J)}}try{await Promise.resolve($.runtime.shutdown(W.shutdownReason))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:W.endReason,ts:Date.now()}}),Z.length>0&&W.status==="failed")throw Z[0]}async releaseSessionRuntime($,W){let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),s$($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,reason:W,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(W)}catch(J){Q("agent_shutdown",J)}try{await Promise.resolve($.runtime.shutdown(W))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),Z.length>0)throw Z[0]}async updateStatus($,W,Z){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,W,Z);if(!Q.updated)return;let J=await this.mutateSessionManifest($,(j)=>{if(j.status=W,K0(W))delete j.ended_at,j.exit_code=null;else j.ended_at=Q.endedAt??X0(),j.exit_code=typeof Z==="number"?Z:null});if(!J)return;$.status=W,$.updatedAt=Q.endedAt??X0(),$.endedAt=K0(W)?null:J.ended_at,$.exitCode=J.exit_code,this.emitStatus($.sessionId,W)}async runWithAuthRetry($,W,Z){try{return await W()}catch(Q){if(!K2($.config.providerId)||!Zm(Q))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Z),W()}}async syncOAuthCredentials($,W){let Z=null;try{Z=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:W?.forceRefresh})}catch(Q){if(Q instanceof z7)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!Z?.apiKey||$.config.apiKey===Z.apiKey)return;$.config.apiKey=Z.apiKey,$.agent.updateConnection({apiKey:Z.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Z.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Z.apiKey})}getSessionOrThrow($){let W=this.sessions.get($);if(!W){let Z=new l1($);throw s$(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Z,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Z}return W}resolveAbsoluteFilePaths($,W){if(!W||W.length===0)return[];let Z=W.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>$m(Q)?Q:NY($,Q));return Array.from(new Set(Z))}getSessionAgentTelemetryIdentity($){return W$({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let W=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Z=L0($.initialUsage,W);return this.withPersistedAggregateUsageFloor(Z,$.manifest)}async summarizePersistedTeammateUsage($,W,Z){let Q=NY(W),J=`${Z}.messages.json`,j;try{j=tg($)}catch{return q0()}let X=q0();for(let Y of j){if(!Y.endsWith(".messages.json"))continue;if(Y===J)continue;let V=NY($,Y);if(V===Q)continue;let B=await p$(V);if(B.length===0)continue;X=L0(X,$6(B))}return X}withPersistedAggregateUsageFloor($,W){let Z=jm(W.metadata?.aggregateUsage);if(Z)return Xm($,Z);let Q=W.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=$.totalCost)return $;return{...$,totalCost:Q}}emitStatus($,W){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:W}})}async emitSessionSnapshot($){let W=await this.getSession($);if(!W)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:N1({session:W,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),C_))}async getRow($){let W=$.trim();if(!W)return;return(await this.listRows(C_)).find((Q)=>Q.sessionId===W)}async readManifest($){let W=$.trim();if(!W)return;return await this.invokeOptionalValue("readSessionManifest",W)}invoke($,...W){return R_(this.sessionService,$,...W)}invokeOptional($,...W){return E_(this.sessionService,$,...W)}invokeOptionalValue($,...W){return N_(this.sessionService,$,...W)}}function Vm($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function Bm($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function f_($={}){let W=new b1({sessionService:new S1(new C1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||F0.CLI,interactive:!1,config:{providerId:Ym(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:Bm(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content)});if(!J)throw Error("local hub schedule runtime returned no turn result");return{result:Vm(J)}},async abortSession(Z){return await W.abort(Z,Error("hub schedule abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}import{resolveClineBuildEnv as bf}from"@cline/shared";function Hm($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Z)=>{if(Z&&typeof Z==="object"&&"type"in Z&&Z.type==="text"&&"text"in Z&&typeof Z.text==="string")return Z.text.trim();return""}).filter(Boolean).join(`
742
+ `).trim()||void 0}var S_=120,wY="...";function k9($){let W=$.trim();if(!W)return"";if(Buffer.byteLength(W,"utf8")<=S_)return W;let Z=S_-Buffer.byteLength(wY,"utf8");if(Z<=0)return wY;let Q="";for(let J of W){if(Buffer.byteLength(Q+J,"utf8")>Z)break;Q+=J}return`${Q}${wY}`}async function b_($){let W=$?.sessionId?.trim()||"unknown",Z=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,J=[...await p$(Z)].reverse().find((V)=>V.role==="assistant"),j=J?Hm(J.content):void 0,X=$?.workspaceRoot?.trim()||"workspace",Y=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():X;return{title:`Task completed (${W})`,body:k9(j&&j.length>0?j:Y.length>0?Y:X),severity:"info"}}import{captureSdkError as N7,createSessionId as Gv}from"@cline/shared";import{createSessionId as Am}from"@cline/shared";import{createSessionId as Fm}from"@cline/shared";function Gm($){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 Km($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())W.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())W.parentAgentId=$.parentAgentId;if($.agentId?.trim())W.agentId=$.agentId;if($.conversationId?.trim())W.conversationId=$.conversationId;if($.messagesPath?.trim())W.messagesPath=$.messagesPath;if($.prompt?.trim())W.prompt=$.prompt;if($.provider?.trim())W.provider=$.provider;if($.model?.trim())W.model=$.model;if($.source?.trim())W.source=$.source;if(typeof $.pid==="number")W.pid=$.pid;return Object.keys(W).length>0?W:void 0}function M7($,W,Z,Q){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:W?.createdByClientId??"hub",status:Gm($.status),participants:W?[...W.participants.values()]:[],metadata:Km($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...Z?{usage:{...Z}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function u($,W){return{version:$.version,requestId:$.requestId,ok:!0,...W!==void 0?{payload:W}:{}}}function h($,W,Z){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:W,message:Z}}}function s6($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function S0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function H8($,W,Z){return{version:"v1",event:$,eventId:Fm("hevt_"),sessionId:Z,timestamp:Date.now(),payload:W}}async function b0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let Q=await $.sessionHost.getAccumulatedUsage?.(W);return M7(Z,$.sessionState.get(W),Q?.usage,Q?.aggregateUsage)}async function u0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let[Q,J]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(W):[],$.sessionHost.getAccumulatedUsage?.(W)]);return N1({session:Z,messages:Q,usage:J?.usage,aggregateUsage:J?.aggregateUsage})}function CY($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(Q==="creator"&&!j.createdByClientId)j.createdByClientId=Z;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={createdByClientId:Z,interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}function y_($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}async function PY($,W){let Z=Am("approval_"),Q=W.sessionId;if($.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((j)=>{$.pendingApprovals.set(Z,{sessionId:Q,resolve:j}),$.publish($.buildEvent("approval.requested",{approvalId:Z,sessionId:W.sessionId,agentId:W.agentId,conversationId:W.conversationId,iteration:W.iteration,toolCallId:W.toolCallId,toolName:W.toolName,inputJson:JSON.stringify(W.input??null),policy:W.policy},Q))})}function SY($,W,Z){let Q=$.pendingApprovals.get(W);if(!Q)return;return $.pendingApprovals.delete(W),Q.resolve(Z),{sessionId:Q.sessionId}}function bY($,W,Z){let Q=0;for(let[J,j]of[...$.pendingApprovals.entries()]){if(!W({approvalId:J,sessionId:j.sessionId}))continue;$.pendingApprovals.delete(J),j.resolve({approved:!1,reason:Z}),$.publish($.buildEvent("approval.resolved",{approvalId:J,approved:!1,cancelled:!0,reason:Z},j.sessionId)),Q+=1}return Q}async function h_($,W){let Z=typeof W.payload?.approvalId==="string"?W.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Z))return h(W,"approval_not_found",`Unknown approval: ${Z}`);let J=typeof W.payload?.reason==="string"?W.payload.reason:W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)&&typeof W.payload.payload.reason==="string"?W.payload.payload.reason:void 0,j=W.payload?.approved===!0,X=SY($,Z,{approved:j,reason:J});if(!X)return h(W,"approval_not_found",`Unknown approval: ${Z}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:j,reason:J},X.sessionId)),u(W,{approvalId:Z,approved:j})}import{createSessionId as _m}from"@cline/shared";function Um($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var k_={debug:10,info:20,warn:30,error:40,silent:50};function Dm(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function i($,W,Z={}){if(k_[$]<k_[Dm()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:W,...Object.fromEntries(Object.entries(Z).map(([J,j])=>[J,Um(j)]).filter(([,J])=>J!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function yY($,W){let Z=W instanceof Error?W.stack||W.message:String(W);i("error",$,{error:Z})}async function I_($,W,Z,Q,J,j){let X=_m("capreq_"),Y=performance.now();return i("info","capability.request.start",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J}),await new Promise((V,B)=>{$.pendingCapabilityRequests.set(X,{sessionId:W,targetClientId:J,capabilityName:Z,onProgress:j,resolve:(H)=>{if(i(H.ok?"info":"warn","capability.request.end",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J,ok:H.ok,error:H.error,durationMs:Math.round(performance.now()-Y)}),!H.ok){B(Error(H.error||`Capability ${Z} was rejected by ${J}.`));return}V(H.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:X,targetClientId:J,capabilityName:Z,payload:Q},W)),i("info","capability.request.published",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J})})}function x_($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);if((W.clientId?.trim()||"")!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{};return Q.onProgress?.(j),u(W,{requestId:Z})}function t$($,W,Z){let Q=0;for(let[J,j]of[...$.pendingCapabilityRequests.entries()]){if(!W({requestId:J,...j}))continue;$.pendingCapabilityRequests.delete(J),i("warn","capability.request.cancelled",{requestId:J,sessionId:j.sessionId,capabilityName:j.capabilityName,targetClientId:j.targetClientId,reason:Z}),j.resolve({ok:!1,error:Z}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:j.capabilityName,targetClientId:j.targetClientId,ok:!1,cancelled:!0,error:Z},j.sessionId)),Q+=1}return Q}async function g_($,W){let Z=typeof W.payload?.sessionId==="string"?W.payload.sessionId.trim():W.sessionId?.trim()||"",Q=typeof W.payload?.capabilityName==="string"?W.payload.capabilityName.trim():"",J=typeof W.payload?.targetClientId==="string"?W.payload.targetClientId.trim():"";if(!Z||!Q||!J)return h(W,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{},X=await $.requestCapability(Z,Q,j,J);return u(W,X)}catch(j){return h(W,"capability_request_failed",j instanceof Error?j.message:String(j))}}function m_($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);let J=W.clientId?.trim()||"";if(J!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);$.pendingCapabilityRequests.delete(Z);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:void 0,X=typeof W.payload?.error==="string"?W.payload.error:void 0,Y=W.payload?.ok===!0;return i(Y?"info":"warn","capability.respond",{requestId:Z,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,error:X}),Q.resolve({ok:Y,payload:j,error:X}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,payload:j,error:X},Q.sessionId)),u(W,{requestId:Z,ok:Y})}import{createSessionId as fm}from"@cline/shared";function v_($,W){let Z=W.payload,Q=Z?.clientId?.trim()||W.clientId?.trim()||fm("client_");return $.clients.set(Q,{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,actorKind:Z?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Z?.transport??"native",capabilities:Z?.capabilities??[],metadata:Z?.metadata,workspaceContext:Z?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,connectedAt:Date.now()})),u(W,{clientId:Q})}function c_($,W){let Z=W.clientId?.trim(),Q=Z?$.clients.get(Z):void 0;if(!Z||!Q)return h(W,"client_not_found","Client is not registered with this hub.");let J=s6(W.payload?.metadata);if(Q.lastSeenAt=Date.now(),J)Q.metadata=JSON.parse(JSON.stringify(J));return u(W)}function u_($,W,Z){let Q=W.clientId?.trim();if(Q)$.clients.delete(Q),Z(Q),$.publish($.buildEvent("hub.client.disconnected",{clientId:Q}));return u(W)}function d_($,W){return u(W,{clients:[...$.clients.values()]})}z0();import{existsSync as r_,mkdirSync as Lm,readdirSync as Tm,readFileSync as Om,rmSync as zm,writeFileSync as qm}from"node:fs";import{dirname as Mm,join as l_}from"node:path";import{CONNECTOR_PLATFORMS as Rm,connectorChannelsFromPlatforms as Em,listConnectorCatalog as i_,shouldIncludeConnectorField as Nm}from"@cline/shared";import{resolveConnectorDataDir as wm,resolveConnectorSettingsPath as kY}from"@cline/shared/storage";var Cm=1,p_={startedAt:($)=>typeof $.startedAt==="string"?$.startedAt:void 0,port:($)=>typeof $.port==="number"?$.port:void 0,baseUrl:($)=>typeof $.baseUrl==="string"?$.baseUrl:void 0,connectionMode:($)=>typeof $.connectionMode==="string"?$.connectionMode:void 0,userName:($)=>typeof $.userName==="string"?$.userName:void 0,botUsername:($)=>typeof $.botUsername==="string"?$.botUsername:void 0,applicationId:($)=>typeof $.applicationId==="string"?$.applicationId:void 0,phoneNumberId:($)=>typeof $.phoneNumberId==="string"?$.phoneNumberId:void 0},Pm={discord:{required:["userName","applicationId"],optional:["startedAt","port","baseUrl"]},telegram:{required:["botUsername"],optional:["startedAt"]},gchat:{required:["userName"],optional:["startedAt","port","baseUrl"]},linear:{required:["userName"],optional:["startedAt","port","baseUrl"]},slack:{required:["userName"],optional:["startedAt","connectionMode","port","baseUrl"]},whatsapp:{required:["userName"],optional:["startedAt","phoneNumberId","port","baseUrl"]}};function e$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function v9($){return typeof $==="string"?$.trim():void 0}function n_($){if(!r_($))return;try{let W=JSON.parse(Om($,"utf8"));return e$(W)?W:void 0}catch{return}}function IY(){let $=n_(kY()),W=e$($?.connectors)?$.connectors:{},Z={};for(let[Q,J]of Object.entries(W)){if(!e$(J))continue;let j=v9(J.type),X=v9(J.configuredAt),Y=v9(J.updatedAt);if(!j||!X||!Y)continue;let V=R7(J.values),B=e$(J.security)?{enabled:J.security.enabled===!0,values:R7(J.security.values)}:void 0;Z[Q]={type:j,values:V,security:B,configuredAt:X,updatedAt:Y}}return{version:Cm,connectors:Z}}function a_($){let W=kY();Lm(Mm(W),{recursive:!0}),qm(W,`${JSON.stringify($,null,2)}
743
+ `,"utf8")}function R7($){if(!e$($))return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q.trim();return W}function Sm($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function bm($){let W=l_(wm(),$);if(!r_(W))return[];return Tm(W).filter((Z)=>Z.endsWith(".json")&&!Z.endsWith(".threads.json")).map((Z)=>l_(W,Z))}function ym($,W,Z){let Q=W.botUsername??W.userName??W.applicationId??W.phoneNumberId??String(Z);return`${$}:${Q}`}function hm($,W){let Z=n_(W);if(!Z)return;let Q=typeof Z.pid==="number"?Z.pid:void 0,J=typeof Z.hubUrl==="string"?Z.hubUrl:typeof Z.rpcAddress==="string"?Z.rpcAddress:void 0;if(!Q||!J||!Sm(Q))return;let j=Pm[$];if(!j)return;let X={};for(let Y of j.required){let V=p_[Y](Z);if(!V||typeof V==="string"&&!V.trim())return;X[Y]=V}for(let Y of j.optional){let V=p_[Y](Z);if(V!==void 0)X[Y]=V}return{id:ym($,X,Q),type:$,pid:Q,hubUrl:J,...X}}function km(){let $=[];for(let{name:W}of i_())for(let Z of bm(W)){let Q=hm(W,Z);if(Q)$.push(Q)}return $.sort((W,Z)=>{if(W.type!==Z.type)return W.type.localeCompare(Z.type);let Q=W.botUsername??W.userName??"",J=Z.botUsername??Z.userName??"";return Q.localeCompare(J)})}function Im(){let $=IY();return Object.entries($.connectors).map(([W,Z])=>({id:W,type:Z.type,configuredAt:Z.configuredAt,updatedAt:Z.updatedAt})).sort((W,Z)=>W.type.localeCompare(Z.type))}function xY(){return{available:Em(),active:km(),configured:Im()}}function xm($,W){if($.required&&!W[$.flag]?.trim())throw Error(`${$.label} is required`)}function gm($,W){let Z={};for(let J of $.fields)Z[J.flag]=W[J.flag]??J.initialValue??"";let Q={};for(let J of $.fields){if(!Nm(J,Z))continue;xm(J,Z),Q[J.flag]=Z[J.flag]}return Q}function mm($){if(!e$($))throw Error("connector.configure payload must be an object.");let W=v9($.channel);if(!W)throw Error("channel is required");let Z=Rm.find((K)=>K.id===W);if(!Z)throw Error(`unknown connector channel: ${W}`);if(!new Set(i_().map((K)=>K.name)).has(Z.id))throw Error(`connector channel is not available: ${W}`);let J=R7($.values),j=gm(Z,J),X=e$($.security)?$.security:{},Y=X.enabled===!0,V=R7(X.values);if(Y&&Z.security)for(let K of Z.security.fields){let F=V[K.key];if(!F)throw Error(K.requiredMessage);let A=K.validate?.(F);if(A)throw Error(A)}let B=IY(),H=new Date().toISOString(),G=B.connectors[W];return B.connectors[W]={type:W,values:j,security:Y?{enabled:!0,values:V}:{enabled:!1,values:{}},configuredAt:G?.configuredAt??H,updatedAt:H},a_(B),xY()}function vm($){if(!e$($))throw Error("connector.delete_config payload must be an object.");let W=v9($.channel);if(!W)throw Error("channel is required");let Z=IY();if(delete Z.connectors[W],Object.keys(Z.connectors).length>0)a_(Z);else zm(kY(),{force:!0});return xY()}function cm($){return $==="connector.configure"||$==="connector.delete_config"}function hY($,W,Z){if(!cm(W.command))return;T8($.telemetry,{ulid:W.sessionId??W.requestId??"hub",tool:W.command,success:Z})}async function o_($,W){try{if(W.command==="connector.channels")return u(W,xY());if(W.command==="connector.configure"){let Z=mm(W.payload);return hY($,W,!0),u(W,Z)}if(W.command==="connector.delete_config"){let Z=vm(W.payload);return hY($,W,!0),u(W,Z)}return h(W,"unsupported_connector_command",`unsupported connector command: ${W.command}`)}catch(Z){return hY($,W,!1),h(W,"connector_command_failed",Z instanceof Error?Z.message:String(Z))}}var um=30000;function dm($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function lm($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function pm($,W,Z){let Q=Z instanceof Error&&Z.message.trim()?Z.message:`Unknown session: ${W}`;return h($,X2,Q)}function rm($){return $?$:void 0}function im($){let W=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(W&&Number.isFinite(W)&&W>0)return Math.floor(W);let Z=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Z&&Number.isFinite(Z)&&Z>0)return Math.floor(Z*1000);return}async function nm($,W,Z,Q){let J=performance.now(),j=!1,X={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z.sessionId,timeoutMs:Q},Y=setInterval(()=>{if(j)return;let H=Math.round(performance.now()-J);i("warn","run.heartbeat",{...X,elapsedMs:H}),$.publish($.buildEvent("run.heartbeat",{requestId:W.requestId,elapsedMs:H,...Q?{timeoutMs:Q}:{}},Z.sessionId))},um),V=$.sessionHost.runTurn(Z);V.then((H)=>{if(!j)return;i("warn","run.late_end",{...X,elapsedMs:Math.round(performance.now()-J),finishReason:H?.finishReason})},(H)=>{if(!j)return;i("error","run.late_error",{...X,elapsedMs:Math.round(performance.now()-J),error:H})});let B;try{if(!Q)return await V;return await Promise.race([V,new Promise((H,G)=>{B=setTimeout(()=>{let K=`Hub run ${W.command} timed out after ${Q}ms.`;j=!0,clearInterval(Y),G(Error(K)),i("error","run.timeout",{...X,elapsedMs:Math.round(performance.now()-J)}),bY($,(F)=>F.sessionId===Z.sessionId,K),t$($,(F)=>F.sessionId===Z.sessionId,K),$.sessionHost.abort(Z.sessionId,K).catch((F)=>{i("error","run.timeout_abort_failed",{...X,error:F})})},Q)})])}finally{if(j=!0,clearInterval(Y),B)clearTimeout(B)}}async function s_($,W){let Z=S0(W),Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!J.trim())return h(W,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Z));let j=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,X=Array.isArray(j?.userFiles)?j.userFiles.filter((H)=>typeof H==="string"):void 0,Y=im(Q);$.suppressNextTerminalEventBySession.set(Z,"run.start.reply");let V;try{V=await nm($,W,{sessionId:Z,prompt:J,mode:rm(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(j?.userImages)?j.userImages:void 0,userFiles:X,timeoutMs:Y},Y)}catch(H){if($.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z);if(p1(H))return pm(W,Z,H);throw $.publish($.buildEvent("run.failed",{reason:"error",error:H instanceof Error?H.message:String(H)},Z)),H}if(V){let H=await u0($,Z),G=lm(V);if($.publish($.buildEvent(dm(V.finishReason),{reason:V.finishReason,...G?{error:G}:{},result:V,...H?{snapshot:H}:{}},Z)),$.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z)}else $.suppressNextTerminalEventBySession.delete(Z);let B=await u0($,Z);return u(W,V||B?{...V?{result:V}:{},...B?{snapshot:B}:{}}:void 0)}async function t_($,W){let Z=S0(W),Q=typeof W.payload?.reason==="string"?W.payload.reason:"Run was aborted before pending approval or capability request was resolved.";bY($,(J)=>J.sessionId===Z,Q);try{await $.sessionHost.abort(Z,W.payload?.reason)}catch(J){i("warn","run.abort_failed",{command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z,error:J})}finally{t$($,(J)=>J.sessionId===Z,Q)}return u(W,{applied:!0})}async function e_($,W){let Z=m6(W.payload?.payload);if(!Z)return h(W,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Z),u(W,{applied:!0})}async function $f($,W){switch(W.type){case"chunk":return;case"agent_event":await am($,W);return;case"hook":if(W.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:W.payload.toolName},W.payload.sessionId));else if(W.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:W.payload.toolName},W.payload.sessionId));return;case"team_progress":{let Z={type:"team_progress_projection",version:1,sessionId:W.payload.sessionId,summary:W.payload.summary,lastEvent:W.payload.lifecycle};$.publish($.buildEvent("team.progress",Z,W.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:W.payload.sessionId,prompts:W.payload.prompts},W.payload.sessionId));return;case"pending_prompt_submitted":{let Z={id:W.payload.id,prompt:W.payload.prompt,delivery:W.payload.delivery,attachmentCount:W.payload.attachmentCount,userImages:W.payload.userImages,userFiles:W.payload.userFiles};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:W.payload.sessionId,prompt:Z},W.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:W.payload.sessionId,snapshot:W.payload.snapshot},W.payload.sessionId));return;case"status":{let[Z,Q]=await Promise.all([b0($,W.payload.sessionId),u0($,W.payload.sessionId)]);if(Z)$.publish($.buildEvent("session.updated",{session:Z,...Q?{snapshot:Q}:{}},W.payload.sessionId));return}case"ended":await om($,W);return;default:return}}async function am($,W){let{sessionId:Z,event:Q}=W.payload;if(Q.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Q.iteration},Z));return}if(Q.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},Z));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Q.text},Z));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Z));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},Z));return}if(Q.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},Z));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Q.text},Z));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Q.reasoning},Z));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},Z));break}return}if(Q.type==="notice"){$.publish($.buildEvent("session.notice",{sessionId:Z,message:Q.message,noticeType:Q.noticeType,...Q.displayRole?{displayRole:Q.displayRole}:{},...Q.reason?{reason:Q.reason}:{},...Q.metadata?{metadata:Q.metadata}:{},agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="usage"){let J;try{J=await $.sessionHost.getAccumulatedUsage?.(Z)}catch{J=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Z,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:J?.usage,aggregateUsage:J?.aggregateUsage,agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="done")$.publish($.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},Z))}async function om($,W){let Z=$.suppressNextTerminalEventBySession.get(W.payload.sessionId),Q=Z===W.payload.reason||Z==="run.start.reply";if(Q)$.suppressNextTerminalEventBySession.delete(W.payload.sessionId);let[J,j]=await Promise.all([b0($,W.payload.sessionId),u0($,W.payload.sessionId)]);if(W.payload.reason==="completed"){let X=await b_(J);$.publish($.buildEvent("ui.notify",X,W.payload.sessionId))}if(Q)return;$.publish($.buildEvent(W.payload.reason==="aborted"?"run.aborted":W.payload.reason==="error"||W.payload.reason==="failed"?"run.failed":"run.completed",{reason:W.payload.reason,...j?{snapshot:j}:{}},W.payload.sessionId))}import{createSessionId as Jf,parseRuntimeConfigExtensions as jf}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as p20,HUB_COMPACTION_CAPABILITY as r20,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as i20,HUB_HOOK_CAPABILITY_PREFIX as n20,HUB_MISTAKE_LIMIT_CAPABILITY as a20,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as o20,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as s20,isHubToolExecutorName as sm}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Q80,HUB_COMPACTION_CAPABILITY as J80,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as j80,HUB_HOOK_CAPABILITY_PREFIX as X80,HUB_MISTAKE_LIMIT_CAPABILITY as Y80,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as V80,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as B80}from"@cline/shared";var tm=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function G8($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function em($,W){let Z=typeof $.name==="string"?$.name.trim():"",Q=typeof $.description==="string"?$.description:"",J=typeof $.capabilityName==="string"?$.capabilityName.trim():"",j=G8($.inputSchema);if(!Z||!Q||!j||!J||W.has(J))return;return W.add(J),{kind:"tool",capabilityName:J,name:Z,description:Q,inputSchema:j,...G8($.lifecycle)?{lifecycle:G8($.lifecycle)}:{}}}function mY($){if(!Array.isArray($))return[];let W=[],Z=new Set;for(let Q of $){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let J=Q,j=J.kind,X=typeof J.capabilityName==="string"?J.capabilityName.trim():"";if(!X||Z.has(X))continue;if(j==="tool"){let Y=em(J,Z);if(Y)W.push(Y);continue}if(j==="toolExecutor"){let Y=J.executor;if(!sm(Y))continue;Z.add(X),W.push({kind:"toolExecutor",capabilityName:X,executor:Y});continue}if(j==="hook"){let Y=typeof J.name==="string"?J.name.trim():"";if(!Y)continue;Z.add(X),W.push({kind:"hook",capabilityName:X,name:Y});continue}if(j==="compaction"){Z.add(X),W.push({kind:"compaction",capabilityName:X,...G8(J.config)?{config:G8(J.config)}:{}});continue}if(j==="checkpoint"){Z.add(X),W.push({kind:"checkpoint",capabilityName:X,...G8(J.config)?{config:G8(J.config)}:{}});continue}if(j==="mistakeLimit"){Z.add(X),W.push({kind:"mistakeLimit",capabilityName:X});continue}if(j==="userInstructionService")Z.add(X),W.push({kind:"userInstructionService",capabilityName:X})}return W}function Zf($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W[nW];return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:W&&Object.keys(W).length>0?W:void 0}}function $v($){return Object.hasOwn($,"update")?$.update:$}function c9($){return $.trim().replace(/^\/+/,"").toLowerCase()}function Wv($){let W=($??[]).map(c9).filter(Boolean);return W.length>0?new Set(W):void 0}function Zv($,W,Z){if(!Z)return!0;let Q=c9($),J=c9(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function gY($,W){let Z=Wv(W);return $.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>Zv(Q.id,Q.name,Z))}function Wf($,W){let Z=async(Q,J)=>{let j=c9(Q),Y=gY($,W).filter((K)=>K.id===j||c9(K.name)===j||K.id.endsWith(`:${j}`)).filter((K)=>!K.disabled);if(Y.length!==1)return Y.length>1?`Skill "${Q}" is ambiguous. Use one of: ${Y.map((K)=>K.id).join(", ")}`:`Skill "${Q}" not found.`;let V=Y[0].skill,B=J?.trim(),H=B?`
744
744
  <command-args>${B}</command-args>`:"",G=V.description?.trim()?`Description: ${V.description.trim()}
745
745
 
746
746
  `:"";return`<command-name>${V.name}</command-name>${H}
747
747
  <command-instructions>
748
748
  ${G}${V.instructions}
749
- </command-instructions>`};return Object.defineProperty(Z,"configuredSkills",{get:()=>xY($,W).map(({skill:Q,...J})=>J),enumerable:!0}),Z}function Zv($,W,Z,Q){let J={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},j=async()=>{let X=await Q($,Z.capabilityName,{},W);if(X?.snapshot)J=X.snapshot};return{start:j,stop:()=>{},refreshType:async()=>{await j()},listRecords:(X)=>[...J.records[X]],listRuntimeCommands:()=>[...J.runtimeCommands],resolveRuntimeSlashCommand:(X)=>{if(!X.startsWith("/")||X.length<2)return X;let V=X.match(/^\/(\S+)/)?.[1];if(!V)return X;let B=J.runtimeCommands.find((H)=>H.name===V);return B?`${B.instructions}${X.slice(V.length+1)}`:X},hasConfiguredSkills:(X)=>xY(J,X).some((Y)=>!Y.disabled),createSkillsExecutor:(X)=>$f(J,X),createExtension:(X)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[X.includeRules?"rules":void 0,X.registerSkillsTool?"tools":void 0,X.includeSkills||X.includeWorkflows?"commands":void 0].filter((Y)=>Boolean(Y))},setup(Y){if(X.includeRules)Y.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>U8(J.records.rule.map((V)=>V.item).filter((V)=>V.disabled!==!0))});if(X.registerSkillsTool)Y.registerTool(O2($f(J,X.allowedSkillNames)));for(let V of J.runtimeCommands.filter((B)=>B.kind==="skill"&&X.includeSkills||B.kind==="workflow"&&X.includeWorkflows))Y.registerCommand({name:V.name,description:V.description,handler:(B)=>{let H=B.trim();return H?`${V.instructions}
749
+ </command-instructions>`};return Object.defineProperty(Z,"configuredSkills",{get:()=>gY($,W).map(({skill:Q,...J})=>J),enumerable:!0}),Z}function Qv($,W,Z,Q){let J={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},j=async()=>{let X=await Q($,Z.capabilityName,{},W);if(X?.snapshot)J=X.snapshot};return{start:j,stop:()=>{},refreshType:async()=>{await j()},listRecords:(X)=>[...J.records[X]],listRuntimeCommands:()=>[...J.runtimeCommands],resolveRuntimeSlashCommand:(X)=>{if(!X.startsWith("/")||X.length<2)return X;let V=X.match(/^\/(\S+)/)?.[1];if(!V)return X;let B=J.runtimeCommands.find((H)=>H.name===V);return B?`${B.instructions}${X.slice(V.length+1)}`:X},hasConfiguredSkills:(X)=>gY(J,X).some((Y)=>!Y.disabled),createSkillsExecutor:(X)=>Wf(J,X),createExtension:(X)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[X.includeRules?"rules":void 0,X.registerSkillsTool?"tools":void 0,X.includeSkills||X.includeWorkflows?"commands":void 0].filter((Y)=>Boolean(Y))},setup(Y){if(X.includeRules)Y.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>U8(J.records.rule.map((V)=>V.item).filter((V)=>V.disabled!==!0))});if(X.registerSkillsTool)Y.registerTool(O2(Wf(J,X.allowedSkillNames)));for(let V of J.runtimeCommands.filter((B)=>B.kind==="skill"&&X.includeSkills||B.kind==="workflow"&&X.includeWorkflows))Y.registerCommand({name:V.name,description:V.description,handler:(B)=>{let H=B.trim();return H?`${V.instructions}
750
750
 
751
- ${H}`:V.instructions}})}})}}function Qv($,W,Z,Q){let J=Z.map((j)=>[j.executor,async(...X)=>{let Y=X.at(-1),V=X.slice(0,-1);return(await Q($,j.capabilityName,{executor:j.executor,args:V,context:Wf(Y)},W))?.result}]);return J.length>0?Object.fromEntries(J):void 0}function Jv($,W,Z,Q){if(Z.length===0)return;return Z.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,lifecycle:J.lifecycle,async execute(j,X){return(await Q($,J.capabilityName,{toolName:J.name,input:j,context:Wf(X)},W,X.emitUpdate?(V)=>{X.emitUpdate?.(em(V))}:void 0))?.result}}))}function jv($,W,Z,Q){let J=new Map(Z.map((X)=>[X.name,X])),j={};for(let X of sm){let Y=J.get(X);if(!Y)continue;j[X]=async(V)=>{return(await Q($,Y.capabilityName,{context:V},W))?.control}}return Object.keys(j).length>0?j:void 0}function mY($){let W=$.contributions.filter((V)=>V.kind==="toolExecutor"),Z=$.contributions.filter((V)=>V.kind==="tool"),Q=$.contributions.filter((V)=>V.kind==="hook"),J=$.contributions.find((V)=>V.kind==="compaction"),j=$.contributions.find((V)=>V.kind==="checkpoint"),X=$.contributions.find((V)=>V.kind==="mistakeLimit"),Y=$.contributions.find((V)=>V.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:Qv($.sessionId,$.targetClientId,W,$.requestCapability),localRuntime:{...Q.length>0?{hooks:jv($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...Z.length>0?{extraTools:Jv($.sessionId,$.targetClientId,Z,$.requestCapability)}:{},...J?{compaction:{...$.sessionConfig?.compaction??{},...J.config,compact:async(V)=>{return(await $.requestCapability($.sessionId,J.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...j?{checkpoint:{...$.sessionConfig?.checkpoint??{},...j.config,createCheckpoint:async(V)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...X?{onConsecutiveMistakeLimitReached:async(V)=>{return(await $.requestCapability($.sessionId,X.capabilityName,{context:V},$.targetClientId))?.result}}:{},...Y?{userInstructionService:Zv($.sessionId,$.targetClientId,Y,$.requestCapability)}:{}}}}var Zf="hubCapabilityOwnerClientId";function R7($){return typeof $==="string"&&$.trim().length>0?$.trim():void 0}function Xv($){if($==="low"||$==="medium"||$==="high"||$==="xhigh"||$===null)return $;return}function Yv($){let W=s6($)??{},Z={},Q=R7(W.providerId);if(Q)Z.providerId=Q;let J=R7(W.modelId);if(J)Z.modelId=J;let j=R7(W.apiKey);if(j!==void 0)Z.apiKey=j;let X=R7(W.baseUrl);if(X!==void 0)Z.baseUrl=X;if(W.headers&&typeof W.headers==="object")Z.headers=W.headers;if(W.providerConfig&&typeof W.providerConfig==="object")Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"thinking")){if(typeof W.thinking==="boolean"||W.thinking===null)Z.thinking=W.thinking}if(Object.hasOwn(W,"reasoningEffort")){let Y=Xv(W.reasoningEffort);if(Y!==void 0)Z.reasoningEffort=Y}if(Object.hasOwn(W,"thinkingBudgetTokens")){if(typeof W.thinkingBudgetTokens==="number"&&Number.isFinite(W.thinkingBudgetTokens)&&W.thinkingBudgetTokens>0)Z.thinkingBudgetTokens=Math.trunc(W.thinkingBudgetTokens);else if(W.thinkingBudgetTokens===null)Z.thinkingBudgetTokens=null}return w2(Z)}function Vv($,W){return $.sessionState.get(W)?.createdByClientId}function Bv($){if(!$||!(Zf in $))return $;let W={...$};return delete W[Zf],W}function jf($){let W=Vv($.ctx,$.sessionId);if(!W)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} has no owner`);if(W!==$.clientId)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} is owned by ${W}`);return}async function Xf($,W,Z){let Q=performance.now(),J={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:W.sessionId};i("info","session.create.begin",J);let j=W.payload&&typeof W.payload==="object"?W.payload:{},X=j.metadata&&typeof j.metadata==="object"?JSON.parse(JSON.stringify(j.metadata)):{},Y=j.sessionConfig&&typeof j.sessionConfig==="object"?JSON.parse(JSON.stringify(j.sessionConfig)):void 0,V=j.runtimeOptions&&typeof j.runtimeOptions==="object"?j.runtimeOptions:{},B=G1(j.initialCompactionState);if(typeof Y?.mode==="string")X.mode=Y.mode;else if(typeof V.mode==="string")X.mode=V.mode;if(typeof Y?.systemPrompt==="string")X.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")X.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)X.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)X.checkpointEnabled=!0;let H=j.modelSelection&&typeof j.modelSelection==="object"?j.modelSelection:{},G=typeof j.workspaceRoot==="string"&&j.workspaceRoot.trim()?j.workspaceRoot.trim():typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():"";if(!G)return i("warn","session.create.invalid",{...J,reason:"missing_workspace_root"}),h(W,"invalid_session_create","session.create requires workspaceRoot or cwd");let K=W.clientId?.trim()||"hub-client",F=gY(V.clientContributions);i("info","session.create.contributions_parsed",{...J,clientId:K,workspaceRoot:G,cwd:typeof j.cwd==="string"?j.cwd:void 0,contributionCount:F.length});let D=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||Qf(),U=Jf(V.configExtensions);i("info","session.create.runtime_build.begin",{...J,sessionId:D,configExtensionCount:U?.length??0});let f=mY({sessionId:D,targetClientId:K,contributions:F,sessionConfig:Y,requestCapability:$.requestCapability});i("info","session.create.start_session.begin",{...J,sessionId:D,provider:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),model:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub")});let _=await $.sessionHost.startSession({source:typeof X.source==="string"?X.source:void 0,interactive:X.interactive!==!1,sessionMetadata:Object.keys(X).length>0?X:void 0,initialMessages:Array.isArray(j.initialMessages)?j.initialMessages:void 0,initialCompactionState:B,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:U,...f.localRuntime},capabilities:{toolExecutors:f.toolExecutors,requestToolApproval:Z},config:{...Y??{},sessionId:D,providerId:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),modelId:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub"),apiKey:Y?.apiKey??(typeof H.apiKey==="string"?H.apiKey:void 0),cwd:Y?.cwd??(typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():G),workspaceRoot:Y?.workspaceRoot??G,systemPrompt:Y?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:Y?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:Y?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:Y?.enableTools??V.enableTools!==!1,enableSpawnAgent:Y?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:Y?.enableAgentTeams??V.enableTeams!==!1,checkpoint:Y?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:Y?.teamName??(typeof X.teamName==="string"?X.teamName:void 0)},toolPolicies:j.toolPolicies&&typeof j.toolPolicies==="object"&&!Array.isArray(j.toolPolicies)?JSON.parse(JSON.stringify(j.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});i("info","session.create.start_session.end",{...J,sessionId:_.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!_.result}),wY($,_.sessionId,K,"creator",{interactive:X.interactive!==!1}),i("info","session.create.read_records.begin",{...J,sessionId:_.sessionId});let[R,O]=await Promise.all([b0($,_.sessionId),u0($,_.sessionId)]);if(i("info","session.create.read_records.end",{...J,sessionId:_.sessionId,hasSession:!!R,hasSnapshot:!!O,elapsedMs:Math.round(performance.now()-Q)}),R)$.publish($.buildEvent("session.created",{session:R,...O?{snapshot:O}:{}},_.sessionId));return i("info","session.create.reply",{...J,sessionId:_.sessionId,elapsedMs:Math.round(performance.now()-Q)}),u(W,{session:R,...O?{snapshot:O}:{}})}async function Yf($,W,Z){let Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.sessionId==="string"?Q.sessionId.trim():W.sessionId?.trim()||"",j=Q.checkpointRunCount;if(!J)return h(W,"invalid_restore","session.restore requires a session id");let X=Q.restore&&typeof Q.restore==="object"?Q.restore:{},Y=X.messages!==!1;if(typeof j!=="number")return h(W,"invalid_restore","checkpointRunCount must be a positive integer");try{let V=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(Y&&!V)return h(W,"invalid_restore","sessionConfig is required when restore.messages is true");let B=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},H=G1(Q.initialCompactionState),G=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof V?.mode==="string")G.mode=V.mode;else if(typeof B.mode==="string")G.mode=B.mode;if(typeof V?.systemPrompt==="string")G.systemPrompt=V.systemPrompt;else if(typeof B.systemPrompt==="string")G.systemPrompt=B.systemPrompt;if(V?.checkpoint?.enabled===!0)G.checkpointEnabled=!0;else if(B.checkpointEnabled===!0)G.checkpointEnabled=!0;let K=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},F=W.clientId?.trim()||"hub-client",A=gY(B.clientContributions),U=(typeof V?.sessionId==="string"?V.sessionId.trim():"")||Qf(),f=Jf(B.configExtensions),_=mY({sessionId:U,targetClientId:F,contributions:A,sessionConfig:V,requestCapability:$.requestCapability}),O=await new o$().restoreCheckpoint({sessionId:J,checkpointRunCount:j,restore:{messages:X.messages,workspace:X.workspace,omitCheckpointMessageFromSession:X.omitCheckpointMessageFromSession===!0},start:V,cwd:typeof V?.cwd==="string"&&V.cwd.trim()||typeof V?.workspaceRoot==="string"&&V.workspaceRoot.trim()||void 0,getSession:(E)=>$.sessionHost.getSession(E),readMessages:(E)=>$.sessionHost.readSessionMessages(E),buildStartInput:(E)=>{if(E.restoredCheckpointMetadata)G.checkpoint=E.restoredCheckpointMetadata;let p=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():E.sourceSession.workspaceRoot||E.sourceSession.cwd;return{source:typeof G.source==="string"?G.source:void 0,interactive:G.interactive!==!1,sessionMetadata:{...G,restoredFromSessionId:J,restoredCheckpointRunCount:j},initialMessages:E.initialMessages,initialCompactionState:H,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:f,..._.localRuntime},capabilities:{toolExecutors:_.toolExecutors,requestToolApproval:Z},config:{...V??{},sessionId:U,providerId:V?.providerId??(typeof K.provider==="string"?K.provider:E.sourceSession.provider),modelId:V?.modelId??(typeof K.model==="string"?K.model:E.sourceSession.model),apiKey:V?.apiKey??(typeof K.apiKey==="string"?K.apiKey:""),cwd:V?.cwd??E.plan.cwd,workspaceRoot:V?.workspaceRoot??p,systemPrompt:V?.systemPrompt??(typeof B.systemPrompt==="string"?B.systemPrompt:""),mode:V?.mode??(B.mode==="plan"||B.mode==="yolo"?B.mode:"act"),maxIterations:V?.maxIterations??(typeof B.maxIterations==="number"?B.maxIterations:void 0),enableTools:V?.enableTools??B.enableTools!==!1,enableSpawnAgent:V?.enableSpawnAgent??B.enableSpawn!==!1,enableAgentTeams:V?.enableAgentTeams??B.enableTeams!==!1,checkpoint:V?.checkpoint??(B.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:V?.teamName??(typeof G.teamName==="string"?G.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):B.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(E)=>$.sessionHost.startSession(E),getStartedSessionId:(E)=>E.sessionId,readRestoredSession:(E)=>$.sessionHost.getSession(E)});if(!Y)return u(W,{checkpoint:O.checkpoint});let T=O.startResult;if(!T)return h(W,"restore_failed","Checkpoint restore did not start a session");wY($,T.sessionId,F,"creator",{interactive:G.interactive!==!1});let[L,C]=await Promise.all([b0($,T.sessionId),u0($,T.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...C?{snapshot:C}:{}},T.sessionId));return u(W,{session:L,...C?{snapshot:C}:{},messages:O.messages??[],checkpoint:O.checkpoint})}catch(V){if(V instanceof c0)return h(W,V.code,V.code==="session_not_found"?`Unknown session: ${J}`:V.message);return h(W,"restore_failed",V instanceof Error?V.message:String(V))}}async function Vf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_attach","session.attach requires a session id");let Q=await b0($,Z);if(!Q)return h(W,"session_not_found",`Unknown session: ${Z}`);b_($,Z,W.clientId?.trim()||"hub-client","participant");let J=await b0($,Z);return $.publish($.buildEvent("session.attached",{session:J??Q},Z)),u(W,{session:J??Q})}async function Bf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_detach","session.detach requires a session id");let Q=W.clientId?.trim()||"hub-client",J=$.sessionState.get(Z);if(J){if(J.participants.delete(Q),J.createdByClientId===Q)J.createdByClientId=void 0;if(J.participants.size===0)$.sessionState.delete(Z)}t$($,(Y)=>Y.sessionId===Z&&Y.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[j,X]=await Promise.all([b0($,Z),u0($,Z)]);return $.publish($.buildEvent("session.detached",j?{session:j,...X?{snapshot:X}:{},clientId:Q}:{clientId:Q},Z)),u(W)}async function Hf($,W){let Z=S0(W),Q=W.payload?.includeSnapshot===!0,[J,j]=await Promise.all([b0($,Z),Q?u0($,Z):Promise.resolve(void 0)]);return J?u(W,{session:J,...j?{snapshot:j}:{}}):h(W,"session_not_found",`Unknown session: ${Z}`)}async function Gf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.messages requires a session id");if(!await b0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=await $.sessionHost.readSessionMessages(Z);return u(W,{sessionId:Z,messages:J})}async function Kf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.get requires a session id");if(!await b0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=W.clientId?.trim()||"hub-client",j=jf({sessionId:Z,ctx:$,clientId:J,envelope:W});if(j)return j;let X=await $.sessionHost.readSessionCompactionState(Z);return u(W,{sessionId:Z,state:X})}async function Ff($,W){let Z=typeof W.payload?.limit==="number"?W.payload.limit:200,J=(await $.sessionHost.listSessions(Z)).map((j)=>q7(j,$.sessionState.get(j.sessionId)));return u(W,{sessions:J})}async function Af($,W){let Z=S0(W),Q=Bv(s6(W.payload?.metadata)),J=await $.sessionHost.updateSession(Z,{metadata:Q}),[j,X]=await Promise.all([b0($,Z),u0($,Z)]);if(j)$.publish($.buildEvent("session.updated",{session:j,...X?{snapshot:X}:{}},Z));return{version:W.version,requestId:W.requestId,ok:J.updated,payload:{updated:J.updated,session:j,...X?{snapshot:X}:{}}}}async function Uf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_update_connection","session.update_connection requires a session id");let Q=$.sessionHost.updateSessionConnection;if(!Q)return h(W,"unsupported_session_update_connection","runtime host does not support session connection updates");let J=s6(W.payload),j=Yv(J?.updates);return await Q.call($.sessionHost,Z,j),u(W,{sessionId:Z,updated:!0})}async function Df($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.update requires a session id");let Q=W.clientId?.trim()||"hub-client",J=await b0($,Z);if(!J)return h(W,"session_not_found",`Unknown session: ${Z}`);let j=jf({sessionId:Z,ctx:$,clientId:Q,envelope:W});if(j)return j;let X=W.payload&&typeof W.payload==="object"?W.payload:{},Y=G1(X.state);if(!Y)return h(W,"invalid_compaction_state","session.compaction.update requires a valid compaction state");let V=await $.sessionHost.updateSessionCompactionState(Z,Y),[B,H]=V.updated?await Promise.all([b0($,Z),u0($,Z)]):[J,void 0];if(V.updated)$.publish($.buildEvent("session.updated",{session:B??J,...H?{snapshot:H}:{}},Z));return{version:W.version,requestId:W.requestId,ok:!0,payload:{updated:V.updated,session:B??J,...H?{snapshot:H}:{}}}}async function _f($,W){let Z=S0(W),Q=await $.sessionHost.deleteSession(Z);return $.sessionState.delete(Z),u(W,{deleted:Q})}async function ff($,W){let Z=S0(W),Q=$.sessionHost.pendingPrompts;if(!Q)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let J=await Q.list({sessionId:Z});return u(W,{sessionId:Z,prompts:J})}async function Lf($,W){let Z=S0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=typeof W.payload?.prompt==="string"?W.payload.prompt:void 0,j=W.payload?.delivery==="queue"||W.payload?.delivery==="steer"?W.payload.delivery:void 0,X=$.sessionHost.pendingPrompts;if(!X)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let Y=await X.update({sessionId:Z,promptId:Q,prompt:J,delivery:j});return u(W,Y)}async function Tf($,W){let Z=S0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=$.sessionHost.pendingPrompts;if(!J)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await J.delete({sessionId:Z,promptId:Q});return u(W,j)}function Of($){switch($){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var Gv=new Set(["skills","workflows","rules","tools","mcp"]);function vY($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function u9($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="string")throw Error(`settings payload '${W}' must be a string.`);return Z}function Kv($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="boolean")throw Error(`settings payload '${W}' must be a boolean.`);return Z}function zf($){if($===void 0)return{};if(!vY($))throw Error("settings.list payload must be an object.");return{cwd:u9($,"cwd"),workspaceRoot:u9($,"workspaceRoot"),availabilityContext:vY($.availabilityContext)?$.availabilityContext:void 0}}function Fv($){if(!vY($))throw Error("settings.toggle payload must be an object.");let{type:W}=$;if(typeof W!=="string"||!Gv.has(W))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...zf($),type:W,id:u9($,"id"),path:u9($,"path"),name:u9($,"name"),enabled:Kv($,"enabled")}}class o6{options;clients=new Map;listeners=new Map;sessionState=new Map;pendingApprovals=new Map;pendingCapabilityRequests=new Map;suppressNextTerminalEventBySession=new Map;schedules;scheduleCommands;settings;cronService;sessionHost;hubId=Hv("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new b1({sessionService:new S1(new C1),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(W)=>this.publish(W),buildEvent:H8,requestCapability:(W,Z,Q,J,j)=>k_(this.ctx,W,Z,Q,J,j)},this.schedules=new f8({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(W,Z)=>{let Q=W==="schedule.execution.completed"?"schedule.execution_completed":W==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(H8(Q,Z&&typeof Z==="object"?Z:void 0))}}),this.scheduleCommands=new A8(this.schedules),this.settings=$.settingsService??new l$,$.cronOptions)this.cronService=new W9({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((W)=>{e_(this.ctx,W).catch((Z)=>{bY("session event handling failed",Z),E7(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Z,severity:"error",handled:!0,context:{eventType:W.type,sessionId:W.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())PY(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(t$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let W=await this.dispatchCommand($);return this.captureFailedReply($,W),W}catch(W){throw E7(this.options.telemetry,{component:"core",operation:"hub.command",error:W,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),W}}async dispatchCommand($){switch($.command){case"client.register":return m_(this.ctx,$);case"client.update":return v_(this.ctx,$);case"client.unregister":return c_(this.ctx,$,(W)=>{this.listeners.delete(W),this.detachClientFromSessions(W)});case"client.list":return u_(this.ctx,$);case"session.create":return await Xf(this.ctx,$,(W)=>CY(this.ctx,W));case"session.restore":return await Yf(this.ctx,$,(W)=>CY(this.ctx,W));case"session.attach":return await Vf(this.ctx,$);case"session.detach":return await Bf(this.ctx,$);case"session.get":return await Hf(this.ctx,$);case"session.messages":return await Gf(this.ctx,$);case"session.compaction.get":return await Kf(this.ctx,$);case"session.list":return await Ff(this.ctx,$);case"session.update":return await Af(this.ctx,$);case"session.update_connection":return await Uf(this.ctx,$);case"session.compaction.update":return await Df(this.ctx,$);case"session.pending_prompts":return await ff(this.ctx,$);case"session.update_pending_prompt":return await Lf(this.ctx,$);case"session.remove_pending_prompt":return await Tf(this.ctx,$);case"session.delete":return await _f(this.ctx,$);case"session.hook":return await t_(this.ctx,$);case"run.start":case"session.send_input":return await o_(this.ctx,$);case"run.abort":return await s_(this.ctx,$);case"capability.request":return await x_(this.ctx,$);case"approval.respond":return await y_(this.ctx,$);case"capability.respond":return g_(this.ctx,$);case"capability.progress":return I_(this.ctx,$);case"ui.notify":return this.publish(H8("ui.notify",$.payload??{})),u($);case"ui.show_window":return this.publish(H8("ui.show_window",$.payload??{})),u($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"connector.channels":case"connector.configure":case"connector.delete_config":return await a_(this.ctx,$);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let W=await this.scheduleCommands.handleCommand($);if(W.ok){let Z=Of($.command);if(Z)this.publish(H8(Z,W.payload))}return W}}}captureFailedReply($,W){if(W.ok||!W.error||!Av(W.error.code))return;E7(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(W.error.message),severity:W.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:W.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let W=await this.settings.list(zf($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:W instanceof Error?W.message:String(W)}}}}async handleSettingsToggle($){try{let W=await this.settings.toggle(Fv($.payload));return this.publish(H8("settings.changed",{types:W.changedTypes,snapshot:W.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W.snapshot,changedTypes:W.changedTypes}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:W instanceof Error?W.message:String(W)}}}}subscribe($,W,Z){let Q=this.listeners.get($)??new Set,J={sessionId:Z?.sessionId,listener:W};return Q.add(J),this.listeners.set($,Q),()=>{let j=this.listeners.get($);if(!j)return;if(j.delete(J),j.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[W,Z]of this.sessionState.entries()){if(Z.participants.delete($),Z.createdByClientId===$)Z.createdByClientId=void 0;if(Z.participants.size===0)this.sessionState.delete(W)}t$(this.ctx,(W)=>W.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let W of this.listeners.values())for(let Z of W){if(Z.sessionId&&Z.sessionId!==$.sessionId)continue;try{Z.listener($)}catch(Q){bY(`listener threw while publishing ${$.event}`,Q),E7(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function Av($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as fv}from"node:crypto";import Lv from"node:http";import Tv from"node:net";import{URL as lY}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as Rf,HUB_CAPABILITIES as Ov,isHubProtocolCompatible as zv,MAX_CLIENT_HUB_PROTOCOL_VERSION as Ef,MIN_CLIENT_HUB_PROTOCOL_VERSION as Nf}from"@cline/shared";import{WebSocketServer as qv}from"ws";import{captureSdkError as qf,HUB_COMMAND_SLOW_LOG_MS as Uv,resolveHubCommandTimeoutMs as Dv,safeJsonParse as _v}from"@cline/shared";function cY($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function Mf($,W,Z){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:W,message:Z}}}class I9{transport;telemetry;constructor($,W){this.transport=$;this.telemetry=W}attach($){let W=new Map,Z=new Set,Q=!1,J=(V)=>{try{$.send(JSON.stringify(V))}catch(B){console.error(`[hub] failed to send websocket frame: ${B instanceof Error?B.stack||B.message:String(B)}`)}},j=(V)=>{J({kind:"event",envelope:V})},X=async(V)=>{try{let B=JSON.parse(V.data);switch(B.kind){case"command":{let H=performance.now(),G=!1,K=cY(B);i("info","command.start",K);let F=setTimeout(()=>{if(G)return;i("warn","command.slow",{...K,elapsedMs:Math.round(performance.now()-H)})},Uv),A=this.transport.command(B.envelope);A.then((O)=>{if(!G)return;i(O.ok?"warn":"error","command.late_end",{...K,elapsedMs:Math.round(performance.now()-H),ok:O.ok,errorCode:O.error?.code,errorMessage:O.error?.message})},(O)=>{if(!G)return;i("error","command.late_error",{...K,elapsedMs:Math.round(performance.now()-H),error:O})});let D=!1,U,f,_=Dv(B.envelope.command,B.envelope.timeoutMs);try{f=_===null?await A:await Promise.race([A,new Promise((O)=>{U=setTimeout(()=>{D=!0,qf(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${B.envelope.command} did not complete within ${_}ms.`),severity:"error",handled:!0,context:{...K,timeoutMs:_}}),O(Mf(B,"hub_command_timeout",`Hub command ${B.envelope.command} did not complete within ${_}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${B.envelope.requestId}.`))},_)})])}catch(O){if(clearTimeout(F),U)clearTimeout(U);throw O}if(G=D,clearTimeout(F),U)clearTimeout(U);let R=Math.round(performance.now()-H);if(D)i("error","command.timeout",{...K,durationMs:R,timeoutMs:_});else i(f.ok?"info":"warn","command.end",{...K,durationMs:R,ok:f.ok,errorCode:f.error?.code,errorMessage:f.error?.message});if(B.envelope.command==="client.register"&&f.ok){let T=(B.envelope.payload??{}).clientId?.trim()||B.envelope.clientId?.trim();if(T)Z.add(T)}else if(B.envelope.command==="client.unregister"&&f.ok){let O=B.envelope.clientId?.trim();if(O)Z.delete(O)}J({kind:"reply",envelope:f});break}case"stream.subscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;if(W.has(H))break;let G=await this.transport.subscribe(B.clientId,j,{sessionId:B.sessionId});W.set(H,G);break}case"stream.unsubscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;W.get(H)?.(),W.delete(H);break}case"reply":case"event":break}}catch(B){let H=typeof V.data==="string"?_v(V.data):void 0;if(!H||H.kind!=="command"){i("error","rejected malformed websocket frame",{error:B});return}i("error","command.error",{...cY(H),error:B}),qf(this.telemetry,{component:"core",operation:"hub.websocket_command",error:B,severity:"error",handled:!0,context:cY(H)}),J({kind:"reply",envelope:Mf(H,"command_failed",B instanceof Error?B.message:"Unknown hub error")})}},Y=()=>{if(Q)return;Q=!0;for(let V of W.values())V();W.clear();for(let V of Z)this.transport.command({version:"v1",command:"client.unregister",clientId:V});Z.clear(),$.removeEventListener("message",X),$.removeEventListener("close",Y)};return $.addEventListener("message",X),$.addEventListener("close",Y),Y}}class x9{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,W,Z){return this.transport.subscribe($,W,Z)}}function Mv($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((W)=>Buffer.from(W))).toString();return String($)}function Rv($){return{send(W){$.send(W)},addEventListener(W,Z){if(W==="message"){$.on("message",(Q)=>{Z({data:Mv(Q)})});return}$.on("close",Z)},removeEventListener(){}}}function Ev($){try{$.write(`HTTP/1.1 400 Bad Request\r
751
+ ${H}`:V.instructions}})}})}}function Jv($,W,Z,Q){let J=Z.map((j)=>[j.executor,async(...X)=>{let Y=X.at(-1),V=X.slice(0,-1);return(await Q($,j.capabilityName,{executor:j.executor,args:V,context:Zf(Y)},W))?.result}]);return J.length>0?Object.fromEntries(J):void 0}function jv($,W,Z,Q){if(Z.length===0)return;return Z.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,lifecycle:J.lifecycle,async execute(j,X){return(await Q($,J.capabilityName,{toolName:J.name,input:j,context:Zf(X)},W,X.emitUpdate?(V)=>{X.emitUpdate?.($v(V))}:void 0))?.result}}))}function Xv($,W,Z,Q){let J=new Map(Z.map((X)=>[X.name,X])),j={};for(let X of tm){let Y=J.get(X);if(!Y)continue;j[X]=async(V)=>{return(await Q($,Y.capabilityName,{context:V},W))?.control}}return Object.keys(j).length>0?j:void 0}function vY($){let W=$.contributions.filter((V)=>V.kind==="toolExecutor"),Z=$.contributions.filter((V)=>V.kind==="tool"),Q=$.contributions.filter((V)=>V.kind==="hook"),J=$.contributions.find((V)=>V.kind==="compaction"),j=$.contributions.find((V)=>V.kind==="checkpoint"),X=$.contributions.find((V)=>V.kind==="mistakeLimit"),Y=$.contributions.find((V)=>V.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:Jv($.sessionId,$.targetClientId,W,$.requestCapability),localRuntime:{...Q.length>0?{hooks:Xv($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...Z.length>0?{extraTools:jv($.sessionId,$.targetClientId,Z,$.requestCapability)}:{},...J?{compaction:{...$.sessionConfig?.compaction??{},...J.config,compact:async(V)=>{return(await $.requestCapability($.sessionId,J.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...j?{checkpoint:{...$.sessionConfig?.checkpoint??{},...j.config,createCheckpoint:async(V)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...X?{onConsecutiveMistakeLimitReached:async(V)=>{return(await $.requestCapability($.sessionId,X.capabilityName,{context:V},$.targetClientId))?.result}}:{},...Y?{userInstructionService:Qv($.sessionId,$.targetClientId,Y,$.requestCapability)}:{}}}}var Qf="hubCapabilityOwnerClientId";function E7($){return typeof $==="string"&&$.trim().length>0?$.trim():void 0}function Yv($){if($==="low"||$==="medium"||$==="high"||$==="xhigh"||$===null)return $;return}function Vv($){let W=s6($)??{},Z={},Q=E7(W.providerId);if(Q)Z.providerId=Q;let J=E7(W.modelId);if(J)Z.modelId=J;let j=E7(W.apiKey);if(j!==void 0)Z.apiKey=j;let X=E7(W.baseUrl);if(X!==void 0)Z.baseUrl=X;if(W.headers&&typeof W.headers==="object")Z.headers=W.headers;if(W.providerConfig&&typeof W.providerConfig==="object")Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"thinking")){if(typeof W.thinking==="boolean"||W.thinking===null)Z.thinking=W.thinking}if(Object.hasOwn(W,"reasoningEffort")){let Y=Yv(W.reasoningEffort);if(Y!==void 0)Z.reasoningEffort=Y}if(Object.hasOwn(W,"thinkingBudgetTokens")){if(typeof W.thinkingBudgetTokens==="number"&&Number.isFinite(W.thinkingBudgetTokens)&&W.thinkingBudgetTokens>0)Z.thinkingBudgetTokens=Math.trunc(W.thinkingBudgetTokens);else if(W.thinkingBudgetTokens===null)Z.thinkingBudgetTokens=null}return w2(Z)}function Bv($,W){return $.sessionState.get(W)?.createdByClientId}function Hv($){if(!$||!(Qf in $))return $;let W={...$};return delete W[Qf],W}function Xf($){let W=Bv($.ctx,$.sessionId);if(!W)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} has no owner`);if(W!==$.clientId)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} is owned by ${W}`);return}async function Yf($,W,Z){let Q=performance.now(),J={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:W.sessionId};i("info","session.create.begin",J);let j=W.payload&&typeof W.payload==="object"?W.payload:{},X=j.metadata&&typeof j.metadata==="object"?JSON.parse(JSON.stringify(j.metadata)):{},Y=j.sessionConfig&&typeof j.sessionConfig==="object"?JSON.parse(JSON.stringify(j.sessionConfig)):void 0,V=j.runtimeOptions&&typeof j.runtimeOptions==="object"?j.runtimeOptions:{},B=G1(j.initialCompactionState);if(typeof Y?.mode==="string")X.mode=Y.mode;else if(typeof V.mode==="string")X.mode=V.mode;if(typeof Y?.systemPrompt==="string")X.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")X.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)X.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)X.checkpointEnabled=!0;let H=j.modelSelection&&typeof j.modelSelection==="object"?j.modelSelection:{},G=typeof j.workspaceRoot==="string"&&j.workspaceRoot.trim()?j.workspaceRoot.trim():typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():"";if(!G)return i("warn","session.create.invalid",{...J,reason:"missing_workspace_root"}),h(W,"invalid_session_create","session.create requires workspaceRoot or cwd");let K=W.clientId?.trim()||"hub-client",F=mY(V.clientContributions);i("info","session.create.contributions_parsed",{...J,clientId:K,workspaceRoot:G,cwd:typeof j.cwd==="string"?j.cwd:void 0,contributionCount:F.length});let D=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||Jf(),U=jf(V.configExtensions);i("info","session.create.runtime_build.begin",{...J,sessionId:D,configExtensionCount:U?.length??0});let f=vY({sessionId:D,targetClientId:K,contributions:F,sessionConfig:Y,requestCapability:$.requestCapability});i("info","session.create.start_session.begin",{...J,sessionId:D,provider:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),model:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub")});let _=await $.sessionHost.startSession({source:typeof X.source==="string"?X.source:void 0,interactive:X.interactive!==!1,sessionMetadata:Object.keys(X).length>0?X:void 0,initialMessages:Array.isArray(j.initialMessages)?j.initialMessages:void 0,initialCompactionState:B,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:U,...f.localRuntime},capabilities:{toolExecutors:f.toolExecutors,requestToolApproval:Z},config:{...Y??{},sessionId:D,providerId:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),modelId:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub"),apiKey:Y?.apiKey??(typeof H.apiKey==="string"?H.apiKey:void 0),cwd:Y?.cwd??(typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():G),workspaceRoot:Y?.workspaceRoot??G,systemPrompt:Y?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:Y?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:Y?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:Y?.enableTools??V.enableTools!==!1,enableSpawnAgent:Y?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:Y?.enableAgentTeams??V.enableTeams!==!1,checkpoint:Y?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:Y?.teamName??(typeof X.teamName==="string"?X.teamName:void 0)},toolPolicies:j.toolPolicies&&typeof j.toolPolicies==="object"&&!Array.isArray(j.toolPolicies)?JSON.parse(JSON.stringify(j.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});i("info","session.create.start_session.end",{...J,sessionId:_.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!_.result}),CY($,_.sessionId,K,"creator",{interactive:X.interactive!==!1}),i("info","session.create.read_records.begin",{...J,sessionId:_.sessionId});let[R,O]=await Promise.all([b0($,_.sessionId),u0($,_.sessionId)]);if(i("info","session.create.read_records.end",{...J,sessionId:_.sessionId,hasSession:!!R,hasSnapshot:!!O,elapsedMs:Math.round(performance.now()-Q)}),R)$.publish($.buildEvent("session.created",{session:R,...O?{snapshot:O}:{}},_.sessionId));return i("info","session.create.reply",{...J,sessionId:_.sessionId,elapsedMs:Math.round(performance.now()-Q)}),u(W,{session:R,...O?{snapshot:O}:{}})}async function Vf($,W,Z){let Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.sessionId==="string"?Q.sessionId.trim():W.sessionId?.trim()||"",j=Q.checkpointRunCount;if(!J)return h(W,"invalid_restore","session.restore requires a session id");let X=Q.restore&&typeof Q.restore==="object"?Q.restore:{},Y=X.messages!==!1;if(typeof j!=="number")return h(W,"invalid_restore","checkpointRunCount must be a positive integer");try{let V=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(Y&&!V)return h(W,"invalid_restore","sessionConfig is required when restore.messages is true");let B=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},H=G1(Q.initialCompactionState),G=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof V?.mode==="string")G.mode=V.mode;else if(typeof B.mode==="string")G.mode=B.mode;if(typeof V?.systemPrompt==="string")G.systemPrompt=V.systemPrompt;else if(typeof B.systemPrompt==="string")G.systemPrompt=B.systemPrompt;if(V?.checkpoint?.enabled===!0)G.checkpointEnabled=!0;else if(B.checkpointEnabled===!0)G.checkpointEnabled=!0;let K=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},F=W.clientId?.trim()||"hub-client",A=mY(B.clientContributions),U=(typeof V?.sessionId==="string"?V.sessionId.trim():"")||Jf(),f=jf(B.configExtensions),_=vY({sessionId:U,targetClientId:F,contributions:A,sessionConfig:V,requestCapability:$.requestCapability}),O=await new o$().restoreCheckpoint({sessionId:J,checkpointRunCount:j,restore:{messages:X.messages,workspace:X.workspace,omitCheckpointMessageFromSession:X.omitCheckpointMessageFromSession===!0},start:V,cwd:typeof V?.cwd==="string"&&V.cwd.trim()||typeof V?.workspaceRoot==="string"&&V.workspaceRoot.trim()||void 0,getSession:(E)=>$.sessionHost.getSession(E),readMessages:(E)=>$.sessionHost.readSessionMessages(E),buildStartInput:(E)=>{if(E.restoredCheckpointMetadata)G.checkpoint=E.restoredCheckpointMetadata;let p=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():E.sourceSession.workspaceRoot||E.sourceSession.cwd;return{source:typeof G.source==="string"?G.source:void 0,interactive:G.interactive!==!1,sessionMetadata:{...G,restoredFromSessionId:J,restoredCheckpointRunCount:j},initialMessages:E.initialMessages,initialCompactionState:H,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:f,..._.localRuntime},capabilities:{toolExecutors:_.toolExecutors,requestToolApproval:Z},config:{...V??{},sessionId:U,providerId:V?.providerId??(typeof K.provider==="string"?K.provider:E.sourceSession.provider),modelId:V?.modelId??(typeof K.model==="string"?K.model:E.sourceSession.model),apiKey:V?.apiKey??(typeof K.apiKey==="string"?K.apiKey:""),cwd:V?.cwd??E.plan.cwd,workspaceRoot:V?.workspaceRoot??p,systemPrompt:V?.systemPrompt??(typeof B.systemPrompt==="string"?B.systemPrompt:""),mode:V?.mode??(B.mode==="plan"||B.mode==="yolo"?B.mode:"act"),maxIterations:V?.maxIterations??(typeof B.maxIterations==="number"?B.maxIterations:void 0),enableTools:V?.enableTools??B.enableTools!==!1,enableSpawnAgent:V?.enableSpawnAgent??B.enableSpawn!==!1,enableAgentTeams:V?.enableAgentTeams??B.enableTeams!==!1,checkpoint:V?.checkpoint??(B.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:V?.teamName??(typeof G.teamName==="string"?G.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):B.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(E)=>$.sessionHost.startSession(E),getStartedSessionId:(E)=>E.sessionId,readRestoredSession:(E)=>$.sessionHost.getSession(E)});if(!Y)return u(W,{checkpoint:O.checkpoint});let T=O.startResult;if(!T)return h(W,"restore_failed","Checkpoint restore did not start a session");CY($,T.sessionId,F,"creator",{interactive:G.interactive!==!1});let[L,C]=await Promise.all([b0($,T.sessionId),u0($,T.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...C?{snapshot:C}:{}},T.sessionId));return u(W,{session:L,...C?{snapshot:C}:{},messages:O.messages??[],checkpoint:O.checkpoint})}catch(V){if(V instanceof c0)return h(W,V.code,V.code==="session_not_found"?`Unknown session: ${J}`:V.message);return h(W,"restore_failed",V instanceof Error?V.message:String(V))}}async function Bf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_attach","session.attach requires a session id");let Q=await b0($,Z);if(!Q)return h(W,"session_not_found",`Unknown session: ${Z}`);y_($,Z,W.clientId?.trim()||"hub-client","participant");let J=await b0($,Z);return $.publish($.buildEvent("session.attached",{session:J??Q},Z)),u(W,{session:J??Q})}async function Hf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_detach","session.detach requires a session id");let Q=W.clientId?.trim()||"hub-client",J=$.sessionState.get(Z);if(J){if(J.participants.delete(Q),J.createdByClientId===Q)J.createdByClientId=void 0;if(J.participants.size===0)$.sessionState.delete(Z)}t$($,(Y)=>Y.sessionId===Z&&Y.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[j,X]=await Promise.all([b0($,Z),u0($,Z)]);return $.publish($.buildEvent("session.detached",j?{session:j,...X?{snapshot:X}:{},clientId:Q}:{clientId:Q},Z)),u(W)}async function Gf($,W){let Z=S0(W),Q=W.payload?.includeSnapshot===!0,[J,j]=await Promise.all([b0($,Z),Q?u0($,Z):Promise.resolve(void 0)]);return J?u(W,{session:J,...j?{snapshot:j}:{}}):h(W,"session_not_found",`Unknown session: ${Z}`)}async function Kf($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.messages requires a session id");if(!await b0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=await $.sessionHost.readSessionMessages(Z);return u(W,{sessionId:Z,messages:J})}async function Ff($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.get requires a session id");if(!await b0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=W.clientId?.trim()||"hub-client",j=Xf({sessionId:Z,ctx:$,clientId:J,envelope:W});if(j)return j;let X=await $.sessionHost.readSessionCompactionState(Z);return u(W,{sessionId:Z,state:X})}async function Af($,W){let Z=typeof W.payload?.limit==="number"?W.payload.limit:200,J=(await $.sessionHost.listSessions(Z)).map((j)=>M7(j,$.sessionState.get(j.sessionId)));return u(W,{sessions:J})}async function Uf($,W){let Z=S0(W),Q=Hv(s6(W.payload?.metadata)),J=await $.sessionHost.updateSession(Z,{metadata:Q}),[j,X]=await Promise.all([b0($,Z),u0($,Z)]);if(j)$.publish($.buildEvent("session.updated",{session:j,...X?{snapshot:X}:{}},Z));return{version:W.version,requestId:W.requestId,ok:J.updated,payload:{updated:J.updated,session:j,...X?{snapshot:X}:{}}}}async function Df($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_update_connection","session.update_connection requires a session id");let Q=$.sessionHost.updateSessionConnection;if(!Q)return h(W,"unsupported_session_update_connection","runtime host does not support session connection updates");let J=s6(W.payload),j=Vv(J?.updates);return await Q.call($.sessionHost,Z,j),u(W,{sessionId:Z,updated:!0})}async function _f($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.update requires a session id");let Q=W.clientId?.trim()||"hub-client",J=await b0($,Z);if(!J)return h(W,"session_not_found",`Unknown session: ${Z}`);let j=Xf({sessionId:Z,ctx:$,clientId:Q,envelope:W});if(j)return j;let X=W.payload&&typeof W.payload==="object"?W.payload:{},Y=G1(X.state);if(!Y)return h(W,"invalid_compaction_state","session.compaction.update requires a valid compaction state");let V=await $.sessionHost.updateSessionCompactionState(Z,Y),[B,H]=V.updated?await Promise.all([b0($,Z),u0($,Z)]):[J,void 0];if(V.updated)$.publish($.buildEvent("session.updated",{session:B??J,...H?{snapshot:H}:{}},Z));return{version:W.version,requestId:W.requestId,ok:!0,payload:{updated:V.updated,session:B??J,...H?{snapshot:H}:{}}}}async function ff($,W){let Z=S0(W),Q=await $.sessionHost.deleteSession(Z);return $.sessionState.delete(Z),u(W,{deleted:Q})}async function Lf($,W){let Z=S0(W),Q=$.sessionHost.pendingPrompts;if(!Q)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let J=await Q.list({sessionId:Z});return u(W,{sessionId:Z,prompts:J})}async function Tf($,W){let Z=S0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=typeof W.payload?.prompt==="string"?W.payload.prompt:void 0,j=W.payload?.delivery==="queue"||W.payload?.delivery==="steer"?W.payload.delivery:void 0,X=$.sessionHost.pendingPrompts;if(!X)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let Y=await X.update({sessionId:Z,promptId:Q,prompt:J,delivery:j});return u(W,Y)}async function Of($,W){let Z=S0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=$.sessionHost.pendingPrompts;if(!J)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await J.delete({sessionId:Z,promptId:Q});return u(W,j)}function zf($){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 Kv=new Set(["skills","workflows","rules","tools","mcp"]);function cY($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function u9($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="string")throw Error(`settings payload '${W}' must be a string.`);return Z}function Fv($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="boolean")throw Error(`settings payload '${W}' must be a boolean.`);return Z}function qf($){if($===void 0)return{};if(!cY($))throw Error("settings.list payload must be an object.");return{cwd:u9($,"cwd"),workspaceRoot:u9($,"workspaceRoot"),availabilityContext:cY($.availabilityContext)?$.availabilityContext:void 0}}function Av($){if(!cY($))throw Error("settings.toggle payload must be an object.");let{type:W}=$;if(typeof W!=="string"||!Kv.has(W))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...qf($),type:W,id:u9($,"id"),path:u9($,"path"),name:u9($,"name"),enabled:Fv($,"enabled")}}class o6{options;clients=new Map;listeners=new Map;sessionState=new Map;pendingApprovals=new Map;pendingCapabilityRequests=new Map;suppressNextTerminalEventBySession=new Map;schedules;scheduleCommands;settings;cronService;sessionHost;hubId=Gv("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new b1({sessionService:new S1(new C1),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(W)=>this.publish(W),buildEvent:H8,requestCapability:(W,Z,Q,J,j)=>I_(this.ctx,W,Z,Q,J,j)},this.schedules=new f8({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(W,Z)=>{let Q=W==="schedule.execution.completed"?"schedule.execution_completed":W==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(H8(Q,Z&&typeof Z==="object"?Z:void 0))}}),this.scheduleCommands=new A8(this.schedules),this.settings=$.settingsService??new l$,$.cronOptions)this.cronService=new W9({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((W)=>{$f(this.ctx,W).catch((Z)=>{yY("session event handling failed",Z),N7(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Z,severity:"error",handled:!0,context:{eventType:W.type,sessionId:W.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())SY(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(t$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let W=await this.dispatchCommand($);return this.captureFailedReply($,W),W}catch(W){throw N7(this.options.telemetry,{component:"core",operation:"hub.command",error:W,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),W}}async dispatchCommand($){switch($.command){case"client.register":return v_(this.ctx,$);case"client.update":return c_(this.ctx,$);case"client.unregister":return u_(this.ctx,$,(W)=>{this.listeners.delete(W),this.detachClientFromSessions(W)});case"client.list":return d_(this.ctx,$);case"session.create":return await Yf(this.ctx,$,(W)=>PY(this.ctx,W));case"session.restore":return await Vf(this.ctx,$,(W)=>PY(this.ctx,W));case"session.attach":return await Bf(this.ctx,$);case"session.detach":return await Hf(this.ctx,$);case"session.get":return await Gf(this.ctx,$);case"session.messages":return await Kf(this.ctx,$);case"session.compaction.get":return await Ff(this.ctx,$);case"session.list":return await Af(this.ctx,$);case"session.update":return await Uf(this.ctx,$);case"session.update_connection":return await Df(this.ctx,$);case"session.compaction.update":return await _f(this.ctx,$);case"session.pending_prompts":return await Lf(this.ctx,$);case"session.update_pending_prompt":return await Tf(this.ctx,$);case"session.remove_pending_prompt":return await Of(this.ctx,$);case"session.delete":return await ff(this.ctx,$);case"session.hook":return await e_(this.ctx,$);case"run.start":case"session.send_input":return await s_(this.ctx,$);case"run.abort":return await t_(this.ctx,$);case"capability.request":return await g_(this.ctx,$);case"approval.respond":return await h_(this.ctx,$);case"capability.respond":return m_(this.ctx,$);case"capability.progress":return x_(this.ctx,$);case"ui.notify":return this.publish(H8("ui.notify",$.payload??{})),u($);case"ui.show_window":return this.publish(H8("ui.show_window",$.payload??{})),u($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"connector.channels":case"connector.configure":case"connector.delete_config":return await o_(this.ctx,$);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let W=await this.scheduleCommands.handleCommand($);if(W.ok){let Z=zf($.command);if(Z)this.publish(H8(Z,W.payload))}return W}}}captureFailedReply($,W){if(W.ok||!W.error||!Uv(W.error.code))return;N7(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(W.error.message),severity:W.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:W.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let W=await this.settings.list(qf($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:W instanceof Error?W.message:String(W)}}}}async handleSettingsToggle($){try{let W=await this.settings.toggle(Av($.payload));return this.publish(H8("settings.changed",{types:W.changedTypes,snapshot:W.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W.snapshot,changedTypes:W.changedTypes}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:W instanceof Error?W.message:String(W)}}}}subscribe($,W,Z){let Q=this.listeners.get($)??new Set,J={sessionId:Z?.sessionId,listener:W};return Q.add(J),this.listeners.set($,Q),()=>{let j=this.listeners.get($);if(!j)return;if(j.delete(J),j.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[W,Z]of this.sessionState.entries()){if(Z.participants.delete($),Z.createdByClientId===$)Z.createdByClientId=void 0;if(Z.participants.size===0)this.sessionState.delete(W)}t$(this.ctx,(W)=>W.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let W of this.listeners.values())for(let Z of W){if(Z.sessionId&&Z.sessionId!==$.sessionId)continue;try{Z.listener($)}catch(Q){yY(`listener threw while publishing ${$.event}`,Q),N7(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function Uv($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as Lv}from"node:crypto";import Tv from"node:http";import Ov from"node:net";import{URL as pY}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as Ef,HUB_CAPABILITIES as zv,isHubProtocolCompatible as qv,MAX_CLIENT_HUB_PROTOCOL_VERSION as Nf,MIN_CLIENT_HUB_PROTOCOL_VERSION as wf}from"@cline/shared";import{WebSocketServer as Mv}from"ws";import{captureSdkError as Mf,HUB_COMMAND_SLOW_LOG_MS as Dv,resolveHubCommandTimeoutMs as _v,safeJsonParse as fv}from"@cline/shared";function uY($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function Rf($,W,Z){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:W,message:Z}}}class I9{transport;telemetry;constructor($,W){this.transport=$;this.telemetry=W}attach($){let W=new Map,Z=new Set,Q=!1,J=(V)=>{try{$.send(JSON.stringify(V))}catch(B){console.error(`[hub] failed to send websocket frame: ${B instanceof Error?B.stack||B.message:String(B)}`)}},j=(V)=>{J({kind:"event",envelope:V})},X=async(V)=>{try{let B=JSON.parse(V.data);switch(B.kind){case"command":{let H=performance.now(),G=!1,K=uY(B);i("info","command.start",K);let F=setTimeout(()=>{if(G)return;i("warn","command.slow",{...K,elapsedMs:Math.round(performance.now()-H)})},Dv),A=this.transport.command(B.envelope);A.then((O)=>{if(!G)return;i(O.ok?"warn":"error","command.late_end",{...K,elapsedMs:Math.round(performance.now()-H),ok:O.ok,errorCode:O.error?.code,errorMessage:O.error?.message})},(O)=>{if(!G)return;i("error","command.late_error",{...K,elapsedMs:Math.round(performance.now()-H),error:O})});let D=!1,U,f,_=_v(B.envelope.command,B.envelope.timeoutMs);try{f=_===null?await A:await Promise.race([A,new Promise((O)=>{U=setTimeout(()=>{D=!0,Mf(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${B.envelope.command} did not complete within ${_}ms.`),severity:"error",handled:!0,context:{...K,timeoutMs:_}}),O(Rf(B,"hub_command_timeout",`Hub command ${B.envelope.command} did not complete within ${_}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${B.envelope.requestId}.`))},_)})])}catch(O){if(clearTimeout(F),U)clearTimeout(U);throw O}if(G=D,clearTimeout(F),U)clearTimeout(U);let R=Math.round(performance.now()-H);if(D)i("error","command.timeout",{...K,durationMs:R,timeoutMs:_});else i(f.ok?"info":"warn","command.end",{...K,durationMs:R,ok:f.ok,errorCode:f.error?.code,errorMessage:f.error?.message});if(B.envelope.command==="client.register"&&f.ok){let T=(B.envelope.payload??{}).clientId?.trim()||B.envelope.clientId?.trim();if(T)Z.add(T)}else if(B.envelope.command==="client.unregister"&&f.ok){let O=B.envelope.clientId?.trim();if(O)Z.delete(O)}J({kind:"reply",envelope:f});break}case"stream.subscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;if(W.has(H))break;let G=await this.transport.subscribe(B.clientId,j,{sessionId:B.sessionId});W.set(H,G);break}case"stream.unsubscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;W.get(H)?.(),W.delete(H);break}case"reply":case"event":break}}catch(B){let H=typeof V.data==="string"?fv(V.data):void 0;if(!H||H.kind!=="command"){i("error","rejected malformed websocket frame",{error:B});return}i("error","command.error",{...uY(H),error:B}),Mf(this.telemetry,{component:"core",operation:"hub.websocket_command",error:B,severity:"error",handled:!0,context:uY(H)}),J({kind:"reply",envelope:Rf(H,"command_failed",B instanceof Error?B.message:"Unknown hub error")})}},Y=()=>{if(Q)return;Q=!0;for(let V of W.values())V();W.clear();for(let V of Z)this.transport.command({version:"v1",command:"client.unregister",clientId:V});Z.clear(),$.removeEventListener("message",X),$.removeEventListener("close",Y)};return $.addEventListener("message",X),$.addEventListener("close",Y),Y}}class x9{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,W,Z){return this.transport.subscribe($,W,Z)}}function Rv($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((W)=>Buffer.from(W))).toString();return String($)}function Ev($){return{send(W){$.send(W)},addEventListener(W,Z){if(W==="message"){$.on("message",(Q)=>{Z({data:Rv(Q)})});return}$.on("close",Z)},removeEventListener(){}}}function Nv($){try{$.write(`HTTP/1.1 400 Bad Request\r
752
752
  Connection: close\r
753
753
  Content-Length: 0\r
754
754
  \r
755
- `),$.end()}catch{$.destroy()}}function Nv($){try{$.write(`HTTP/1.1 401 Unauthorized\r
755
+ `),$.end()}catch{$.destroy()}}function wv($){try{$.write(`HTTP/1.1 401 Unauthorized\r
756
756
  Connection: close\r
757
757
  Content-Length: 0\r
758
758
  \r
759
- `),$.end()}catch{$.destroy()}}function uY($,W){if(!$||!W)return!1;let Z=Buffer.from($,"utf8"),Q=Buffer.from(W,"utf8");return Z.length===Q.length&&fv(Z,Q)}function wf($,W){let Z=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Q=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",J=`Failed to start hub server on ${W.host}:${W.port}${W.pathname}: ${Q}`,j=Error(Z?`${J} (${Z})`:J);if(Z)$.code=Z,j.code=Z;if($ instanceof Error&&$.stack)j.stack=`${j.name}: ${j.message}
760
- Caused by: ${$.stack}`;return j}async function wv($){return await new Promise((W,Z)=>{let Q=Tv.createServer();Q.once("error",Z),Q.listen(0,$,()=>{let J=Q.address();if(!J||typeof J==="string"){Q.close(()=>Z(Error("Failed to resolve free port")));return}let j=J.port;Q.close((X)=>{if(X){Z(X);return}W(j)})})})}function Cv($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var dY=new Map,Cf="cline-hub-auth.",Pv=30000;function pY($){return Array.isArray($)?$.join(","):$??""}function Pf($){return $===32||$===9}function f7($){let W=pY($).trim(),Z="bearer";if(W.length<=6||W.slice(0,6).toLowerCase()!=="bearer"||!Pf(W.charCodeAt(6)))return null;let Q=7;while(Q<W.length&&Pf(W.charCodeAt(Q)))Q+=1;return W.slice(Q).trim()||null}function Sv($){for(let W of pY($).split(",")){let Z=W.trim();if(Z.startsWith(Cf))return Z.slice(Cf.length).trim()||null}return null}function L7($){let W=$.trim().toLowerCase();return W==="localhost"||W==="127.0.0.1"||W==="::1"||W==="[::1]"}function AY($){let W=pY($).trim();if(!W)return!1;try{return L7(new lY(W).hostname)}catch{return!1}}async function g9($){let W=$.owner??r1(),Z=$.host??"127.0.0.1",Q=$.pathname??"/hub",J=$.port??E8(),j=J===0?await wv(Z):J,X=j,Y=Y1(Z,j,Q),V=TW(),B=LW(),H=new o6($);await H.start();let G=new I9(new x9(H),$.telemetry),K=new Set,F=new Date().toISOString(),A={protocolVersion:Rf,minClientProtocolVersion:Nf,maxClientProtocolVersion:Ef,capabilities:Ov,coreVersion:_4.version,buildId:V,pid:process.pid,startedAt:F},D=new Set,U,f,_=async()=>{if(f)return f;return f=(async()=>{if(U)clearInterval(U),U=void 0;for(let L of D)L.terminate?.();D.clear();for(let L of K)L();if(K.clear(),await new Promise((L,C)=>{O.close((E)=>{if(E){C(E);return}L()})}),await new Promise((L,C)=>{R.close((E)=>{if(E){C(E);return}L()})}),await H.stop(),(await D0(W.discoveryPath))?.url===Y)await g0(W.discoveryPath)})(),f},R=Lv.createServer((T,L)=>{if((T.url??"/")==="/health"){let E=JSON.stringify({ok:!0,protocolVersion:A.protocolVersion,minClientProtocolVersion:A.minClientProtocolVersion,maxClientProtocolVersion:A.maxClientProtocolVersion,coreVersion:A.coreVersion,host:Z,port:X,url:Y});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(E);return}if((T.url??"/")==="/status"){if(!uY(f7(T.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}let E=JSON.stringify({hubId:H.getHubId(),...A,authToken:B,host:Z,port:X,url:Y,updatedAt:new Date().toISOString()});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(E);return}if((T.url??"/")==="/version"){L.statusCode=200,L.setHeader("content-type","application/json"),L.end(JSON.stringify(A));return}if(new lY(T.url??"/",`http://${Z}:${X}`).pathname==="/shutdown"&&T.method==="POST"){if(!uY(f7(T.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}L.statusCode=202,L.setHeader("content-type","application/json"),L.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{_()});return}L.statusCode=404,L.end("Not found")}),O=new qv({noServer:!0});U=setInterval(()=>{for(let T of D){if(T.isAlive===!1){try{T.terminate?.()}catch{}D.delete(T);continue}T.isAlive=!1;try{T.ping?.()}catch{try{T.terminate?.()}catch{}D.delete(T)}}},Pv),R.on("upgrade",(T,L,C)=>{if(new lY(T.url??"/",`http://${Z}:${X}`).pathname!==Q){L.destroy();return}if(!(uY(Sv(T.headers["sec-websocket-protocol"]),B)||L7(Z)&&AY(T.headers.origin))){Nv(L);return}try{O.handleUpgrade(T,L,C,(x)=>{let P=x;P.isAlive=!0,P.on("pong",()=>{P.isAlive=!0}),D.add(P);let r=G.attach(Rv(x));K.add(r),x.once("close",()=>{D.delete(P),r(),K.delete(r)})})}catch{Ev(L)}});try{await new Promise((T,L)=>{R.once("error",(C)=>{L(wf(C,{host:Z,port:j,pathname:Q}))}),R.listen(j,Z,()=>{let C=R.address();if(!C||typeof C==="string"){L(wf(Error("Failed to resolve hub port"),{host:Z,port:j,pathname:Q}));return}X=C.port,Y=Y1(Z,X,Q),T()})})}catch(T){if(U)clearInterval(U),U=void 0;throw await H.stop().catch(()=>{return}),T}return await OW(W.discoveryPath,{hubId:H.getHubId(),protocolVersion:Rf,minClientProtocolVersion:Nf,maxClientProtocolVersion:Ef,capabilities:[...A.capabilities],coreVersion:_4.version,buildId:V,authToken:B,host:Z,port:X,url:Y,pid:process.pid,startedAt:F,updatedAt:F}),{host:Z,port:X,url:Y,authToken:B,close:_}}async function T7($){let W=$.owner??r1(),Z=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=$.host??"127.0.0.1",J=$.port??E8(),j=$.pathname??"/hub",X=Y1(Q,J,j),Y=W.discoveryPath,V=(H)=>{if(!Z)O$(H.url,H.authToken);return H},B=dY.get(Y);if(B){let H=await B;if(H.url===X)return V({server:H,url:H.url,authToken:H.authToken,action:"reuse"})}return await zW(W.discoveryPath,async()=>{let H=await D0(W.discoveryPath);if(H?.url&&(H.url===X||$.allowPortFallback===!0)){let F=await i1(H.url,{authToken:H.authToken});if(F?.url&&zv(F).compatible&&await z1(F.url,{authToken:H.authToken}))return V({url:F.url,authToken:H.authToken,action:"reuse"})}if(H?.url)await g0(W.discoveryPath);let K=async(F)=>{let A=g9({...F,owner:W});dY.set(Y,A);try{let D=await A;return V({server:D,url:D.url,authToken:D.authToken,action:"started"})}catch(D){throw dY.delete(Y),D}};try{return await K($)}catch(F){if(!$.allowPortFallback||!Cv(F))throw F;return await K({...$,port:0})}})}function bf(){return Sf()==="production"?O1():V1()}function bv($){return Sf()!=="production"&&!$}async function f_($){let W=T1({host:$.host,port:$.port,pathname:$.pathname});return await g9({...$,...W,owner:bf()})}async function L_($){let W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=T1({host:$.host,port:$.port,pathname:$.pathname});return await T7({...$,...Z,allowPortFallback:$.allowPortFallback??bv(W),owner:bf()})}export{OW as writeHubDiscovery,zW as withHubStartupLock,z1 as verifyHubConnection,k9 as truncateNotificationBody,s7 as toHubStatusUrl,qW as toHubHealthUrl,B3 as stopLocalHubServerGracefully,g9 as startHubWebSocketServer,f_ as startHubServer,N8 as spawnDetachedHubServerWithRetry,Q3 as spawnDetachedHubServer,AB as sendHubCommand,wW as restartLocalHubIfIdleAfterStartupTimeout,sV as resolveWorkspaceHubOwnerContext,V1 as resolveSharedHubOwnerContext,O1 as resolveProductionHubOwnerContext,H3 as resolveHubUrl,r1 as resolveHubOwnerContext,T1 as resolveHubEndpointOptions,TW as resolveHubBuildId,E8 as resolveDefaultHubPort,Z3 as resolveDefaultHubPathname,W3 as resolveDefaultHubHost,T4 as resolveCompatibleLocalHubUrl,iV as resolveClineDir,Y2 as resolveClineDataDir,L4 as requestHubShutdown,O$ as rememberRecoverableLocalHubUrl,D0 as readHubDiscovery,f7 as readBearerToken,i1 as probeHubServer,FB as probeHubConnection,RW as prewarmDetachedHubServer,z$ as normalizeHubWebSocketUrl,AY as isLocalHubOrigin,L7 as isLocalHubHostName,Y3 as isHubReconnectableTransportError,NW as isHubCommandTimeoutError,aV as isDiscoveryFilePresent,T7 as ensureHubWebSocketServer,L_ as ensureHubServer,QB as ensureDetachedHubServer,H2 as ensureCompatibleLocalHubUrl,__ as createLocalHubScheduleRuntimeHandlers,nV as createInMemoryHubOwnerContext,Y1 as createHubServerUrl,LW as createHubAuthToken,d1 as createConfiguredTelemetryService,M8 as createConfiguredTelemetryHandle,CW as connectToHub,g0 as clearHubDiscovery,B1 as NodeHubClient,x9 as NativeHubTransportAdapter,F3 as HubUIClient,y0 as HubTransportError,K3 as HubSessionClient,o6 as HubServerTransport,f8 as HubScheduleService,A8 as HubScheduleCommandService,w8 as HubCommandError,e7 as DEFAULT_HUB_PORT,$3 as DEFAULT_HUB_PATHNAME,t7 as DEFAULT_HUB_HOST,I9 as BrowserWebSocketHubAdapter};
759
+ `),$.end()}catch{$.destroy()}}function dY($,W){if(!$||!W)return!1;let Z=Buffer.from($,"utf8"),Q=Buffer.from(W,"utf8");return Z.length===Q.length&&Lv(Z,Q)}function Cf($,W){let Z=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Q=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",J=`Failed to start hub server on ${W.host}:${W.port}${W.pathname}: ${Q}`,j=Error(Z?`${J} (${Z})`:J);if(Z)$.code=Z,j.code=Z;if($ instanceof Error&&$.stack)j.stack=`${j.name}: ${j.message}
760
+ Caused by: ${$.stack}`;return j}async function Cv($){return await new Promise((W,Z)=>{let Q=Ov.createServer();Q.once("error",Z),Q.listen(0,$,()=>{let J=Q.address();if(!J||typeof J==="string"){Q.close(()=>Z(Error("Failed to resolve free port")));return}let j=J.port;Q.close((X)=>{if(X){Z(X);return}W(j)})})})}function Pv($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var lY=new Map,Pf="cline-hub-auth.",Sv=30000;function rY($){return Array.isArray($)?$.join(","):$??""}function Sf($){return $===32||$===9}function L7($){let W=rY($).trim(),Z="bearer";if(W.length<=6||W.slice(0,6).toLowerCase()!=="bearer"||!Sf(W.charCodeAt(6)))return null;let Q=7;while(Q<W.length&&Sf(W.charCodeAt(Q)))Q+=1;return W.slice(Q).trim()||null}function bv($){for(let W of rY($).split(",")){let Z=W.trim();if(Z.startsWith(Pf))return Z.slice(Pf.length).trim()||null}return null}function T7($){let W=$.trim().toLowerCase();return W==="localhost"||W==="127.0.0.1"||W==="::1"||W==="[::1]"}function UY($){let W=rY($).trim();if(!W)return!1;try{return T7(new pY(W).hostname)}catch{return!1}}async function g9($){let W=$.owner??r1(),Z=$.host??"127.0.0.1",Q=$.pathname??"/hub",J=$.port??E8(),j=J===0?await Cv(Z):J,X=j,Y=Y1(Z,j,Q),V=OW(),B=TW(),H=new o6($);await H.start();let G=new I9(new x9(H),$.telemetry),K=new Set,F=new Date().toISOString(),A={protocolVersion:Ef,minClientProtocolVersion:wf,maxClientProtocolVersion:Nf,capabilities:zv,coreVersion:_4.version,buildId:V,pid:process.pid,startedAt:F},D=new Set,U,f,_=async()=>{if(f)return f;return f=(async()=>{if(U)clearInterval(U),U=void 0;for(let L of D)L.terminate?.();D.clear();for(let L of K)L();if(K.clear(),await new Promise((L,C)=>{O.close((E)=>{if(E){C(E);return}L()})}),await new Promise((L,C)=>{R.close((E)=>{if(E){C(E);return}L()})}),await H.stop(),(await D0(W.discoveryPath))?.url===Y)await g0(W.discoveryPath)})(),f},R=Tv.createServer((T,L)=>{if((T.url??"/")==="/health"){let E=JSON.stringify({ok:!0,protocolVersion:A.protocolVersion,minClientProtocolVersion:A.minClientProtocolVersion,maxClientProtocolVersion:A.maxClientProtocolVersion,coreVersion:A.coreVersion,host:Z,port:X,url:Y});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(E);return}if((T.url??"/")==="/status"){if(!dY(L7(T.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}let E=JSON.stringify({hubId:H.getHubId(),...A,authToken:B,host:Z,port:X,url:Y,updatedAt:new Date().toISOString()});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(E);return}if((T.url??"/")==="/version"){L.statusCode=200,L.setHeader("content-type","application/json"),L.end(JSON.stringify(A));return}if(new pY(T.url??"/",`http://${Z}:${X}`).pathname==="/shutdown"&&T.method==="POST"){if(!dY(L7(T.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}L.statusCode=202,L.setHeader("content-type","application/json"),L.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{_()});return}L.statusCode=404,L.end("Not found")}),O=new Mv({noServer:!0});U=setInterval(()=>{for(let T of D){if(T.isAlive===!1){try{T.terminate?.()}catch{}D.delete(T);continue}T.isAlive=!1;try{T.ping?.()}catch{try{T.terminate?.()}catch{}D.delete(T)}}},Sv),R.on("upgrade",(T,L,C)=>{if(new pY(T.url??"/",`http://${Z}:${X}`).pathname!==Q){L.destroy();return}if(!(dY(bv(T.headers["sec-websocket-protocol"]),B)||T7(Z)&&UY(T.headers.origin))){wv(L);return}try{O.handleUpgrade(T,L,C,(x)=>{let P=x;P.isAlive=!0,P.on("pong",()=>{P.isAlive=!0}),D.add(P);let r=G.attach(Ev(x));K.add(r),x.once("close",()=>{D.delete(P),r(),K.delete(r)})})}catch{Nv(L)}});try{await new Promise((T,L)=>{R.once("error",(C)=>{L(Cf(C,{host:Z,port:j,pathname:Q}))}),R.listen(j,Z,()=>{let C=R.address();if(!C||typeof C==="string"){L(Cf(Error("Failed to resolve hub port"),{host:Z,port:j,pathname:Q}));return}X=C.port,Y=Y1(Z,X,Q),T()})})}catch(T){if(U)clearInterval(U),U=void 0;throw await H.stop().catch(()=>{return}),T}return await zW(W.discoveryPath,{hubId:H.getHubId(),protocolVersion:Ef,minClientProtocolVersion:wf,maxClientProtocolVersion:Nf,capabilities:[...A.capabilities],coreVersion:_4.version,buildId:V,authToken:B,host:Z,port:X,url:Y,pid:process.pid,startedAt:F,updatedAt:F}),{host:Z,port:X,url:Y,authToken:B,close:_}}async function O7($){let W=$.owner??r1(),Z=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=$.host??"127.0.0.1",J=$.port??E8(),j=$.pathname??"/hub",X=Y1(Q,J,j),Y=W.discoveryPath,V=(H)=>{if(!Z)O$(H.url,H.authToken);return H},B=lY.get(Y);if(B){let H=await B;if(H.url===X)return V({server:H,url:H.url,authToken:H.authToken,action:"reuse"})}return await qW(W.discoveryPath,async()=>{let H=await D0(W.discoveryPath);if(H?.url&&(H.url===X||$.allowPortFallback===!0)){let F=await i1(H.url,{authToken:H.authToken});if(F?.url&&qv(F).compatible&&await z1(F.url,{authToken:H.authToken}))return V({url:F.url,authToken:H.authToken,action:"reuse"})}if(H?.url)await g0(W.discoveryPath);let K=async(F)=>{let A=g9({...F,owner:W});lY.set(Y,A);try{let D=await A;return V({server:D,url:D.url,authToken:D.authToken,action:"started"})}catch(D){throw lY.delete(Y),D}};try{return await K($)}catch(F){if(!$.allowPortFallback||!Pv(F))throw F;return await K({...$,port:0})}})}function yf(){return bf()==="production"?O1():V1()}function yv($){return bf()!=="production"&&!$}async function L_($){let W=T1({host:$.host,port:$.port,pathname:$.pathname});return await g9({...$,...W,owner:yf()})}async function T_($){let W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=T1({host:$.host,port:$.port,pathname:$.pathname});return await O7({...$,...Z,allowPortFallback:$.allowPortFallback??yv(W),owner:yf()})}export{zW as writeHubDiscovery,qW as withHubStartupLock,z1 as verifyHubConnection,k9 as truncateNotificationBody,t7 as toHubStatusUrl,MW as toHubHealthUrl,H3 as stopLocalHubServerGracefully,g9 as startHubWebSocketServer,L_ as startHubServer,N8 as spawnDetachedHubServerWithRetry,J3 as spawnDetachedHubServer,UB as sendHubCommand,CW as restartLocalHubIfIdleAfterStartupTimeout,tV as resolveWorkspaceHubOwnerContext,V1 as resolveSharedHubOwnerContext,O1 as resolveProductionHubOwnerContext,G3 as resolveHubUrl,r1 as resolveHubOwnerContext,T1 as resolveHubEndpointOptions,OW as resolveHubBuildId,E8 as resolveDefaultHubPort,Q3 as resolveDefaultHubPathname,Z3 as resolveDefaultHubHost,T4 as resolveCompatibleLocalHubUrl,nV as resolveClineDir,Y2 as resolveClineDataDir,L4 as requestHubShutdown,O$ as rememberRecoverableLocalHubUrl,D0 as readHubDiscovery,L7 as readBearerToken,i1 as probeHubServer,AB as probeHubConnection,EW as prewarmDetachedHubServer,z$ as normalizeHubWebSocketUrl,UY as isLocalHubOrigin,T7 as isLocalHubHostName,V3 as isHubReconnectableTransportError,wW as isHubCommandTimeoutError,oV as isDiscoveryFilePresent,O7 as ensureHubWebSocketServer,T_ as ensureHubServer,JB as ensureDetachedHubServer,H2 as ensureCompatibleLocalHubUrl,f_ as createLocalHubScheduleRuntimeHandlers,aV as createInMemoryHubOwnerContext,Y1 as createHubServerUrl,TW as createHubAuthToken,d1 as createConfiguredTelemetryService,M8 as createConfiguredTelemetryHandle,PW as connectToHub,g0 as clearHubDiscovery,B1 as NodeHubClient,x9 as NativeHubTransportAdapter,A3 as HubUIClient,y0 as HubTransportError,F3 as HubSessionClient,o6 as HubServerTransport,f8 as HubScheduleService,A8 as HubScheduleCommandService,w8 as HubCommandError,$3 as DEFAULT_HUB_PORT,W3 as DEFAULT_HUB_PATHNAME,e7 as DEFAULT_HUB_HOST,I9 as BrowserWebSocketHubAdapter};