@cline/core 0.0.38 → 0.0.39

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,20 +1,20 @@
1
- import{createRequire as XY}from"node:module";var{defineProperty:ZH,getOwnPropertyNames:ZY}=Object;var Y3=Object.prototype.hasOwnProperty;function B3(f){return this[f]}var O=(f,$,J)=>{var H=ZY($);for(let W of H)if(!Y3.call(f,W)&&W!=="default")ZH(f,W,{get:B3.bind($,W),enumerable:!0});if(J){for(let W of H)if(!Y3.call(J,W)&&W!=="default")ZH(J,W,{get:B3.bind($,W),enumerable:!0});return J}};var jY=(f)=>f;function PY(f,$){this[f]=jY.bind(null,$)}var N=(f,$)=>{for(var J in $)ZH(f,J,{get:$[J],enumerable:!0,configurable:!0,set:PY.bind($,J)})};var f1=(f,$)=>()=>(f&&($=f(f=0)),$);var A3=XY(import.meta.url);function l(f,$,J){f?.capture({event:$,properties:J})}function C4(f){if(!f)return;return f.substring(0,500)}function pY(f){if(typeof f==="string")return"Error";return f.name?.trim()||f.constructor?.name||"Error"}function iY(f){return typeof f==="string"?f:f.message}function E3(f,$){return f.some((J)=>$.has(J.trim().toLowerCase()))}function S3(f){l(f,g.CLIENT.EXTENSION_ACTIVATED)}function E4(f,$){let J=[...$.vcs_types],H={root_count:$.root_count,vcs_types:J,is_multi_root:$.root_count>1,has_git:E3(J,new Set(["git"])),has_mercurial:E3(J,new Set(["mercurial","hg"]))};if($.init_duration_ms!==void 0)H.init_duration_ms=$.init_duration_ms;if($.feature_flag_enabled!==void 0)H.feature_flag_enabled=$.feature_flag_enabled;if($.is_remote_workspace!==void 0)H.is_remote_workspace=$.is_remote_workspace;l(f,g.WORKSPACE.INITIALIZED,H)}function S4(f,$,J){l(f,g.WORKSPACE.INIT_ERROR,{error_type:pY($),error_message:C4(iY($)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function k3(f,$){l(f,g.WORKSPACE.PATH_RESOLVED,{...$})}function Y0(f,$){l(f,g.USER.AUTH_STARTED,{provider:$})}function B0(f,$){l(f,g.USER.AUTH_SUCCEEDED,{provider:$})}function A0(f,$,J){l(f,g.USER.AUTH_FAILED,{provider:$,errorMessage:C4(J)})}function C0(f,$,J){l(f,g.USER.AUTH_LOGGED_OUT,{provider:$,reason:J})}function m3(f,$){f?.captureRequired(g.USER.TELEMETRY_OPT_OUT,$)}function R0(f,$){let J=$.id?.trim();if(J)f?.setDistinctId(J);f?.updateCommonProperties({account_id:$.id,account_email:$.email,provider:$.provider,organization_id:$.organizationId,organization_name:$.organizationName,member_id:$.memberId})}function k4(f,$){l(f,g.TASK.CREATED,$)}function m4(f,$){l(f,g.TASK.RESTARTED,$)}function _2(f,$){l(f,g.TASK.COMPLETED,$)}function Z1(f,$){l(f,g.TASK.CONVERSATION_TURN,{...$,timestamp:new Date().toISOString()})}function I4(f,$){l(f,g.TASK.TOKEN_USAGE,$)}function x4(f,$,J){l(f,g.TASK.MODE_SWITCH,{ulid:$,mode:J})}function g4(f,$){l(f,g.TASK.TOOL_USED,$)}function v4(f,$){l(f,g.TASK.SKILL_USED,$)}function u4(f,$){l(f,g.TASK.DIFF_EDIT_FAILED,$)}function L2(f,$){l(f,g.TASK.PROVIDER_API_ERROR,{...$,errorMessage:C4($.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function c4(f,$,J){l(f,g.TASK.MENTION_USED,{mentionType:$,contentLength:J,timestamp:new Date().toISOString()})}function d4(f,$,J,H){l(f,g.TASK.MENTION_FAILED,{mentionType:$,errorType:J,errorMessage:C4(H),timestamp:new Date().toISOString()})}function r4(f,$,J,H,W){l(f,g.TASK.MENTION_SEARCH_RESULTS,{queryLength:$.length,resultCount:J,searchType:H,isEmpty:W,timestamp:new Date().toISOString()})}function E0(f,$){l(f,g.TASK.AGENT_CREATED,{...$,timestamp:new Date().toISOString()})}function l4(f,$){l(f,g.TASK.AGENT_TEAM_CREATED,{...$,timestamp:new Date().toISOString()})}function z2(f,$){l(f,$.event==="ended"?g.TASK.SUBAGENT_COMPLETED:g.TASK.SUBAGENT_STARTED,{...$,timestamp:new Date().toISOString()})}function p4(f,$,J,H){l(f,g.HOOKS.DISCOVERY_COMPLETED,{hookName:$,globalCount:J,workspaceCount:H,totalCount:J+H,timestamp:new Date().toISOString()})}var g;var Kf=f1(()=>{g={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",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"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"}}});import{mkdirSync as nY,readFileSync as aY,writeFileSync as tY}from"node:fs";import{dirname as sY}from"node:path";import{resolveGlobalSettingsPath as g3}from"@cline/shared/storage";import{z as O2}from"zod";function x3(){return N2.parse({})}function af(){let f=g3(),$;try{$=JSON.parse(aY(f,"utf8"))}catch{return x3()}let J=N2.safeParse($);return J.success?J.data:x3()}function A$(f,$={}){let J=g3(),H=af();nY(sY(J),{recursive:!0});let W=N2.parse(f);if(!H.telemetryOptOut&&W.telemetryOptOut)m3($.telemetry);tY(J,`${JSON.stringify(W,null,2)}
2
- `,"utf8")}function i4(){return af().telemetryOptOut}function v3(f,$={}){A$({...af(),telemetryOptOut:f},$)}function uf(f){return new Set(f??af().disabledTools??[])}function q2(f){return new Set(f??af().disabledPlugins??[])}function u3(f){return uf().has(f)}function n4(f){let $=uf(),J=af();if($.has(f))return $.delete(f),A$({...J,disabledTools:[...$]}),!1;return $.add(f),A$({...J,disabledTools:[...$]}),!0}function UH(f,$){let J=[...new Set(f.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let H=af(),W=uf(H.disabledTools);for(let Q of J)if($)W.add(Q);else W.delete(Q);A$({...H,disabledTools:[...W]})}function c3(f,$){return UH([f],$),$}function d3(f){return q2().has(f)}function r3(f,$){let J=f.trim();if(!J)return;let H=af(),W=q2(H.disabledPlugins);if($)W.add(J);else W.delete(J);A$({...H,disabledPlugins:[...W]})}function a4(f,$){let J=q2($);if(J.size===0)return[...f];return f.filter((H)=>!J.has(H))}function R$(f,$){let J=uf($);if(J.size===0)return[...f];return f.filter((H)=>!J.has(H.name))}function t4(f,$){if(!f||f.length===0)return f;let J=uf($);if(J.size===0)return f;return f.map((H)=>{if(!H.setup)return H;return{...H,setup:(W,Q)=>H.setup?.({...W,registerTool:(Z)=>{if(!J.has(Z.name))W.registerTool(Z)}},Q)}})}var I3,N2;var F0=f1(()=>{Kf();I3=O2.preprocess((f)=>Array.isArray(f)?f.filter(($)=>typeof $==="string").map(($)=>$.trim()).filter(Boolean):void 0,O2.array(O2.string()).optional()).transform((f)=>{if(!f)return;let $=[...new Set(f)].sort((J,H)=>J.localeCompare(H));return $.length>0?$:void 0}),N2=O2.object({telemetryOptOut:O2.boolean().default(!1).catch(!1),disabledTools:I3.optional(),disabledPlugins:I3.optional()}).strip().transform((f)=>{let $={telemetryOptOut:f.telemetryOptOut};if(f.disabledTools?.length)$.disabledTools=f.disabledTools;if(f.disabledPlugins?.length)$.disabledPlugins=f.disabledPlugins;return $})});import{existsSync as oY,mkdirSync as eY,readFileSync as fB,writeFileSync as $B}from"node:fs";import{resolve as JB}from"node:path";import{resolveSessionDataDir as HB}from"@cline/shared/storage";import{nanoid as WB}from"nanoid";import*as QB from"node-machine-id";function F$(f){let $=f?.trim();if($)return $;let J=PB();if(J)return J;return XB()}function jB(){let f=QB;return f.machineIdSync??f.default?.machineIdSync}function PB(){try{let f=jB();if(!f)return;return f().trim()||void 0}catch{return}}function XB(){let f=HB(),$=JB(f,ZB);try{if(oY($)){let H=fB($,"utf8").trim();if(H.length>0)return H}}catch{}let J=`cl-${WB()}`;try{eY(f,{recursive:!0}),$B($,J,"utf8")}catch{}return J}var ZB="machine-id";var s4=()=>{};class w2{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(f){this.name=f.name??"OpenTelemetryAdapter",this.metadata={...f.metadata},this.meterProvider=f.meterProvider,this.loggerProvider=f.loggerProvider,this.meter=f.meterProvider?.getMeter("cline")??null,this.logger=f.loggerProvider?.getLogger("cline")??null,this.enabled=f.enabled??!0,this.distinctId=f.distinctId,this.commonProperties=f.commonProperties?{...f.commonProperties}:{}}emit(f,$){if(!this.isEnabled())return;this.emitLog(f,$,!1)}emitRequired(f,$){this.emitLog(f,$,!0)}recordCounter(f,$,J,H,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let Q=this.counters.get(f);if(!Q)Q=this.meter.createCounter(f,H?{description:H}:void 0),this.counters.set(f,Q);Q.add($,this.flattenProperties(this.buildAttributes(J)))}recordHistogram(f,$,J,H,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let Q=this.histograms.get(f);if(!Q)Q=this.meter.createHistogram(f,H?{description:H}:void 0),this.histograms.set(f,Q);Q.record($,this.flattenProperties(this.buildAttributes(J)))}recordGauge(f,$,J,H,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let Q=this.buildAttributes(J),Z=JSON.stringify(Q),j=this.gaugeValues.get(f);if($===null){if(j){if(j.delete(Z),j.size===0)this.gaugeValues.delete(f),this.gauges.delete(f)}return}let P=j;if(!P)P=new Map,this.gaugeValues.set(f,P);if(!this.gauges.has(f)){let X=this.meter.createObservableGauge(f,H?{description:H}:void 0);X.addCallback((V)=>{for(let Y of this.snapshotGaugeSeries(f))V.observe(Y.value,this.flattenProperties(Y.attributes))}),this.gauges.set(f,X)}P.set(Z,{value:$,attributes:Q})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(f){this.distinctId=f}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(f,$,J){if(!this.logger)return;let H=this.flattenProperties(this.buildAttributes($,J));this.logger.emit({severityText:"INFO",body:f,attributes:H})}buildAttributes(f,$=!1){return{...this.commonProperties,...this.metadata,...f,...this.distinctId?{distinct_id:this.distinctId}:{},...$?{_required:!0}:{}}}snapshotGaugeSeries(f){let $=this.gaugeValues.get(f);if(!$)return[];return Array.from($.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties(f,$="",J=new WeakSet,H=0){if(!f)return{};let W={},Q=100,Z=10;for(let[j,P]of Object.entries(f)){if(j==="__proto__"||j==="constructor"||j==="prototype")continue;let X=$?`${$}.${j}`:j;if(P===null||P===void 0){W[X]=String(P);continue}if(Array.isArray(P)){let V=P.length>Q?P.slice(0,Q):P;try{W[X]=JSON.stringify(V)}catch{W[X]="[UnserializableArray]"}if(P.length>Q)W[`${X}_truncated`]=!0,W[`${X}_original_length`]=P.length;continue}if(typeof P==="object"){if(P instanceof Date){W[X]=P.toISOString();continue}if(P instanceof Error){W[X]=P.message;continue}if(J.has(P)){W[X]="[Circular]";continue}if(H>=Z){W[X]="[MaxDepthExceeded]";continue}J.add(P),Object.assign(W,this.flattenProperties(P,X,J,H+1));continue}if(VB(P)){W[X]=P;continue}try{W[X]=JSON.stringify(P)}catch{W[X]=String(P)}}return W}}function VB(f){return typeof f==="string"||typeof f==="number"||typeof f==="boolean"}class C2{name;logger;enabled;constructor(f={}){this.name=f.name??"TelemetryLoggerSink",this.logger=f.logger,this.enabled=f.enabled??!0}emit(f,$){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:f,properties:$})}emitRequired(f,$){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:f,properties:$})}recordCounter(f,$,J,H,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:f,value:$,attributes:J,description:H,required:W===!0})}recordHistogram(f,$,J,H,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:f,value:$,attributes:J,description:H,required:W===!0})}recordGauge(f,$,J,H,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:f,value:$,attributes:J,description:H,required:W===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class j1{adapters;metadata;distinctId;commonProperties;constructor(f={}){if(this.adapters=[...f.adapters??[]],f.logger)this.adapters.push(new C2({logger:f.logger}));this.metadata={...f.metadata??{}},this.distinctId=f.distinctId,this.commonProperties={...f.commonProperties??{}}}addAdapter(f){this.adapters.push(f)}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return this.adapters.some((f)=>f.isEnabled())}capture(f){let $=this.buildAttributes(f.properties);for(let J of this.adapters)J.emit(f.event,$)}captureRequired(f,$){let J=this.buildAttributes($);for(let H of this.adapters)H.emitRequired(f,J)}recordCounter(f,$,J,H,W=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordCounter(f,$,Q,H,W)}recordHistogram(f,$,J,H,W=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordHistogram(f,$,Q,H,W)}recordGauge(f,$,J,H,W=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordGauge(f,$,Q,H,W)}async flush(){await Promise.all(this.adapters.map((f)=>f.flush()))}async dispose(){await Promise.all(this.adapters.map((f)=>f.dispose()))}buildAttributes(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var GH=()=>{};import{metrics as YB,trace as BB}from"@opentelemetry/api";import{logs as AB}from"@opentelemetry/api-logs";import{OTLPLogExporter as RB}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as FB}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as yB}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as KB}from"@opentelemetry/resources";import{BatchLogRecordProcessor as UB,ConsoleLogRecordExporter as GB,LoggerProvider as hB}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as TB,MeterProvider as DB,PeriodicExportingMetricReader as l3}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as MB,ConsoleSpanExporter as _B,SimpleSpanProcessor as LB}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as zB}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as OB,ATTR_SERVICE_VERSION as NB}from"@opentelemetry/semantic-conventions";class p3{distinctId;metadata;commonProperties;constructor(f={}){this.distinctId=f.distinctId,this.metadata={...f.metadata??{}},this.commonProperties={...f.commonProperties??{}}}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return!1}capture(f){this.resolveProperties(f.properties)}captureRequired(f,$){this.resolveProperties($)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class P1{meterProvider;loggerProvider;tracerProvider;options;constructor(f={}){this.options=f;let $=KB({[OB]:f.serviceName??"cline",...f.serviceVersion?{[NB]:f.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)YB.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)AB.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(f="cline",$){return BB.getTracer(f,$??this.options.serviceVersion)}createAdapter(f){return new w2({...f,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(f){let $=this.createAdapter({name:f.name,enabled:this.options.enabled,metadata:f.metadata});return new j1({...f,adapters:[$],distinctId:F$(f.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(f){let $=hH(this.options.metricsExporter);if($.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),H=Math.min(30000,Math.floor(J*0.8)),W=$.map((Q)=>wB(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:H})).filter((Q)=>Q!==null);if(W.length===0)return null;return new DB({resource:f,readers:W})}createTracerProvider(f){let $=hH(this.options.tracesExporter);if($.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,H=this.options.otlpTracesHeaders??this.options.otlpHeaders,W=[];for(let Q of $){let Z=bB(Q,{endpoint:J,headers:H,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(Z)W.push(Z)}if(W.length===0)return null;return new zB({resource:f,spanProcessors:W})}createLoggerProvider(f){let $=hH(this.options.logsExporter);if($.length===0)return null;let J=$.map((H)=>{let W=qB(H,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!W)return null;return new UB(W,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((H)=>H!==null);if(J.length===0)return null;return new hB({resource:f,processors:J})}}function E2(f){let $=new P1(f),J=$.createTelemetryService(f);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:f.enabled??!0,logsExporter:Array.isArray(f.logsExporter)?f.logsExporter.join(","):f.logsExporter,metricsExporter:Array.isArray(f.metricsExporter)?f.metricsExporter.join(","):f.metricsExporter,tracesExporter:Array.isArray(f.tracesExporter)?f.tracesExporter.join(","):f.tracesExporter,otlpProtocol:f.otlpProtocol,hasOtlpEndpoint:Boolean(f.otlpEndpoint),serviceName:f.serviceName,serviceVersion:f.serviceVersion}),{provider:$,telemetry:J}}function y$(f){if(i4())return{telemetry:new p3(f)};if(f.enabled!==!0)return{telemetry:new j1({...f,distinctId:F$(f.distinctId)})};return E2(f)}function X1(f){let{telemetry:$,provider:J}=y$(f);return{telemetry:$,provider:J,flush:async()=>{let Q=J;if(Q&&typeof Q.forceFlush==="function")try{await Q.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([$.dispose(),J?.dispose()])}}}function hH(f){if(!f)return[];return(Array.isArray(f)?f:f.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function qB(f,$){if(f==="console")return new GB;if(!$.endpoint)return null;let J=TH($.endpoint,"/v1/logs");return new RB({url:J,headers:$.headers})}function bB(f,$){if(f==="console")return new LB(new _B);if(!$.endpoint)return null;let J=TH($.endpoint,"/v1/traces");return new MB(new yB({url:J,headers:$.headers}))}function wB(f,$){if(f==="console")return new l3({exporter:new TB,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let J=TH($.endpoint,"/v1/metrics");return new l3({exporter:new FB({url:J,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function TH(f,$){let J=new URL(f),H=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=H.endsWith($)?H:`${H}${$}`,J.toString()}var o4=f1(()=>{F0();s4();GH()});var MQ={};N(MQ,{normalizeUserMessage:()=>SF,buildInitialUserContent:()=>EF});async function EF(f,$,J,H){let W=kF($),Q=await IF(J,H);if(W.length===0&&!Q)return f;let Z=[{type:"text",text:f},...W];if(Q)Z.push(...Q);return Z}function SF(f){if(f==null)return"";if(typeof f==="string")return f;let $=f.content;if(typeof $==="string")return $;if(!Array.isArray($))return"";let J=[];for(let H of $)if(H&&typeof H==="object"&&H.type==="text"){let W=H.text;if(typeof W==="string")J.push(W)}return J.join(`
3
- `)}function kF(f){if(!f||f.length===0)return[];let $=[];for(let J of f){let H=mF(J);if(H)$.push(H)}return $}function mF(f){let $=f.trim();if(!$)return;let J=$.match(/^data:([^;,]+);base64,(.+)$/);if(J){let H=J[1],W=J[2];if(!H||!W)return;return{type:"image",mediaType:H,data:W}}return{type:"image",mediaType:"image/png",data:$}}async function IF(f,$){if(!f||f.length===0)return;let J=$??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),H=await Promise.all(f.map(async(W)=>{let Q=W.replace(/\\/g,"/");try{let Z=await J(W);return{type:"file",path:Q,content:Z}}catch(Z){let j=Z instanceof Error?Z.message:String(Z);return{type:"file",path:Q,content:`Error fetching content: ${j}`}}}));if(H.length===0)return;return H}var fV={};N(fV,{createOpenTelemetryTelemetryService:()=>E2,createConfiguredTelemetryService:()=>y$,createConfiguredTelemetryHandle:()=>X1,OpenTelemetryProvider:()=>P1,OpenTelemetryAdapter:()=>w2});var $V=f1(()=>{o4()});var jV={};N(jV,{writeHubDiscovery:()=>f6,withHubStartupLock:()=>$6,verifyHubConnection:()=>sf,truncateNotificationBody:()=>h4,toHubHealthUrl:()=>LH,stopLocalHubServerGracefully:()=>mH,startHubWebSocketServer:()=>M4,startHubServer:()=>QV,spawnDetachedHubServer:()=>Y1,sendHubCommand:()=>K7,restartLocalHubIfIdleAfterStartupTimeout:()=>W6,resolveWorkspaceHubOwnerContext:()=>Q7,resolveSharedHubOwnerContext:()=>Xf,resolveHubUrl:()=>IH,resolveHubOwnerContext:()=>y0,resolveHubEndpointOptions:()=>tf,resolveHubBuildId:()=>S0,resolveDefaultHubPort:()=>V1,resolveDefaultHubPathname:()=>bH,resolveDefaultHubHost:()=>qH,resolveCompatibleLocalHubUrl:()=>x2,resolveClineDir:()=>$7,resolveClineDataDir:()=>S2,requestHubShutdown:()=>I2,rememberRecoverableLocalHubUrl:()=>k0,readHubDiscovery:()=>Qf,probeHubServer:()=>Pf,probeHubConnection:()=>y7,prewarmDetachedHubServer:()=>J6,normalizeHubWebSocketUrl:()=>m0,isHubReconnectableTransportError:()=>SH,isHubCommandTimeoutError:()=>H6,isDiscoveryFilePresent:()=>H7,ensureHubWebSocketServer:()=>oJ,ensureHubServer:()=>ZV,ensureDetachedHubServer:()=>j7,ensureCompatibleLocalHubUrl:()=>K$,createLocalHubScheduleRuntimeHandlers:()=>WV,createInMemoryHubOwnerContext:()=>J7,createHubServerUrl:()=>cf,createHubAuthToken:()=>e4,createConfiguredTelemetryService:()=>y$,createConfiguredTelemetryHandle:()=>X1,connectToHub:()=>Q6,clearHubDiscovery:()=>zf,NodeHubClient:()=>df,NativeHubTransportAdapter:()=>D4,HubUIClient:()=>gH,HubTransportError:()=>Rf,HubSessionClient:()=>xH,HubServerTransport:()=>B2,HubScheduleService:()=>Q1,HubScheduleCommandService:()=>$1,HubCommandError:()=>B1,DEFAULT_HUB_PORT:()=>OH,DEFAULT_HUB_PATHNAME:()=>NH,DEFAULT_HUB_HOST:()=>zH,BrowserWebSocketHubAdapter:()=>T4});import{createSessionId as VY}from"@cline/shared";function Lf(f,$){return{version:f.version,requestId:f.requestId,ok:!0,payload:$}}function R3(f,$,J){return{version:f.version,requestId:f.requestId??VY("hubreq_"),ok:!1,error:{code:$,message:J}}}class $1{schedules;constructor(f){this.schedules=f}async handleCommand(f){try{switch(f.command){case"schedule.create":return Lf(f,{schedule:this.schedules.createSchedule(this.toCreateInput(f.payload??{}))});case"schedule.list":return Lf(f,{schedules:this.schedules.listSchedules({enabled:typeof f.payload?.enabled==="boolean"?f.payload.enabled:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0,tags:Array.isArray(f.payload?.tags)?f.payload?.tags:void 0})});case"schedule.get":return Lf(f,{schedule:this.schedules.getSchedule(String(f.payload?.scheduleId??""))});case"schedule.update":return Lf(f,{schedule:this.schedules.updateSchedule(String(f.payload?.scheduleId??""),this.toUpdateInput(f.payload??{}))});case"schedule.delete":return Lf(f,{deleted:this.schedules.deleteSchedule(String(f.payload?.scheduleId??""))});case"schedule.enable":return Lf(f,{schedule:this.schedules.resumeSchedule(String(f.payload?.scheduleId??""))});case"schedule.disable":return Lf(f,{schedule:this.schedules.pauseSchedule(String(f.payload?.scheduleId??""))});case"schedule.trigger":return Lf(f,{execution:await this.schedules.triggerScheduleNow(String(f.payload?.scheduleId??""))});case"schedule.list_executions":return Lf(f,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof f.payload?.scheduleId==="string"?f.payload.scheduleId:void 0,status:typeof f.payload?.status==="string"?f.payload.status:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0})});case"schedule.stats":return Lf(f,{stats:this.schedules.getScheduleStats(String(f.payload?.scheduleId??""))});case"schedule.active":return Lf(f,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return Lf(f,{runs:this.schedules.getUpcomingRuns(typeof f.payload?.limit==="number"?f.payload.limit:void 0)});default:return R3(f,"unsupported_command",`Unsupported hub schedule command: ${f.command}`)}}catch($){return R3(f,"schedule_command_failed",$ instanceof Error?$.message:String($))}}toCreateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider&&f.model?{providerId:String(f.provider),modelId:String(f.model)}:void 0;return{...f,modelSelection:$}}toUpdateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider||f.model?{providerId:typeof f.provider==="string"?f.provider:"",modelId:typeof f.model==="string"?f.model:""}:void 0;return{...f,modelSelection:$}}}class y2{store;nowFn;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now())}materializeAll(){let f={oneOffQueued:0,scheduleQueued:0},$=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let H of $)if(this.materializeOneOff(H))f.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let H of J)try{if(this.materializeSchedule(H))f.scheduleQueued+=1}catch{}return f}materializeOneOff(f){if(f.triggerKind!=="one_off")return!1;if(!f.enabled||f.removed)return!1;if(this.store.hasOneOffRunForRevision(f.specId,f.revision))return!1;return this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule(f){if(f.triggerKind!=="schedule")return!1;if(!f.enabled||f.removed)return!1;if(!f.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:f.specId,nowMs:this.nowFn()}).queued}}import{basename as hY}from"node:path";import{buildClineSystemPrompt as TY}from"@cline/shared";import{nowIso as h3}from"@cline/shared/db";var ff={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"},q0=[ff.READ_FILES,ff.SEARCH_CODEBASE,ff.RUN_COMMANDS,ff.FETCH_WEB_CONTENT,ff.APPLY_PATCH,ff.EDITOR,ff.SKILLS,ff.ASK,ff.SUBMIT_AND_EXIT];var y3={};N(y3,{mergeRulesForSystemPrompt:()=>H1,loadRulesForSystemPromptFromWatcher:()=>jH,listEnabledRulesFromWatcher:()=>F3,isRuleEnabled:()=>O4,formatRulesForSystemPrompt:()=>J1});function O4(f){return f.disabled!==!0}function J1(f){if(f.length===0)return"";return`
1
+ import{createRequire as qB}from"node:module";var{defineProperty:j5,getOwnPropertyNames:OB}=Object;var M3=Object.prototype.hasOwnProperty;function L3(f){return this[f]}var z=(f,$,J)=>{var W=OB($);for(let H of W)if(!M3.call(f,H)&&H!=="default")j5(f,H,{get:L3.bind($,H),enumerable:!0});if(J){for(let H of W)if(!M3.call(J,H)&&H!=="default")j5(J,H,{get:L3.bind($,H),enumerable:!0});return J}};var zB=(f)=>f;function NB(f,$){this[f]=zB.bind(null,$)}var N=(f,$)=>{for(var J in $)j5(f,J,{get:$[J],enumerable:!0,configurable:!0,set:NB.bind($,J)})};var J1=(f,$)=>()=>(f&&($=f(f=0)),$);var h3=qB(import.meta.url);function l(f,$,J){f?.capture({event:$,properties:J})}function x4(f){if(!f)return;return f.substring(0,500)}function YY(f){if(typeof f==="string")return"Error";return f.name?.trim()||f.constructor?.name||"Error"}function VY(f){return typeof f==="string"?f:f.message}function l3(f,$){return f.some((J)=>$.has(J.trim().toLowerCase()))}function p3(f){l(f,v.CLIENT.EXTENSION_ACTIVATED)}function g4(f,$){let J=[...$.vcs_types],W={root_count:$.root_count,vcs_types:J,is_multi_root:$.root_count>1,has_git:l3(J,new Set(["git"])),has_mercurial:l3(J,new Set(["mercurial","hg"]))};if($.init_duration_ms!==void 0)W.init_duration_ms=$.init_duration_ms;if($.feature_flag_enabled!==void 0)W.feature_flag_enabled=$.feature_flag_enabled;if($.is_remote_workspace!==void 0)W.is_remote_workspace=$.is_remote_workspace;l(f,v.WORKSPACE.INITIALIZED,W)}function v4(f,$,J){l(f,v.WORKSPACE.INIT_ERROR,{error_type:YY($),error_message:x4(VY($)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function i3(f,$){l(f,v.WORKSPACE.PATH_RESOLVED,{...$})}function F0(f,$){l(f,v.USER.AUTH_STARTED,{provider:$})}function K0(f,$){l(f,v.USER.AUTH_SUCCEEDED,{provider:$})}function y0(f,$,J){l(f,v.USER.AUTH_FAILED,{provider:$,errorMessage:x4(J)})}function x0(f,$,J){l(f,v.USER.AUTH_LOGGED_OUT,{provider:$,reason:J})}function n3(f,$){f?.captureRequired(v.USER.TELEMETRY_OPT_OUT,$)}function U0(f,$){let J=$.id?.trim();if(J)f?.setDistinctId(J);f?.updateCommonProperties({account_id:$.id,account_email:$.email,provider:$.provider,organization_id:$.organizationId,organization_name:$.organizationName,member_id:$.memberId})}function u4(f,$){l(f,v.TASK.CREATED,$)}function c4(f,$){l(f,v.TASK.RESTARTED,$)}function O2(f,$){l(f,v.TASK.COMPLETED,$)}function X1(f,$){l(f,v.TASK.CONVERSATION_TURN,{...$,timestamp:new Date().toISOString()})}function d4(f,$){l(f,v.TASK.TOKEN_USAGE,$)}function r4(f,$,J){l(f,v.TASK.MODE_SWITCH,{ulid:$,mode:J})}function l4(f,$){l(f,v.TASK.TOOL_USED,$)}function p4(f,$){l(f,v.TASK.SKILL_USED,$)}function i4(f,$){l(f,v.TASK.DIFF_EDIT_FAILED,$)}function z2(f,$){l(f,v.TASK.PROVIDER_API_ERROR,{...$,errorMessage:x4($.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function n4(f,$,J){l(f,v.TASK.MENTION_USED,{mentionType:$,contentLength:J,timestamp:new Date().toISOString()})}function a4(f,$,J,W){l(f,v.TASK.MENTION_FAILED,{mentionType:$,errorType:J,errorMessage:x4(W),timestamp:new Date().toISOString()})}function t4(f,$,J,W,H){l(f,v.TASK.MENTION_SEARCH_RESULTS,{queryLength:$.length,resultCount:J,searchType:W,isEmpty:H,timestamp:new Date().toISOString()})}function g0(f,$){l(f,v.TASK.AGENT_CREATED,{...$,timestamp:new Date().toISOString()})}function s4(f,$){l(f,v.TASK.AGENT_TEAM_CREATED,{...$,timestamp:new Date().toISOString()})}function N2(f,$){l(f,$.event==="ended"?v.TASK.SUBAGENT_COMPLETED:v.TASK.SUBAGENT_STARTED,{...$,timestamp:new Date().toISOString()})}function o4(f,$,J,W){l(f,v.HOOKS.DISCOVERY_COMPLETED,{hookName:$,globalCount:J,workspaceCount:W,totalCount:J+W,timestamp:new Date().toISOString()})}var v;var _f=J1(()=>{v={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",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"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"}}});import{mkdirSync as RY,readFileSync as FY,writeFileSync as KY}from"node:fs";import{dirname as yY}from"node:path";import{resolveGlobalSettingsPath as s3}from"@cline/shared/storage";import{z as q2}from"zod";function t3(){return w2.parse({})}function sf(){let f=s3(),$;try{$=JSON.parse(FY(f,"utf8"))}catch{return t3()}let J=w2.safeParse($);return J.success?J.data:t3()}function y$(f,$={}){let J=s3(),W=sf();RY(yY(J),{recursive:!0});let H=w2.parse(f);if(!W.telemetryOptOut&&H.telemetryOptOut)n3($.telemetry);KY(J,`${JSON.stringify(H,null,2)}
2
+ `,"utf8")}function e4(){return sf().telemetryOptOut}function o3(f,$={}){y$({...sf(),telemetryOptOut:f},$)}function rf(f){return new Set(f??sf().disabledTools??[])}function b2(f){return new Set(f??sf().disabledPlugins??[])}function e3(f){return rf().has(f)}function f6(f){let $=rf(),J=sf();if($.has(f))return $.delete(f),y$({...J,disabledTools:[...$]}),!1;return $.add(f),y$({...J,disabledTools:[...$]}),!0}function G5(f,$){let J=[...new Set(f.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let W=sf(),H=rf(W.disabledTools);for(let Q of J)if($)H.add(Q);else H.delete(Q);y$({...W,disabledTools:[...H]})}function fQ(f,$){return G5([f],$),$}function $Q(f){return b2().has(f)}function JQ(f,$){let J=f.trim();if(!J)return;let W=sf(),H=b2(W.disabledPlugins);if($)H.add(J);else H.delete(J);y$({...W,disabledPlugins:[...H]})}function $6(f,$){let J=b2($);if(J.size===0)return[...f];return f.filter((W)=>!J.has(W))}function U$(f,$){let J=rf($);if(J.size===0)return[...f];return f.filter((W)=>!J.has(W.name))}function J6(f,$){if(!f||f.length===0)return f;let J=rf($);if(J.size===0)return f;return f.map((W)=>{if(!W.setup)return W;return{...W,setup:(H,Q)=>W.setup?.({...H,registerTool:(Z)=>{if(!J.has(Z.name))H.registerTool(Z)}},Q)}})}var a3,w2;var G0=J1(()=>{_f();a3=q2.preprocess((f)=>Array.isArray(f)?f.filter(($)=>typeof $==="string").map(($)=>$.trim()).filter(Boolean):void 0,q2.array(q2.string()).optional()).transform((f)=>{if(!f)return;let $=[...new Set(f)].sort((J,W)=>J.localeCompare(W));return $.length>0?$:void 0}),w2=q2.object({telemetryOptOut:q2.boolean().default(!1).catch(!1),disabledTools:a3.optional(),disabledPlugins:a3.optional()}).strip().transform((f)=>{let $={telemetryOptOut:f.telemetryOptOut};if(f.disabledTools?.length)$.disabledTools=f.disabledTools;if(f.disabledPlugins?.length)$.disabledPlugins=f.disabledPlugins;return $})});import{existsSync as UY,mkdirSync as GY,readFileSync as TY,writeFileSync as DY}from"node:fs";import{resolve as _Y}from"node:path";import{resolveSessionDataDir as MY}from"@cline/shared/storage";import{nanoid as LY}from"nanoid";import*as hY from"node-machine-id";function G$(f){let $=f?.trim();if($)return $;let J=NY();if(J)return J;return qY()}function zY(){let f=hY;return f.machineIdSync??f.default?.machineIdSync}function NY(){try{let f=zY();if(!f)return;return f().trim()||void 0}catch{return}}function qY(){let f=MY(),$=_Y(f,OY);try{if(UY($)){let W=TY($,"utf8").trim();if(W.length>0)return W}}catch{}let J=`cl-${LY()}`;try{GY(f,{recursive:!0}),DY($,J,"utf8")}catch{}return J}var OY="machine-id";var W6=()=>{};class E2{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(f){this.name=f.name??"OpenTelemetryAdapter",this.metadata={...f.metadata},this.meterProvider=f.meterProvider,this.loggerProvider=f.loggerProvider,this.meter=f.meterProvider?.getMeter("cline")??null,this.logger=f.loggerProvider?.getLogger("cline")??null,this.enabled=f.enabled??!0,this.distinctId=f.distinctId,this.commonProperties=f.commonProperties?{...f.commonProperties}:{}}emit(f,$){if(!this.isEnabled())return;this.emitLog(f,$,!1)}emitRequired(f,$){this.emitLog(f,$,!0)}recordCounter(f,$,J,W,H=!1){if(!this.meter||!H&&!this.isEnabled())return;let Q=this.counters.get(f);if(!Q)Q=this.meter.createCounter(f,W?{description:W}:void 0),this.counters.set(f,Q);Q.add($,this.flattenProperties(this.buildAttributes(J)))}recordHistogram(f,$,J,W,H=!1){if(!this.meter||!H&&!this.isEnabled())return;let Q=this.histograms.get(f);if(!Q)Q=this.meter.createHistogram(f,W?{description:W}:void 0),this.histograms.set(f,Q);Q.record($,this.flattenProperties(this.buildAttributes(J)))}recordGauge(f,$,J,W,H=!1){if(!this.meter||!H&&!this.isEnabled())return;let Q=this.buildAttributes(J),Z=JSON.stringify(Q),j=this.gaugeValues.get(f);if($===null){if(j){if(j.delete(Z),j.size===0)this.gaugeValues.delete(f),this.gauges.delete(f)}return}let X=j;if(!X)X=new Map,this.gaugeValues.set(f,X);if(!this.gauges.has(f)){let A=this.meter.createObservableGauge(f,W?{description:W}:void 0);A.addCallback((P)=>{for(let B of this.snapshotGaugeSeries(f))P.observe(B.value,this.flattenProperties(B.attributes))}),this.gauges.set(f,A)}X.set(Z,{value:$,attributes:Q})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(f){this.distinctId=f}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(f,$,J){if(!this.logger)return;let W=this.flattenProperties(this.buildAttributes($,J));this.logger.emit({severityText:"INFO",body:f,attributes:W})}buildAttributes(f,$=!1){return{...this.commonProperties,...this.metadata,...f,...this.distinctId?{distinct_id:this.distinctId}:{},...$?{_required:!0}:{}}}snapshotGaugeSeries(f){let $=this.gaugeValues.get(f);if(!$)return[];return Array.from($.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties(f,$="",J=new WeakSet,W=0){if(!f)return{};let H={},Q=100,Z=10;for(let[j,X]of Object.entries(f)){if(j==="__proto__"||j==="constructor"||j==="prototype")continue;let A=$?`${$}.${j}`:j;if(X===null||X===void 0){H[A]=String(X);continue}if(Array.isArray(X)){let P=X.length>Q?X.slice(0,Q):X;try{H[A]=JSON.stringify(P)}catch{H[A]="[UnserializableArray]"}if(X.length>Q)H[`${A}_truncated`]=!0,H[`${A}_original_length`]=X.length;continue}if(typeof X==="object"){if(X instanceof Date){H[A]=X.toISOString();continue}if(X instanceof Error){H[A]=X.message;continue}if(J.has(X)){H[A]="[Circular]";continue}if(W>=Z){H[A]="[MaxDepthExceeded]";continue}J.add(X),Object.assign(H,this.flattenProperties(X,A,J,W+1));continue}if(wY(X)){H[A]=X;continue}try{H[A]=JSON.stringify(X)}catch{H[A]=String(X)}}return H}}function wY(f){return typeof f==="string"||typeof f==="number"||typeof f==="boolean"}class S2{name;logger;enabled;constructor(f={}){this.name=f.name??"TelemetryLoggerSink",this.logger=f.logger,this.enabled=f.enabled??!0}emit(f,$){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:f,properties:$})}emitRequired(f,$){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:f,properties:$})}recordCounter(f,$,J,W,H){if(!H&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:f,value:$,attributes:J,description:W,required:H===!0})}recordHistogram(f,$,J,W,H){if(!H&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:f,value:$,attributes:J,description:W,required:H===!0})}recordGauge(f,$,J,W,H){if(!H&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:f,value:$,attributes:J,description:W,required:H===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class A1{adapters;metadata;distinctId;commonProperties;constructor(f={}){if(this.adapters=[...f.adapters??[]],f.logger)this.adapters.push(new S2({logger:f.logger}));this.metadata={...f.metadata??{}},this.distinctId=f.distinctId,this.commonProperties={...f.commonProperties??{}}}addAdapter(f){this.adapters.push(f)}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return this.adapters.some((f)=>f.isEnabled())}capture(f){let $=this.buildAttributes(f.properties);for(let J of this.adapters)J.emit(f.event,$)}captureRequired(f,$){let J=this.buildAttributes($);for(let W of this.adapters)W.emitRequired(f,J)}recordCounter(f,$,J,W,H=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordCounter(f,$,Q,W,H)}recordHistogram(f,$,J,W,H=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordHistogram(f,$,Q,W,H)}recordGauge(f,$,J,W,H=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordGauge(f,$,Q,W,H)}async flush(){await Promise.all(this.adapters.map((f)=>f.flush()))}async dispose(){await Promise.all(this.adapters.map((f)=>f.dispose()))}buildAttributes(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var T5=()=>{};import{metrics as bY,trace as CY}from"@opentelemetry/api";import{logs as EY}from"@opentelemetry/api-logs";import{OTLPLogExporter as SY}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as kY}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as IY}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as mY}from"@opentelemetry/resources";import{BatchLogRecordProcessor as xY,ConsoleLogRecordExporter as gY,LoggerProvider as vY}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as uY,MeterProvider as cY,PeriodicExportingMetricReader as WQ}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as dY,ConsoleSpanExporter as rY,SimpleSpanProcessor as lY}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as pY}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as iY,ATTR_SERVICE_VERSION as nY}from"@opentelemetry/semantic-conventions";class HQ{distinctId;metadata;commonProperties;constructor(f={}){this.distinctId=f.distinctId,this.metadata={...f.metadata??{}},this.commonProperties={...f.commonProperties??{}}}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return!1}capture(f){this.resolveProperties(f.properties)}captureRequired(f,$){this.resolveProperties($)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class P1{meterProvider;loggerProvider;tracerProvider;options;constructor(f={}){this.options=f;let $=mY({[iY]:f.serviceName??"cline",...f.serviceVersion?{[nY]:f.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)bY.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)EY.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(f="cline",$){return CY.getTracer(f,$??this.options.serviceVersion)}createAdapter(f){return new E2({...f,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(f){let $=this.createAdapter({name:f.name,enabled:this.options.enabled,metadata:f.metadata});return new A1({...f,adapters:[$],distinctId:G$(f.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(f){let $=D5(this.options.metricsExporter);if($.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),W=Math.min(30000,Math.floor(J*0.8)),H=$.map((Q)=>sY(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:W})).filter((Q)=>Q!==null);if(H.length===0)return null;return new cY({resource:f,readers:H})}createTracerProvider(f){let $=D5(this.options.tracesExporter);if($.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,W=this.options.otlpTracesHeaders??this.options.otlpHeaders,H=[];for(let Q of $){let Z=tY(Q,{endpoint:J,headers:W,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(Z)H.push(Z)}if(H.length===0)return null;return new pY({resource:f,spanProcessors:H})}createLoggerProvider(f){let $=D5(this.options.logsExporter);if($.length===0)return null;let J=$.map((W)=>{let H=aY(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!H)return null;return new xY(H,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((W)=>W!==null);if(J.length===0)return null;return new vY({resource:f,processors:J})}}function k2(f){let $=new P1(f),J=$.createTelemetryService(f);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:f.enabled??!0,logsExporter:Array.isArray(f.logsExporter)?f.logsExporter.join(","):f.logsExporter,metricsExporter:Array.isArray(f.metricsExporter)?f.metricsExporter.join(","):f.metricsExporter,tracesExporter:Array.isArray(f.tracesExporter)?f.tracesExporter.join(","):f.tracesExporter,otlpProtocol:f.otlpProtocol,hasOtlpEndpoint:Boolean(f.otlpEndpoint),serviceName:f.serviceName,serviceVersion:f.serviceVersion}),{provider:$,telemetry:J}}function T0(f){if(e4())return{telemetry:new HQ(f)};if(f.enabled!==!0)return{telemetry:new A1({...f,distinctId:G$(f.distinctId)})};return k2(f)}function B1(f){let{telemetry:$,provider:J}=T0(f);return{telemetry:$,provider:J,flush:async()=>{let Q=J;if(Q&&typeof Q.forceFlush==="function")try{await Q.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([$.dispose(),J?.dispose()])}}}function D5(f){if(!f)return[];return(Array.isArray(f)?f:f.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function aY(f,$){if(f==="console")return new gY;if(!$.endpoint)return null;let J=_5($.endpoint,"/v1/logs");return new SY({url:J,headers:$.headers})}function tY(f,$){if(f==="console")return new lY(new rY);if(!$.endpoint)return null;let J=_5($.endpoint,"/v1/traces");return new dY(new IY({url:J,headers:$.headers}))}function sY(f,$){if(f==="console")return new WQ({exporter:new uY,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let J=_5($.endpoint,"/v1/metrics");return new WQ({exporter:new kY({url:J,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function _5(f,$){let J=new URL(f),W=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=W.endsWith($)?W:`${W}${$}`,J.toString()}var H6=J1(()=>{G0();W6();T5()});var k7={};N(k7,{normalizeUserMessage:()=>JK,buildInitialUserContent:()=>$K});async function $K(f,$,J,W){let H=WK($),Q=await QK(J,W);if(H.length===0&&!Q)return f;let Z=[{type:"text",text:f},...H];if(Q)Z.push(...Q);return Z}function JK(f){if(f==null)return"";if(typeof f==="string")return f;let $=f.content;if(typeof $==="string")return $;if(!Array.isArray($))return"";let J=[];for(let W of $)if(W&&typeof W==="object"&&W.type==="text"){let H=W.text;if(typeof H==="string")J.push(H)}return J.join(`
3
+ `)}function WK(f){if(!f||f.length===0)return[];let $=[];for(let J of f){let W=HK(J);if(W)$.push(W)}return $}function HK(f){let $=f.trim();if(!$)return;let J=$.match(/^data:([^;,]+);base64,(.+)$/);if(J){let W=J[1],H=J[2];if(!W||!H)return;return{type:"image",mediaType:W,data:H}}return{type:"image",mediaType:"image/png",data:$}}async function QK(f,$){if(!f||f.length===0)return;let J=$??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),W=await Promise.all(f.map(async(H)=>{let Q=H.replace(/\\/g,"/");try{let Z=await J(H);return{type:"file",path:Q,content:Z}}catch(Z){let j=Z instanceof Error?Z.message:String(Z);return{type:"file",path:Q,content:`Error fetching content: ${j}`}}}));if(W.length===0)return;return W}var zA={};N(zA,{createOpenTelemetryTelemetryService:()=>k2,createConfiguredTelemetryService:()=>T0,createConfiguredTelemetryHandle:()=>B1,OpenTelemetryProvider:()=>P1,OpenTelemetryAdapter:()=>E2});var Y9=J1(()=>{H6()});var NP={};N(NP,{writeHubDiscovery:()=>Z6,withHubStartupLock:()=>j6,verifyHubConnection:()=>ef,truncateNotificationBody:()=>h4,toHubHealthUrl:()=>O5,stopLocalHubServerGracefully:()=>x5,startHubWebSocketServer:()=>N4,startHubServer:()=>OP,spawnDetachedHubServerWithRetry:()=>V1,spawnDetachedHubServer:()=>C5,sendHubCommand:()=>qQ,restartLocalHubIfIdleAfterStartupTimeout:()=>P6,resolveWorkspaceHubOwnerContext:()=>yQ,resolveSharedHubOwnerContext:()=>Rf,resolveHubUrl:()=>g5,resolveHubOwnerContext:()=>D0,resolveHubEndpointOptions:()=>of,resolveHubBuildId:()=>v0,resolveDefaultHubPort:()=>Y1,resolveDefaultHubPathname:()=>b5,resolveDefaultHubHost:()=>w5,resolveCompatibleLocalHubUrl:()=>v2,resolveClineDir:()=>VQ,resolveClineDataDir:()=>I2,requestHubShutdown:()=>g2,rememberRecoverableLocalHubUrl:()=>u0,readHubDiscovery:()=>Af,probeHubServer:()=>Vf,probeHubConnection:()=>NQ,prewarmDetachedHubServer:()=>X6,normalizeHubWebSocketUrl:()=>c0,isHubReconnectableTransportError:()=>I5,isHubCommandTimeoutError:()=>A6,isDiscoveryFilePresent:()=>FQ,ensureHubWebSocketServer:()=>eJ,ensureHubServer:()=>zP,ensureDetachedHubServer:()=>GQ,ensureCompatibleLocalHubUrl:()=>T$,createLocalHubScheduleRuntimeHandlers:()=>hP,createInMemoryHubOwnerContext:()=>RQ,createHubServerUrl:()=>lf,createHubAuthToken:()=>Q6,createConfiguredTelemetryService:()=>T0,createConfiguredTelemetryHandle:()=>B1,connectToHub:()=>B6,clearHubDiscovery:()=>bf,NodeHubClient:()=>pf,NativeHubTransportAdapter:()=>z4,HubUIClient:()=>u5,HubTransportError:()=>Df,HubSessionClient:()=>v5,HubServerTransport:()=>F2,HubScheduleService:()=>j1,HubScheduleCommandService:()=>W1,HubCommandError:()=>R1,DEFAULT_HUB_PORT:()=>N5,DEFAULT_HUB_PATHNAME:()=>q5,DEFAULT_HUB_HOST:()=>z5,BrowserWebSocketHubAdapter:()=>O4});import{createSessionId as wB}from"@cline/shared";function wf(f,$){return{version:f.version,requestId:f.requestId,ok:!0,payload:$}}function O3(f,$,J){return{version:f.version,requestId:f.requestId??wB("hubreq_"),ok:!1,error:{code:$,message:J}}}class W1{schedules;constructor(f){this.schedules=f}async handleCommand(f){try{switch(f.command){case"schedule.create":return wf(f,{schedule:this.schedules.createSchedule(this.toCreateInput(f.payload??{}))});case"schedule.list":return wf(f,{schedules:this.schedules.listSchedules({enabled:typeof f.payload?.enabled==="boolean"?f.payload.enabled:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0,tags:Array.isArray(f.payload?.tags)?f.payload?.tags:void 0})});case"schedule.get":return wf(f,{schedule:this.schedules.getSchedule(String(f.payload?.scheduleId??""))});case"schedule.update":return wf(f,{schedule:this.schedules.updateSchedule(String(f.payload?.scheduleId??""),this.toUpdateInput(f.payload??{}))});case"schedule.delete":return wf(f,{deleted:this.schedules.deleteSchedule(String(f.payload?.scheduleId??""))});case"schedule.enable":return wf(f,{schedule:this.schedules.resumeSchedule(String(f.payload?.scheduleId??""))});case"schedule.disable":return wf(f,{schedule:this.schedules.pauseSchedule(String(f.payload?.scheduleId??""))});case"schedule.trigger":return wf(f,{execution:await this.schedules.triggerScheduleNow(String(f.payload?.scheduleId??""))});case"schedule.list_executions":return wf(f,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof f.payload?.scheduleId==="string"?f.payload.scheduleId:void 0,status:typeof f.payload?.status==="string"?f.payload.status:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0})});case"schedule.stats":return wf(f,{stats:this.schedules.getScheduleStats(String(f.payload?.scheduleId??""))});case"schedule.active":return wf(f,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return wf(f,{runs:this.schedules.getUpcomingRuns(typeof f.payload?.limit==="number"?f.payload.limit:void 0)});default:return O3(f,"unsupported_command",`Unsupported hub schedule command: ${f.command}`)}}catch($){return O3(f,"schedule_command_failed",$ instanceof Error?$.message:String($))}}toCreateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider&&f.model?{providerId:String(f.provider),modelId:String(f.model)}:void 0;return{...f,modelSelection:$}}toUpdateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider||f.model?{providerId:typeof f.provider==="string"?f.provider:"",modelId:typeof f.model==="string"?f.model:""}:void 0;return{...f,modelSelection:$}}}class U2{store;nowFn;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now())}materializeAll(){let f={oneOffQueued:0,scheduleQueued:0},$=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let W of $)if(this.materializeOneOff(W))f.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of J)try{if(this.materializeSchedule(W))f.scheduleQueued+=1}catch{}return f}materializeOneOff(f){if(f.triggerKind!=="one_off")return!1;if(!f.enabled||f.removed)return!1;if(this.store.hasOneOffRunForRevision(f.specId,f.revision))return!1;return this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule(f){if(f.triggerKind!=="schedule")return!1;if(!f.enabled||f.removed)return!1;if(!f.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:f.specId,nowMs:this.nowFn()}).queued}}import{basename as vB}from"node:path";import{buildClineSystemPrompt as uB}from"@cline/shared";import{nowIso as C3}from"@cline/shared/db";var Jf={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"},k0=[Jf.READ_FILES,Jf.SEARCH_CODEBASE,Jf.RUN_COMMANDS,Jf.FETCH_WEB_CONTENT,Jf.APPLY_PATCH,Jf.EDITOR,Jf.SKILLS,Jf.ASK,Jf.SUBMIT_AND_EXIT];var N3={};N(N3,{mergeRulesForSystemPrompt:()=>Q1,loadRulesForSystemPromptFromWatcher:()=>X5,listEnabledRulesFromWatcher:()=>z3,isRuleEnabled:()=>E4,formatRulesForSystemPrompt:()=>H1});function E4(f){return f.disabled!==!0}function H1(f){if(f.length===0)return"";return`
4
4
 
5
5
  # Rules
6
6
  ${f.map((J)=>`## ${J.name}
7
7
  ${J.instructions}`).join(`
8
8
 
9
- `)}`}function H1(f,$){let J=f?.trim(),H=$?.trim();if(J&&H)return`${J}
9
+ `)}`}function Q1(f,$){let J=f?.trim(),W=$?.trim();if(J&&W)return`${J}
10
10
 
11
- ${H}`;return J||H||void 0}function F3(f){return[...f.getSnapshot("rule").values()].map((J)=>J.item).filter(O4).sort((J,H)=>J.name.localeCompare(H.name))}function jH(f){return J1(F3(f))}var G3={};N(G3,{normalizeWorkspacePath:()=>V0,generateWorkspaceInfoWithDiagnostics:()=>K2,generateWorkspaceInfo:()=>W1,buildWorkspaceMetadataWithInfo:()=>PH,buildWorkspaceMetadata:()=>U2});import{basename as YY,resolve as BY}from"node:path";import{performance as K3}from"node:perf_hooks";import{processWorkspaceInfo as U3}from"@cline/shared";import AY from"simple-git";function V0(f){return BY(f)}async function W1(f){return(await K2(f)).info}function N4(f){if(f instanceof Error)return{errorType:f.name?.trim()||f.constructor.name||"Error",message:f.message};return{errorType:"Error",message:String(f)}}async function K2(f){let $=V0(f),J={rootPath:$,hint:YY($)},H;try{let W=AY({baseDir:$});if(!await W.checkIsRepo())return{info:J,vcsType:"none"};try{let Z=await W.getRemotes(!0);if(Z.length>0){let j=Z.map((P)=>{let X=P.refs.fetch||P.refs.push;return`${P.name}: ${X}`});J.associatedRemoteUrls=j}}catch(Z){H??=N4(Z)}try{let Z=(await W.revparse(["HEAD"])).trim();if(Z.length>0)J.latestGitCommitHash=Z}catch(Z){H??=N4(Z)}try{let Z=(await W.branch()).current.trim();if(Z.length>0)J.latestGitBranchName=Z}catch(Z){H??=N4(Z)}return{info:J,vcsType:"git",error:H}}catch(W){return{info:J,vcsType:"none",error:N4(W)}}}async function U2(f){let $=await W1(f);return U3($)}async function PH(f){let $=K3.now(),J=await K2(f),H=K3.now()-$,W=J.info;return{workspaceInfo:W,workspaceMetadata:U3(W),durationMs:H,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as RY,writeFileSync as FY}from"node:fs";import{join as yY}from"node:path";import{resolveCronReportsDir as KY}from"@cline/shared/storage";function b0(f){if(/[:#\n]/.test(f)||f.includes('"'))return JSON.stringify(f);return f}function V$(f,$){if($===void 0||$===null)return;return`${f}: ${b0($)}`}function UY(f,$,J){let H=[`runId: ${b0(f.runId)}`,`specId: ${b0($.specId)}`,`externalId: ${b0($.externalId)}`,`title: ${b0($.title)}`,`triggerKind: ${b0(f.triggerKind)}`,`status: ${b0(f.status)}`,`sourcePath: ${b0($.sourcePath)}`],W=[V$("sessionId",f.sessionId),V$("startedAt",f.startedAt),V$("completedAt",f.completedAt),V$("triggerEventId",f.triggerEventId),V$("triggerEventType",J?.eventType),V$("triggerEventSource",J?.source),V$("triggerEventSubject",J?.subject)];for(let Q of W)if(Q)H.push(Q);return`---
12
- ${H.join(`
11
+ ${W}`;return J||W||void 0}function z3(f){return[...f.getSnapshot("rule").values()].map((J)=>J.item).filter(E4).sort((J,W)=>J.name.localeCompare(W.name))}function X5(f){return H1(z3(f))}var b3={};N(b3,{normalizeWorkspacePath:()=>R0,generateWorkspaceInfoWithDiagnostics:()=>G2,generateWorkspaceInfo:()=>Z1,buildWorkspaceMetadataWithInfo:()=>A5,buildWorkspaceMetadata:()=>T2});import{basename as bB,resolve as CB}from"node:path";import{performance as q3}from"node:perf_hooks";import{processWorkspaceInfo as w3}from"@cline/shared";import EB from"simple-git";function R0(f){return CB(f)}async function Z1(f){return(await G2(f)).info}function S4(f){if(f instanceof Error)return{errorType:f.name?.trim()||f.constructor.name||"Error",message:f.message};return{errorType:"Error",message:String(f)}}async function G2(f){let $=R0(f),J={rootPath:$,hint:bB($)},W;try{let H=EB({baseDir:$});if(!await H.checkIsRepo())return{info:J,vcsType:"none"};try{let Z=await H.getRemotes(!0);if(Z.length>0){let j=Z.map((X)=>{let A=X.refs.fetch||X.refs.push;return`${X.name}: ${A}`});J.associatedRemoteUrls=j}}catch(Z){W??=S4(Z)}try{let Z=(await H.revparse(["HEAD"])).trim();if(Z.length>0)J.latestGitCommitHash=Z}catch(Z){W??=S4(Z)}try{let Z=(await H.branch()).current.trim();if(Z.length>0)J.latestGitBranchName=Z}catch(Z){W??=S4(Z)}return{info:J,vcsType:"git",error:W}}catch(H){return{info:J,vcsType:"none",error:S4(H)}}}async function T2(f){let $=await Z1(f);return w3($)}async function A5(f){let $=q3.now(),J=await G2(f),W=q3.now()-$,H=J.info;return{workspaceInfo:H,workspaceMetadata:w3(H),durationMs:W,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as SB,writeFileSync as kB}from"node:fs";import{join as IB}from"node:path";import{resolveCronReportsDir as mB}from"@cline/shared/storage";function I0(f){if(/[:#\n]/.test(f)||f.includes('"'))return JSON.stringify(f);return f}function R$(f,$){if($===void 0||$===null)return;return`${f}: ${I0($)}`}function xB(f,$,J){let W=[`runId: ${I0(f.runId)}`,`specId: ${I0($.specId)}`,`externalId: ${I0($.externalId)}`,`title: ${I0($.title)}`,`triggerKind: ${I0(f.triggerKind)}`,`status: ${I0(f.status)}`,`sourcePath: ${I0($.sourcePath)}`],H=[R$("sessionId",f.sessionId),R$("startedAt",f.startedAt),R$("completedAt",f.completedAt),R$("triggerEventId",f.triggerEventId),R$("triggerEventType",J?.eventType),R$("triggerEventSource",J?.source),R$("triggerEventSubject",J?.subject)];for(let Q of H)if(Q)W.push(Q);return`---
12
+ ${W.join(`
13
13
  `)}
14
14
  ---
15
- `}function GY(f){let $=[];if(f.triggerEvent){let J=f.triggerEvent,H=[`- eventId: ${J.eventId}`,`- eventType: ${J.eventType}`,`- source: ${J.source}`,J.subject?`- subject: ${J.subject}`:"",`- occurredAt: ${J.occurredAt}`,J.dedupeKey?`- dedupeKey: ${J.dedupeKey}`:"",J.attributes?`- attributes: ${JSON.stringify(J.attributes)}`:""].filter((W)=>W.length>0);$.push(`## Trigger Event
15
+ `}function gB(f){let $=[];if(f.triggerEvent){let J=f.triggerEvent,W=[`- eventId: ${J.eventId}`,`- eventType: ${J.eventType}`,`- source: ${J.source}`,J.subject?`- subject: ${J.subject}`:"",`- occurredAt: ${J.occurredAt}`,J.dedupeKey?`- dedupeKey: ${J.dedupeKey}`:"",J.attributes?`- attributes: ${JSON.stringify(J.attributes)}`:""].filter((H)=>H.length>0);$.push(`## Trigger Event
16
16
 
17
- ${H.join(`
17
+ ${W.join(`
18
18
  `)}
19
19
  `)}if(f.error)$.push(`## Error
20
20
 
@@ -22,21 +22,21 @@ ${f.error}
22
22
  `);if(f.finalText&&f.finalText.trim().length>0)$.push(`## Summary
23
23
 
24
24
  ${f.finalText.trim()}
25
- `);if(f.usage){let J=f.usage,H=[J.inputTokens!==void 0?`- inputTokens: ${J.inputTokens}`:"",J.outputTokens!==void 0?`- outputTokens: ${J.outputTokens}`:"",J.cacheReadTokens!==void 0?`- cacheReadTokens: ${J.cacheReadTokens}`:"",J.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${J.cacheWriteTokens}`:"",J.totalCost!==void 0?`- totalCostUsd: ${J.totalCost}`:"",f.durationMs!==void 0?`- durationMs: ${f.durationMs}`:""].filter((W)=>W.length>0);if(H.length>0)$.push(`## Usage
25
+ `);if(f.usage){let J=f.usage,W=[J.inputTokens!==void 0?`- inputTokens: ${J.inputTokens}`:"",J.outputTokens!==void 0?`- outputTokens: ${J.outputTokens}`:"",J.cacheReadTokens!==void 0?`- cacheReadTokens: ${J.cacheReadTokens}`:"",J.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${J.cacheWriteTokens}`:"",J.totalCost!==void 0?`- totalCostUsd: ${J.totalCost}`:"",f.durationMs!==void 0?`- durationMs: ${f.durationMs}`:""].filter((H)=>H.length>0);if(W.length>0)$.push(`## Usage
26
26
 
27
- ${H.join(`
27
+ ${W.join(`
28
28
  `)}
29
- `)}if(f.toolCalls&&f.toolCalls.length>0){let J=f.toolCalls.map((H)=>{let W=[`- ${H.name}`];if(H.durationMs!==void 0)W.push(`(${H.durationMs}ms)`);if(H.error)W.push(`error: ${H.error}`);return W.join(" ")});$.push(`## Tool Calls
29
+ `)}if(f.toolCalls&&f.toolCalls.length>0){let J=f.toolCalls.map((W)=>{let H=[`- ${W.name}`];if(W.durationMs!==void 0)H.push(`(${W.durationMs}ms)`);if(W.error)H.push(`error: ${W.error}`);return H.join(" ")});$.push(`## Tool Calls
30
30
 
31
31
  ${J.join(`
32
32
  `)}
33
33
  `)}return $.join(`
34
- `)}function XH(f){let $=KY(f.specs);RY($,{recursive:!0});let J=yY($,`${f.run.runId}.md`),H=`${UY(f.run,f.spec,f.data.triggerEvent)}
35
- ${GY(f.data)}`;return FY(J,H,"utf8"),J}class VH{globalMaxConcurrency;activeExecutions=new Map;constructor(f){this.globalMaxConcurrency=Math.max(1,Math.floor(f))}acquire(f,$,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let H=Math.max(1,Math.floor(J)),W=this.activeExecutions.get(f)??new Set;if(W.size>=H)return!1;return W.add($),this.activeExecutions.set(f,W),!0}release(f,$){let J=this.activeExecutions.get(f);if(!J)return;if(J.delete($),J.size===0)this.activeExecutions.delete(f)}getGlobalActiveCount(){let f=0;for(let $ of this.activeExecutions.values())f+=$.size;return f}}var DY=15000,MY=90,T3=["rules","skills","plugins"];function _Y(f,$){return new Set(f.extensions??T3).has($)}function LY(f,$){if(f.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let H of f.tools)J[H]={enabled:!0,autoApprove:!0};if($==="yolo")J[ff.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function zY(f){let $=f?.trim();if(!$)return;return["# Notes Directory",`Use ${$} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
36
- `)}class YH extends Error{constructor(f){super(f);this.name="TimeoutError"}}async function OY(f,$){if($<=0)return f;let J,H=new Promise((W,Q)=>{J=setTimeout(()=>{Q(new YH("cron run timed out"))},$)});try{return await Promise.race([f,H])}finally{if(J)clearTimeout(J)}}class G2{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor(f){this.store=f.store,this.materializer=f.materializer,this.options=f,this.limiter=new VH(f.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,(f.claimLeaseSeconds??MY)*1000)}async start(){if(this.disposed)throw Error("CronRunner disposed");if(this.started)return;this.stopping=!1,this.started=!0;let f=Math.max(2000,this.options.pollIntervalMs??DY);await this.tick(),this.timer=setInterval(()=>void this.tick(),f)}async stop(){let f=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!f)return;let $=[...this.activeRuns.entries()];await Promise.all($.map(async([J,H])=>{if(H.sessionId)try{await this.options.runtimeHandlers.abortSession(H.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:H.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let f=this.store.claimDueRuns({nowIso:h3(),leaseMs:this.claimLeaseMs});await Promise.allSettled(f.map(($)=>this.executeClaim($)))}catch(f){let $=this.options.logger;if($)if($.error)$.error("cron.runner.tick.failed",{error:f});else $.log("cron.runner.tick.failed",{error:f})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([f,$])=>{let J=this.store.getRun(f);return J?[{...J,...$}]:[]})}async executeClaim(f){let $=f.run,J=this.store.getSpec($.specId);if(!J){this.store.completeRun($.runId,{status:"failed",error:"spec not found",claimToken:f.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun($.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:f.claimToken});return}let H=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,$.runId,H)){this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,$.runId),this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set($.runId,{claimToken:f.claimToken});let Q=$.triggerEventId?this.store.getEventLog($.triggerEventId):void 0,Z,j,P=Date.now(),X;if(J.timeoutSeconds&&J.timeoutSeconds>0)X=P+J.timeoutSeconds*1000;try{j=this.startClaimLeaseHeartbeat(f);let V=await this.buildStartRequest(J);if(Z=(await this.options.runtimeHandlers.startSession(V)).sessionId.trim(),!Z)throw Error("runtime returned empty sessionId");this.activeRuns.set($.runId,{claimToken:f.claimToken,sessionId:Z}),this.store.attachSessionIdToRun($.runId,Z);let B={config:V,prompt:this.buildPrompt(J,Q)},A=this.options.runtimeHandlers.sendSession(Z,B),R=X?Math.max(1,X-Date.now()):0,y=(await OY(A,R)).result,F=Date.now(),K=XH({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:Z,status:"done"},spec:J,data:{finalText:y.text,usage:y.usage,toolCalls:y.toolCalls,durationMs:F-P,triggerEvent:Q}});this.store.completeRun($.runId,{status:"done",sessionId:Z,reportPath:K,claimToken:f.claimToken}),this.store.updateSpecLastRunAt(J.specId,h3())}catch(V){let Y=V instanceof YH;if(Z&&Y)try{await this.options.runtimeHandlers.abortSession(Z)}catch{}let B=V instanceof Error?V.message:String(V),A=Date.now(),R=XH({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:Z,status:"failed"},spec:J,data:{error:B,durationMs:A-P,triggerEvent:Q}});this.store.completeRun($.runId,{status:"failed",sessionId:Z,reportPath:R,error:B,claimToken:f.claimToken})}finally{if(j?.(),Z)try{await this.options.runtimeHandlers.stopSession(Z)}catch{}this.activeRuns.delete($.runId),this.limiter.release(J.specId,$.runId)}}buildPrompt(f,$){let J=f.prompt??"";if(!$)return J;let H={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload};return`${J}
34
+ `)}function P5(f){let $=mB(f.specs);SB($,{recursive:!0});let J=IB($,`${f.run.runId}.md`),W=`${xB(f.run,f.spec,f.data.triggerEvent)}
35
+ ${gB(f.data)}`;return kB(J,W,"utf8"),J}class B5{globalMaxConcurrency;activeExecutions=new Map;constructor(f){this.globalMaxConcurrency=Math.max(1,Math.floor(f))}acquire(f,$,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let W=Math.max(1,Math.floor(J)),H=this.activeExecutions.get(f)??new Set;if(H.size>=W)return!1;return H.add($),this.activeExecutions.set(f,H),!0}release(f,$){let J=this.activeExecutions.get(f);if(!J)return;if(J.delete($),J.size===0)this.activeExecutions.delete(f)}getGlobalActiveCount(){let f=0;for(let $ of this.activeExecutions.values())f+=$.size;return f}}var cB=15000,dB=90,E3=["rules","skills","plugins"];function rB(f,$){return new Set(f.extensions??E3).has($)}function lB(f,$){if(f.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let W of f.tools)J[W]={enabled:!0,autoApprove:!0};if($==="yolo")J[Jf.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function pB(f){let $=f?.trim();if(!$)return;return["# Notes Directory",`Use ${$} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
36
+ `)}class Y5 extends Error{constructor(f){super(f);this.name="TimeoutError"}}async function iB(f,$){if($<=0)return f;let J,W=new Promise((H,Q)=>{J=setTimeout(()=>{Q(new Y5("cron run timed out"))},$)});try{return await Promise.race([f,W])}finally{if(J)clearTimeout(J)}}class D2{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor(f){this.store=f.store,this.materializer=f.materializer,this.options=f,this.limiter=new B5(f.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,(f.claimLeaseSeconds??dB)*1000)}async start(){if(this.disposed)throw Error("CronRunner disposed");if(this.started)return;this.stopping=!1,this.started=!0;let f=Math.max(2000,this.options.pollIntervalMs??cB);await this.tick(),this.timer=setInterval(()=>void this.tick(),f)}async stop(){let f=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!f)return;let $=[...this.activeRuns.entries()];await Promise.all($.map(async([J,W])=>{if(W.sessionId)try{await this.options.runtimeHandlers.abortSession(W.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:W.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let f=this.store.claimDueRuns({nowIso:C3(),leaseMs:this.claimLeaseMs});await Promise.allSettled(f.map(($)=>this.executeClaim($)))}catch(f){let $=this.options.logger;if($)if($.error)$.error("cron.runner.tick.failed",{error:f});else $.log("cron.runner.tick.failed",{error:f})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([f,$])=>{let J=this.store.getRun(f);return J?[{...J,...$}]:[]})}async executeClaim(f){let $=f.run,J=this.store.getSpec($.specId);if(!J){this.store.completeRun($.runId,{status:"failed",error:"spec not found",claimToken:f.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun($.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:f.claimToken});return}let W=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,$.runId,W)){this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,$.runId),this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set($.runId,{claimToken:f.claimToken});let Q=$.triggerEventId?this.store.getEventLog($.triggerEventId):void 0,Z,j,X=Date.now(),A;if(J.timeoutSeconds&&J.timeoutSeconds>0)A=X+J.timeoutSeconds*1000;try{j=this.startClaimLeaseHeartbeat(f);let P=await this.buildStartRequest(J);if(Z=(await this.options.runtimeHandlers.startSession(P)).sessionId.trim(),!Z)throw Error("runtime returned empty sessionId");this.activeRuns.set($.runId,{claimToken:f.claimToken,sessionId:Z}),this.store.attachSessionIdToRun($.runId,Z);let Y={config:P,prompt:this.buildPrompt(J,Q)},V=this.options.runtimeHandlers.sendSession(Z,Y),R=A?Math.max(1,A-Date.now()):0,K=(await iB(V,R)).result,F=Date.now(),y=P5({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:Z,status:"done"},spec:J,data:{finalText:K.text,usage:K.usage,toolCalls:K.toolCalls,durationMs:F-X,triggerEvent:Q}});this.store.completeRun($.runId,{status:"done",sessionId:Z,reportPath:y,claimToken:f.claimToken}),this.store.updateSpecLastRunAt(J.specId,C3())}catch(P){let B=P instanceof Y5;if(Z&&B)try{await this.options.runtimeHandlers.abortSession(Z)}catch{}let Y=P instanceof Error?P.message:String(P),V=Date.now(),R=P5({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:Z,status:"failed"},spec:J,data:{error:Y,durationMs:V-X,triggerEvent:Q}});this.store.completeRun($.runId,{status:"failed",sessionId:Z,reportPath:R,error:Y,claimToken:f.claimToken})}finally{if(j?.(),Z)try{await this.options.runtimeHandlers.stopSession(Z)}catch{}this.activeRuns.delete($.runId),this.limiter.release(J.specId,$.runId)}}buildPrompt(f,$){let J=f.prompt??"";if(!$)return J;let W={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload};return`${J}
37
37
 
38
38
  Trigger event:
39
- ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let H=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim(f.run.runId,f.claimToken,H))clearInterval(J)},$);return()=>clearInterval(J)}async buildSystemPrompt(f,$,J,H){let W=zY(f.notesDirectory),Q=H1(void 0,W),Z=await U2($),j=TY({ide:"Cline Cron",workspaceRoot:$,workspaceName:hY($),metadata:Z,rules:f.systemPrompt?void 0:Q,mode:J,providerId:H,overridePrompt:f.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return f.systemPrompt?H1(j,Q)??j:j}async buildStartRequest(f){let $=(f.workspaceRoot??"").trim(),J=(f.providerId??"").trim(),H=(f.modelId??"").trim(),W=f.metadata?.__hubRuntimeOptions&&typeof f.metadata.__hubRuntimeOptions==="object"&&!Array.isArray(f.metadata.__hubRuntimeOptions)?f.metadata.__hubRuntimeOptions:void 0,Q=typeof f.metadata?.__hubScheduleCwd==="string"&&f.metadata.__hubScheduleCwd.trim()?f.metadata.__hubScheduleCwd.trim():$;if(!$)throw Error("cron spec requires workspaceRoot");let Z=f.mode==="plan"?"plan":f.mode==="act"?"act":"yolo";return{workspaceRoot:$,cwd:Q,provider:J,model:H,mode:Z,source:f.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt(f,$,Z,J),maxIterations:f.maxIterations,enableTools:W?.enableTools??!0,enableSpawn:W?.enableSpawn??!0,enableTeams:W?.enableTeams??!0,autoApproveTools:W?.autoApproveTools??!0,toolPolicies:LY(f,Z),configExtensions:T3.filter((j)=>_Y(f,j))}}}function h2(f,$,J,H){let W=new Set;function Q(Z){let j=Z.toLowerCase();if(H){let X=H.indexOf(j);if(X!==-1)return X+$}let P=Number(Z);if(!Number.isInteger(P)||P<$||P>J)throw Error(`Invalid cron value "${Z}" for range [${$}-${J}]`);return P}for(let Z of f.split(",")){if(Z==="*"){for(let X=$;X<=J;X+=1)W.add(X);continue}let j=Z.indexOf("/");if(j!==-1){let X=Z.slice(0,j),V=Number(Z.slice(j+1));if(!Number.isInteger(V)||V<1)throw Error(`Invalid step "${Z.slice(j+1)}"`);let Y=$,B=J;if(X!=="*"){let A=X.indexOf("-");if(A!==-1)Y=Q(X.slice(0,A)),B=Q(X.slice(A+1));else Y=Q(X)}if(Y>B)throw Error(`Invalid cron range "${X}"`);for(let A=Y;A<=B;A+=V)W.add(A);continue}let P=Z.indexOf("-");if(P!==-1){let X=Q(Z.slice(0,P)),V=Q(Z.slice(P+1));if(X>V)throw Error(`Invalid cron range "${Z}"`);for(let Y=X;Y<=V;Y+=1)W.add(Y);continue}W.add(Q(Z))}return[...W].sort((Z,j)=>Z-j)}var NY=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],M3=["sun","mon","tue","wed","thu","fri","sat"];function T2(f,$,J){let H=f[$];if(typeof H!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${$+1}`);return H}function BH(f,$){let J=f[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${$}`);return J}function AH(f){let $=f.trim().split(/\s+/);if($.length!==5)throw Error(`Invalid cron pattern "${f}": expected 5 fields, got ${$.length}`);return{minutes:h2(T2($,0,f),0,59),hours:h2(T2($,1,f),0,23),daysOfMonth:h2(T2($,2,f),1,31),months:h2(T2($,3,f),1,12,NY),daysOfWeek:h2(T2($,4,f),0,6,M3)}}function RH(f){AH(f)}function _3(f,$,J=Date.now()){Y$(f,J,$)}var D3=new Map,qY=new Map(M3.map((f,$)=>[f,$]));function L3(f){let $=f?.trim();return $?$:void 0}function z3(f){let $=D3.get(f);if($)return $;let J=new Intl.DateTimeFormat("en-US",{timeZone:f,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return D3.set(f,J),J}function bY(f){let $=L3(f);if(!$)return;z3($).format(new Date)}function wY(f,$){let J=z3($).formatToParts(new Date(f)),H=new Map(J.map((Z)=>[Z.type,Z.value])),W=H.get("weekday")?.toLowerCase().slice(0,3)??"",Q=qY.get(W);if(Q===void 0)throw Error(`Unable to resolve weekday for timezone "${$}"`);return{month:Number(H.get("month")),dayOfMonth:Number(H.get("day")),dayOfWeek:Q,hour:Number(H.get("hour")),minute:Number(H.get("minute"))}}function CY(f){let $=new Date(f);return{month:$.getMonth()+1,dayOfMonth:$.getDate(),dayOfWeek:$.getDay(),hour:$.getHours(),minute:$.getMinutes()}}function EY(f,$){return f.months.includes($.month)&&f.daysOfMonth.includes($.dayOfMonth)&&f.daysOfWeek.includes($.dayOfWeek)&&f.hours.includes($.hour)&&f.minutes.includes($.minute)}function SY(f,$,J){let H=AH(f),W=new Date($);W.setSeconds(0,0);let Q=W.getTime()+60000,Z=new Date($);Z.setFullYear(Z.getFullYear()+4);let j=Z.getTime();while(Q<=j){if(EY(H,wY(Q,J)))return Q;Q+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${f}" in timezone "${J}"`)}function Y$(f,$,J){let H=L3(J);if(H)return bY(H),SY(f,$,H);let W=AH(f),Q=new Date($);Q.setSeconds(0,0),Q=new Date(Q.getTime()+60000);let Z=new Date($);Z.setFullYear(Z.getFullYear()+4);while(Q<=Z){let{month:j,dayOfMonth:P,dayOfWeek:X,hour:V,minute:Y}=CY(Q.getTime());if(!W.months.includes(j)){let B=W.months.find((R)=>R>j)??BH(W.months,"months"),A=B<=j?1:0;Q=new Date(Q.getFullYear()+A,B-1,1,0,0,0,0);continue}if(!W.daysOfMonth.includes(P)||!W.daysOfWeek.includes(X)){Q=new Date(Q.getFullYear(),Q.getMonth(),P+1,0,0,0,0);continue}if(!W.hours.includes(V)){let B=W.hours.find((R)=>R>V)??BH(W.hours,"hours"),A=B<=V?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()+A,B,0,0,0);continue}if(!W.minutes.includes(Y)){let B=W.minutes.find((R)=>R>Y)??BH(W.minutes,"minutes"),A=B<=Y?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate(),Q.getHours()+A,B,0,0);continue}return Q.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${f}"`)}import{randomUUID as D2}from"node:crypto";import{asOptionalString as S,asString as i,loadSqliteDb as mY,nowIso as jf}from"@cline/shared/db";import{resolveCronDbPath as IY}from"@cline/shared/storage";var kY=[`CREATE TABLE IF NOT EXISTS cron_specs (
39
+ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let W=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim(f.run.runId,f.claimToken,W))clearInterval(J)},$);return()=>clearInterval(J)}async buildSystemPrompt(f,$,J,W){let H=pB(f.notesDirectory),Q=Q1(void 0,H),Z=await T2($),j=uB({ide:"Cline Cron",workspaceRoot:$,workspaceName:vB($),metadata:Z,rules:f.systemPrompt?void 0:Q,mode:J,providerId:W,overridePrompt:f.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return f.systemPrompt?Q1(j,Q)??j:j}async buildStartRequest(f){let $=(f.workspaceRoot??"").trim(),J=(f.providerId??"").trim(),W=(f.modelId??"").trim(),H=f.metadata?.__hubRuntimeOptions&&typeof f.metadata.__hubRuntimeOptions==="object"&&!Array.isArray(f.metadata.__hubRuntimeOptions)?f.metadata.__hubRuntimeOptions:void 0,Q=typeof f.metadata?.__hubScheduleCwd==="string"&&f.metadata.__hubScheduleCwd.trim()?f.metadata.__hubScheduleCwd.trim():$;if(!$)throw Error("cron spec requires workspaceRoot");let Z=f.mode==="plan"?"plan":f.mode==="act"?"act":"yolo";return{workspaceRoot:$,cwd:Q,provider:J,model:W,mode:Z,source:f.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt(f,$,Z,J),maxIterations:f.maxIterations,enableTools:H?.enableTools??!0,enableSpawn:H?.enableSpawn??!0,enableTeams:H?.enableTeams??!0,autoApproveTools:H?.autoApproveTools??!0,toolPolicies:lB(f,Z),configExtensions:E3.filter((j)=>rB(f,j))}}}function _2(f,$,J,W){let H=new Set;function Q(Z){let j=Z.toLowerCase();if(W){let A=W.indexOf(j);if(A!==-1)return A+$}let X=Number(Z);if(!Number.isInteger(X)||X<$||X>J)throw Error(`Invalid cron value "${Z}" for range [${$}-${J}]`);return X}for(let Z of f.split(",")){if(Z==="*"){for(let A=$;A<=J;A+=1)H.add(A);continue}let j=Z.indexOf("/");if(j!==-1){let A=Z.slice(0,j),P=Number(Z.slice(j+1));if(!Number.isInteger(P)||P<1)throw Error(`Invalid step "${Z.slice(j+1)}"`);let B=$,Y=J;if(A!=="*"){let V=A.indexOf("-");if(V!==-1)B=Q(A.slice(0,V)),Y=Q(A.slice(V+1));else B=Q(A)}if(B>Y)throw Error(`Invalid cron range "${A}"`);for(let V=B;V<=Y;V+=P)H.add(V);continue}let X=Z.indexOf("-");if(X!==-1){let A=Q(Z.slice(0,X)),P=Q(Z.slice(X+1));if(A>P)throw Error(`Invalid cron range "${Z}"`);for(let B=A;B<=P;B+=1)H.add(B);continue}H.add(Q(Z))}return[...H].sort((Z,j)=>Z-j)}var nB=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],k3=["sun","mon","tue","wed","thu","fri","sat"];function M2(f,$,J){let W=f[$];if(typeof W!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${$+1}`);return W}function V5(f,$){let J=f[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${$}`);return J}function R5(f){let $=f.trim().split(/\s+/);if($.length!==5)throw Error(`Invalid cron pattern "${f}": expected 5 fields, got ${$.length}`);return{minutes:_2(M2($,0,f),0,59),hours:_2(M2($,1,f),0,23),daysOfMonth:_2(M2($,2,f),1,31),months:_2(M2($,3,f),1,12,nB),daysOfWeek:_2(M2($,4,f),0,6,k3)}}function F5(f){R5(f)}function I3(f,$,J=Date.now()){F$(f,J,$)}var S3=new Map,aB=new Map(k3.map((f,$)=>[f,$]));function m3(f){let $=f?.trim();return $?$:void 0}function x3(f){let $=S3.get(f);if($)return $;let J=new Intl.DateTimeFormat("en-US",{timeZone:f,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return S3.set(f,J),J}function tB(f){let $=m3(f);if(!$)return;x3($).format(new Date)}function sB(f,$){let J=x3($).formatToParts(new Date(f)),W=new Map(J.map((Z)=>[Z.type,Z.value])),H=W.get("weekday")?.toLowerCase().slice(0,3)??"",Q=aB.get(H);if(Q===void 0)throw Error(`Unable to resolve weekday for timezone "${$}"`);return{month:Number(W.get("month")),dayOfMonth:Number(W.get("day")),dayOfWeek:Q,hour:Number(W.get("hour")),minute:Number(W.get("minute"))}}function oB(f){let $=new Date(f);return{month:$.getMonth()+1,dayOfMonth:$.getDate(),dayOfWeek:$.getDay(),hour:$.getHours(),minute:$.getMinutes()}}function eB(f,$){return f.months.includes($.month)&&f.daysOfMonth.includes($.dayOfMonth)&&f.daysOfWeek.includes($.dayOfWeek)&&f.hours.includes($.hour)&&f.minutes.includes($.minute)}function fY(f,$,J){let W=R5(f),H=new Date($);H.setSeconds(0,0);let Q=H.getTime()+60000,Z=new Date($);Z.setFullYear(Z.getFullYear()+4);let j=Z.getTime();while(Q<=j){if(eB(W,sB(Q,J)))return Q;Q+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${f}" in timezone "${J}"`)}function F$(f,$,J){let W=m3(J);if(W)return tB(W),fY(f,$,W);let H=R5(f),Q=new Date($);Q.setSeconds(0,0),Q=new Date(Q.getTime()+60000);let Z=new Date($);Z.setFullYear(Z.getFullYear()+4);while(Q<=Z){let{month:j,dayOfMonth:X,dayOfWeek:A,hour:P,minute:B}=oB(Q.getTime());if(!H.months.includes(j)){let Y=H.months.find((R)=>R>j)??V5(H.months,"months"),V=Y<=j?1:0;Q=new Date(Q.getFullYear()+V,Y-1,1,0,0,0,0);continue}if(!H.daysOfMonth.includes(X)||!H.daysOfWeek.includes(A)){Q=new Date(Q.getFullYear(),Q.getMonth(),X+1,0,0,0,0);continue}if(!H.hours.includes(P)){let Y=H.hours.find((R)=>R>P)??V5(H.hours,"hours"),V=Y<=P?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()+V,Y,0,0,0);continue}if(!H.minutes.includes(B)){let Y=H.minutes.find((R)=>R>B)??V5(H.minutes,"minutes"),V=Y<=B?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate(),Q.getHours()+V,Y,0,0);continue}return Q.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${f}"`)}import{randomUUID as L2}from"node:crypto";import{asOptionalString as k,asString as a,loadSqliteDb as JY,nowIso as Yf}from"@cline/shared/db";import{resolveCronDbPath as WY}from"@cline/shared/storage";var $Y=[`CREATE TABLE IF NOT EXISTS cron_specs (
40
40
  spec_id TEXT PRIMARY KEY,
41
41
  external_id TEXT NOT NULL,
42
42
  source_path TEXT NOT NULL UNIQUE,
@@ -127,17 +127,17 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
127
127
  ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
128
128
  ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
129
129
  ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
130
- ON cron_specs(source_path);`];function O3(f){f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec("PRAGMA foreign_keys = ON;");for(let $ of kY)f.exec($)}function q4(f){if(!f)return;try{let $=JSON.parse(f);if($&&typeof $==="object"&&!Array.isArray($))return $}catch{}return}function FH(f,$={}){if(!f)return;try{let J=JSON.parse(f);if(!Array.isArray(J))return;let H=J.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0);if($.preserveEmpty)return H;return H.length>0?H:void 0}catch{return}}function B$(f){if(typeof f==="number"&&Number.isFinite(f))return f;if(typeof f==="bigint")return Number(f);return}function w0(f){return{specId:i(f.spec_id),externalId:i(f.external_id),sourcePath:i(f.source_path),triggerKind:i(f.trigger_kind),sourceMtimeMs:B$(f.source_mtime_ms),sourceHash:S(f.source_hash),parseStatus:i(f.parse_status)==="invalid"?"invalid":"valid",parseError:S(f.parse_error),enabled:Number(f.enabled??0)===1,removed:Number(f.removed??0)===1,title:i(f.title),prompt:S(f.prompt),workspaceRoot:S(f.workspace_root),scheduleExpr:S(f.schedule_expr),timezone:S(f.timezone),eventType:S(f.event_type),filters:q4(S(f.filters_json)),debounceSeconds:B$(f.debounce_seconds),dedupeWindowSeconds:B$(f.dedupe_window_seconds),cooldownSeconds:B$(f.cooldown_seconds),mode:S(f.mode),systemPrompt:S(f.system_prompt),providerId:S(f.provider_id),modelId:S(f.model_id),maxIterations:B$(f.max_iterations),timeoutSeconds:B$(f.timeout_seconds),maxParallel:B$(f.max_parallel),tools:FH(S(f.tools_json),{preserveEmpty:!0}),notesDirectory:S(f.notes_directory),extensions:FH(S(f.extensions_json),{preserveEmpty:!0}),source:S(f.source),tags:FH(S(f.tags_json)),metadata:q4(S(f.metadata_json)),revision:Number(f.revision??1),lastMaterializedRunId:S(f.last_materialized_run_id),lastRunAt:S(f.last_run_at),nextRunAt:S(f.next_run_at),createdAt:i(f.created_at),updatedAt:i(f.updated_at)}}function yH(f){return{runId:i(f.run_id),specId:i(f.spec_id),specRevision:Number(f.spec_revision??1),triggerKind:i(f.trigger_kind),status:i(f.status),claimToken:S(f.claim_token),claimStartedAt:S(f.claim_started_at),claimUntilAt:S(f.claim_until_at),scheduledFor:S(f.scheduled_for),triggerEventId:S(f.trigger_event_id),startedAt:S(f.started_at),completedAt:S(f.completed_at),sessionId:S(f.session_id),reportPath:S(f.report_path),error:S(f.error),attemptCount:Number(f.attempt_count??0),createdAt:i(f.created_at),updatedAt:i(f.updated_at)}}function N3(f){return{eventId:i(f.event_id),eventType:i(f.event_type),source:i(f.source),subject:S(f.subject),occurredAt:i(f.occurred_at),receivedAt:i(f.received_at),workspaceRoot:S(f.workspace_root),dedupeKey:S(f.dedupe_key),payload:q4(S(f.payload_json)),attributes:q4(S(f.attributes_json)),processingStatus:i(f.processing_status),matchedSpecCount:Number(f.matched_spec_count??0),queuedRunCount:Number(f.queued_run_count??0),suppressedCount:Number(f.suppressed_count??0),error:S(f.error),createdAt:i(f.created_at),updatedAt:i(f.updated_at)}}function q3(f){return f?JSON.stringify(f):null}var xY=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function b3(f){if(f===void 0)return null;if(f&&typeof f==="object")return JSON.stringify(f);return f}function gY(f,$,J,H){for(let W of xY){let Q=f[W],Z=$[W];if(b3(Q)!==b3(Z))return!0}if(J===!1&&H===!0)return!0;return!1}function vY(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function uY(f){return`hub/schedules/${f}.cron.md`}function cY(f){let $={...f.metadata??{},...f.createdBy?{__hubScheduleCreatedBy:f.createdBy}:{},...f.cwd?{__hubScheduleCwd:f.cwd}:{},...f.runtimeOptions?{__hubRuntimeOptions:f.runtimeOptions}:{}};return Object.keys($).length>0?$:void 0}function KH(f){return{triggerKind:"schedule",title:f.name.trim(),prompt:f.prompt,workspaceRoot:f.workspaceRoot.trim(),schedule:f.cronPattern.trim(),mode:f.mode??"act",systemPrompt:f.systemPrompt,modelSelection:f.modelSelection?JSON.parse(JSON.stringify(f.modelSelection)):void 0,maxIterations:typeof f.maxIterations==="number"?Math.floor(f.maxIterations):void 0,timeoutSeconds:typeof f.timeoutSeconds==="number"?Math.floor(f.timeoutSeconds):void 0,maxParallel:typeof f.maxParallel==="number"?Math.max(1,Math.floor(f.maxParallel)):1,source:"hub-schedule",tags:f.tags?.filter(($)=>$.trim().length>0),enabled:f.enabled!==!1,metadata:cY(f)}}function w3(f){return JSON.stringify(KH(f))}function dY(f,$){let J=f.metadata?{...f.metadata}:{},H=$.createdBy===null?void 0:$.createdBy!==void 0?$.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,W=$.cwd!==void 0?$.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,Q=$.runtimeOptions!==void 0?$.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:$.name??f.title,cronPattern:$.cronPattern??f.scheduleExpr??"",prompt:$.prompt??f.prompt??"",workspaceRoot:$.workspaceRoot??f.workspaceRoot??"",cwd:W,modelSelection:$.modelSelection!==void 0?$.modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:$.enabled??f.enabled,mode:$.mode??(f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"),systemPrompt:$.systemPrompt===null?void 0:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,maxIterations:$.maxIterations===null?void 0:$.maxIterations!==void 0?$.maxIterations:f.maxIterations,timeoutSeconds:$.timeoutSeconds===null?void 0:$.timeoutSeconds!==void 0?$.timeoutSeconds:f.timeoutSeconds,maxParallel:$.maxParallel??f.maxParallel??1,createdBy:H,tags:$.tags??f.tags,runtimeOptions:Q,metadata:$.metadata!==void 0?$.metadata:Object.keys(J).length>0?J:void 0}}class M2{db;constructor(f={}){let $=f.dbPath??IY();this.db=mY($),O3(this.db)}close(){this.db.close?.()}getSpecBySourcePath(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get(f);return $?w0($):void 0}getSpec(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f);return $?w0($):void 0}getSpecByExternalId(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get(f);return $?w0($):void 0}listSpecs(f={}){let $=[],J=[];if(f.triggerKind)$.push("trigger_kind = ?"),J.push(f.triggerKind);if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.parseStatus)$.push("parse_status = ?"),J.push(f.parseStatus);if(!f.includeRemoved)$.push("removed = 0");let H=$.length>0?`WHERE ${$.join(" AND ")}`:"",W=Math.max(1,Math.floor(f.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${H} ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Z)=>w0(Z))}createHubSchedule(f){let $=`sched_${D2()}`,J=this.upsertSpec({externalId:$,sourcePath:uY($),triggerKind:"schedule",sourceHash:w3(f),parseStatus:"valid",spec:KH(f)});this.initializeScheduleNextRun(J.record.specId);let H=this.getSpec(J.record.specId);if(!H)throw Error("failed to create hub schedule");return H}getHubSchedule(f){let $=this.db.prepare(`SELECT * FROM cron_specs
130
+ ON cron_specs(source_path);`];function g3(f){f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec("PRAGMA foreign_keys = ON;");for(let $ of $Y)f.exec($)}function k4(f){if(!f)return;try{let $=JSON.parse(f);if($&&typeof $==="object"&&!Array.isArray($))return $}catch{}return}function K5(f,$={}){if(!f)return;try{let J=JSON.parse(f);if(!Array.isArray(J))return;let W=J.map((H)=>typeof H==="string"?H.trim():"").filter((H)=>H.length>0);if($.preserveEmpty)return W;return W.length>0?W:void 0}catch{return}}function K$(f){if(typeof f==="number"&&Number.isFinite(f))return f;if(typeof f==="bigint")return Number(f);return}function m0(f){return{specId:a(f.spec_id),externalId:a(f.external_id),sourcePath:a(f.source_path),triggerKind:a(f.trigger_kind),sourceMtimeMs:K$(f.source_mtime_ms),sourceHash:k(f.source_hash),parseStatus:a(f.parse_status)==="invalid"?"invalid":"valid",parseError:k(f.parse_error),enabled:Number(f.enabled??0)===1,removed:Number(f.removed??0)===1,title:a(f.title),prompt:k(f.prompt),workspaceRoot:k(f.workspace_root),scheduleExpr:k(f.schedule_expr),timezone:k(f.timezone),eventType:k(f.event_type),filters:k4(k(f.filters_json)),debounceSeconds:K$(f.debounce_seconds),dedupeWindowSeconds:K$(f.dedupe_window_seconds),cooldownSeconds:K$(f.cooldown_seconds),mode:k(f.mode),systemPrompt:k(f.system_prompt),providerId:k(f.provider_id),modelId:k(f.model_id),maxIterations:K$(f.max_iterations),timeoutSeconds:K$(f.timeout_seconds),maxParallel:K$(f.max_parallel),tools:K5(k(f.tools_json),{preserveEmpty:!0}),notesDirectory:k(f.notes_directory),extensions:K5(k(f.extensions_json),{preserveEmpty:!0}),source:k(f.source),tags:K5(k(f.tags_json)),metadata:k4(k(f.metadata_json)),revision:Number(f.revision??1),lastMaterializedRunId:k(f.last_materialized_run_id),lastRunAt:k(f.last_run_at),nextRunAt:k(f.next_run_at),createdAt:a(f.created_at),updatedAt:a(f.updated_at)}}function y5(f){return{runId:a(f.run_id),specId:a(f.spec_id),specRevision:Number(f.spec_revision??1),triggerKind:a(f.trigger_kind),status:a(f.status),claimToken:k(f.claim_token),claimStartedAt:k(f.claim_started_at),claimUntilAt:k(f.claim_until_at),scheduledFor:k(f.scheduled_for),triggerEventId:k(f.trigger_event_id),startedAt:k(f.started_at),completedAt:k(f.completed_at),sessionId:k(f.session_id),reportPath:k(f.report_path),error:k(f.error),attemptCount:Number(f.attempt_count??0),createdAt:a(f.created_at),updatedAt:a(f.updated_at)}}function v3(f){return{eventId:a(f.event_id),eventType:a(f.event_type),source:a(f.source),subject:k(f.subject),occurredAt:a(f.occurred_at),receivedAt:a(f.received_at),workspaceRoot:k(f.workspace_root),dedupeKey:k(f.dedupe_key),payload:k4(k(f.payload_json)),attributes:k4(k(f.attributes_json)),processingStatus:a(f.processing_status),matchedSpecCount:Number(f.matched_spec_count??0),queuedRunCount:Number(f.queued_run_count??0),suppressedCount:Number(f.suppressed_count??0),error:k(f.error),createdAt:a(f.created_at),updatedAt:a(f.updated_at)}}function u3(f){return f?JSON.stringify(f):null}var HY=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function c3(f){if(f===void 0)return null;if(f&&typeof f==="object")return JSON.stringify(f);return f}function QY(f,$,J,W){for(let H of HY){let Q=f[H],Z=$[H];if(c3(Q)!==c3(Z))return!0}if(J===!1&&W===!0)return!0;return!1}function ZY(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function jY(f){return`hub/schedules/${f}.cron.md`}function XY(f){let $={...f.metadata??{},...f.createdBy?{__hubScheduleCreatedBy:f.createdBy}:{},...f.cwd?{__hubScheduleCwd:f.cwd}:{},...f.runtimeOptions?{__hubRuntimeOptions:f.runtimeOptions}:{}};return Object.keys($).length>0?$:void 0}function U5(f){return{triggerKind:"schedule",title:f.name.trim(),prompt:f.prompt,workspaceRoot:f.workspaceRoot.trim(),schedule:f.cronPattern.trim(),mode:f.mode??"act",systemPrompt:f.systemPrompt,modelSelection:f.modelSelection?JSON.parse(JSON.stringify(f.modelSelection)):void 0,maxIterations:typeof f.maxIterations==="number"?Math.floor(f.maxIterations):void 0,timeoutSeconds:typeof f.timeoutSeconds==="number"?Math.floor(f.timeoutSeconds):void 0,maxParallel:typeof f.maxParallel==="number"?Math.max(1,Math.floor(f.maxParallel)):1,source:"hub-schedule",tags:f.tags?.filter(($)=>$.trim().length>0),enabled:f.enabled!==!1,metadata:XY(f)}}function d3(f){return JSON.stringify(U5(f))}function AY(f,$){let J=f.metadata?{...f.metadata}:{},W=$.createdBy===null?void 0:$.createdBy!==void 0?$.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,H=$.cwd!==void 0?$.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,Q=$.runtimeOptions!==void 0?$.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:$.name??f.title,cronPattern:$.cronPattern??f.scheduleExpr??"",prompt:$.prompt??f.prompt??"",workspaceRoot:$.workspaceRoot??f.workspaceRoot??"",cwd:H,modelSelection:$.modelSelection!==void 0?$.modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:$.enabled??f.enabled,mode:$.mode??(f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"),systemPrompt:$.systemPrompt===null?void 0:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,maxIterations:$.maxIterations===null?void 0:$.maxIterations!==void 0?$.maxIterations:f.maxIterations,timeoutSeconds:$.timeoutSeconds===null?void 0:$.timeoutSeconds!==void 0?$.timeoutSeconds:f.timeoutSeconds,maxParallel:$.maxParallel??f.maxParallel??1,createdBy:W,tags:$.tags??f.tags,runtimeOptions:Q,metadata:$.metadata!==void 0?$.metadata:Object.keys(J).length>0?J:void 0}}class h2{db;constructor(f={}){let $=f.dbPath??WY();this.db=JY($),g3(this.db)}close(){this.db.close?.()}getSpecBySourcePath(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get(f);return $?m0($):void 0}getSpec(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f);return $?m0($):void 0}getSpecByExternalId(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get(f);return $?m0($):void 0}listSpecs(f={}){let $=[],J=[];if(f.triggerKind)$.push("trigger_kind = ?"),J.push(f.triggerKind);if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.parseStatus)$.push("parse_status = ?"),J.push(f.parseStatus);if(!f.includeRemoved)$.push("removed = 0");let W=$.length>0?`WHERE ${$.join(" AND ")}`:"",H=Math.max(1,Math.floor(f.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,H).map((Z)=>m0(Z))}createHubSchedule(f){let $=`sched_${L2()}`,J=this.upsertSpec({externalId:$,sourcePath:jY($),triggerKind:"schedule",sourceHash:d3(f),parseStatus:"valid",spec:U5(f)});this.initializeScheduleNextRun(J.record.specId);let W=this.getSpec(J.record.specId);if(!W)throw Error("failed to create hub schedule");return W}getHubSchedule(f){let $=this.db.prepare(`SELECT * FROM cron_specs
131
131
  WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
132
- ORDER BY created_at ASC LIMIT 1`).get(f);return $?w0($):void 0}listHubSchedules(f={}){let $=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.tags&&f.tags.length>0)for(let Q of f.tags)$.push("tags_json LIKE ?"),J.push(`%"${Q.trim()}"%`);let H=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
132
+ ORDER BY created_at ASC LIMIT 1`).get(f);return $?m0($):void 0}listHubSchedules(f={}){let $=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.tags&&f.tags.length>0)for(let Q of f.tags)$.push("tags_json LIKE ?"),J.push(`%"${Q.trim()}"%`);let W=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
133
133
  WHERE ${$.join(" AND ")}
134
- ORDER BY created_at DESC LIMIT ?`).all(...J,H).map((Q)=>w0(Q))}updateHubSchedule(f,$){let J=this.getHubSchedule(f);if(!J)return;let H=dY(J,$),W=this.upsertSpec({externalId:f,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:w3(H),parseStatus:"valid",spec:KH(H)});if($.cronPattern!==void 0||$.enabled!==void 0)this.initializeScheduleNextRun(W.record.specId);return this.getSpec(W.record.specId)}deleteHubSchedule(f){let $=this.getHubSchedule(f);if(!$)return!1;return this.markSpecRemoved($.specId),this.cancelQueuedRunsForSpec($.specId),!0}enqueueHubScheduleRun(f,$="manual"){let J=this.getHubSchedule(f);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:$,scheduledFor:jf()})}listEventSpecsForType(f){return this.db.prepare(`SELECT * FROM cron_specs
134
+ ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Q)=>m0(Q))}updateHubSchedule(f,$){let J=this.getHubSchedule(f);if(!J)return;let W=AY(J,$),H=this.upsertSpec({externalId:f,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:d3(W),parseStatus:"valid",spec:U5(W)});if($.cronPattern!==void 0||$.enabled!==void 0)this.initializeScheduleNextRun(H.record.specId);return this.getSpec(H.record.specId)}deleteHubSchedule(f){let $=this.getHubSchedule(f);if(!$)return!1;return this.markSpecRemoved($.specId),this.cancelQueuedRunsForSpec($.specId),!0}enqueueHubScheduleRun(f,$="manual"){let J=this.getHubSchedule(f);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:$,scheduledFor:Yf()})}listEventSpecsForType(f){return this.db.prepare(`SELECT * FROM cron_specs
135
135
  WHERE trigger_kind = 'event'
136
136
  AND event_type = ?
137
137
  AND enabled = 1
138
138
  AND removed = 0
139
139
  AND parse_status = 'valid'
140
- ORDER BY created_at ASC`).all(f).map((J)=>w0(J))}upsertSpec(f){let $=jf(),J=this.getSpecBySourcePath(f.sourcePath),H=f.spec,W={title:H?.title??J?.title??vY(f.sourcePath),prompt:H?.prompt,workspaceRoot:H?.workspaceRoot,scheduleExpr:H?.triggerKind==="schedule"?H.schedule:void 0,timezone:H?.triggerKind==="schedule"?H.timezone:void 0,eventType:H?.triggerKind==="event"?H.event:void 0,filters:H?.triggerKind==="event"?H.filters:void 0,debounceSeconds:H?.triggerKind==="event"?H.debounceSeconds:void 0,dedupeWindowSeconds:H?.triggerKind==="event"?H.dedupeWindowSeconds:void 0,cooldownSeconds:H?.triggerKind==="event"?H.cooldownSeconds:void 0,mode:H?.mode,systemPrompt:H?.systemPrompt,providerId:H?.modelSelection?.providerId,modelId:H?.modelSelection?.modelId,maxIterations:H?.maxIterations,timeoutSeconds:H?.timeoutSeconds,maxParallel:H&&"maxParallel"in H?H.maxParallel:void 0,tools:H?.tools,notesDirectory:H?.notesDirectory,extensions:H?.extensions,source:H?.source},Q=f.parseStatus==="valid"&&(H?.enabled??!0);if(!J){let V=`cspec_${D2()}`;this.insertSpecRow(V,f,W,Q,$);let Y=this.getSpec(V);if(!Y)throw Error("failed to insert cron_spec row");return{record:Y,created:!0,revisionChanged:!0}}let j=J.sourceHash!==f.sourceHash&&gY(J,W,J.enabled,Q),P=j?J.revision+1:J.revision;this.updateSpecRow(J.specId,f,W,Q,P,$);let X=this.getSpec(J.specId);if(!X)throw Error("failed to reload cron_spec after update");return{record:X,created:!1,revisionChanged:j}}insertSpecRow(f,$,J,H,W){let Q=$.spec;this.db.prepare(`INSERT INTO cron_specs (
140
+ ORDER BY created_at ASC`).all(f).map((J)=>m0(J))}upsertSpec(f){let $=Yf(),J=this.getSpecBySourcePath(f.sourcePath),W=f.spec,H={title:W?.title??J?.title??ZY(f.sourcePath),prompt:W?.prompt,workspaceRoot:W?.workspaceRoot,scheduleExpr:W?.triggerKind==="schedule"?W.schedule:void 0,timezone:W?.triggerKind==="schedule"?W.timezone:void 0,eventType:W?.triggerKind==="event"?W.event:void 0,filters:W?.triggerKind==="event"?W.filters:void 0,debounceSeconds:W?.triggerKind==="event"?W.debounceSeconds:void 0,dedupeWindowSeconds:W?.triggerKind==="event"?W.dedupeWindowSeconds:void 0,cooldownSeconds:W?.triggerKind==="event"?W.cooldownSeconds:void 0,mode:W?.mode,systemPrompt:W?.systemPrompt,providerId:W?.modelSelection?.providerId,modelId:W?.modelSelection?.modelId,maxIterations:W?.maxIterations,timeoutSeconds:W?.timeoutSeconds,maxParallel:W&&"maxParallel"in W?W.maxParallel:void 0,tools:W?.tools,notesDirectory:W?.notesDirectory,extensions:W?.extensions,source:W?.source},Q=f.parseStatus==="valid"&&(W?.enabled??!0);if(!J){let P=`cspec_${L2()}`;this.insertSpecRow(P,f,H,Q,$);let B=this.getSpec(P);if(!B)throw Error("failed to insert cron_spec row");return{record:B,created:!0,revisionChanged:!0}}let j=J.sourceHash!==f.sourceHash&&QY(J,H,J.enabled,Q),X=j?J.revision+1:J.revision;this.updateSpecRow(J.specId,f,H,Q,X,$);let A=this.getSpec(J.specId);if(!A)throw Error("failed to reload cron_spec after update");return{record:A,created:!1,revisionChanged:j}}insertSpecRow(f,$,J,W,H){let Q=$.spec;this.db.prepare(`INSERT INTO cron_specs (
141
141
  spec_id, external_id, source_path, trigger_kind,
142
142
  source_mtime_ms, source_hash, parse_status, parse_error,
143
143
  enabled, removed, title, prompt, workspace_root,
@@ -148,7 +148,7 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
148
148
  tools_json, notes_directory, extensions_json, source,
149
149
  tags_json, metadata_json, revision,
150
150
  created_at, updated_at
151
- ) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run(f,$.externalId,$.sourcePath,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,H?1:0,0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,Q?.tags?JSON.stringify(Q.tags):null,Q?.metadata?JSON.stringify(Q.metadata):null,1,W,W)}updateSpecRow(f,$,J,H,W,Q){let Z=$.spec;this.db.prepare(`UPDATE cron_specs SET
151
+ ) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run(f,$.externalId,$.sourcePath,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,W?1:0,0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,Q?.tags?JSON.stringify(Q.tags):null,Q?.metadata?JSON.stringify(Q.metadata):null,1,H,H)}updateSpecRow(f,$,J,W,H,Q){let Z=$.spec;this.db.prepare(`UPDATE cron_specs SET
152
152
  external_id = ?, trigger_kind = ?,
153
153
  source_mtime_ms = ?, source_hash = ?, parse_status = ?, parse_error = ?,
154
154
  enabled = ?, removed = 0, title = ?, prompt = ?,
@@ -160,31 +160,31 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
160
160
  tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
161
161
  tags_json = ?, metadata_json = ?,
162
162
  revision = ?, updated_at = ?
163
- WHERE spec_id = ?`).run($.externalId,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,H?1:0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,Z?.tags?JSON.stringify(Z.tags):null,Z?.metadata?JSON.stringify(Z.metadata):null,W,Q,f)}markSpecRemoved(f){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(jf(),f)}updateSpecNextRunAt(f,$){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run($??null,jf(),f)}updateSpecLastRunAt(f,$){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run($,jf(),f)}updateLastMaterializedRunId(f,$){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run($,jf(),f)}initializeScheduleNextRun(f){let $=this.getSpec(f);if(!$||$.triggerKind!=="schedule"||!$.enabled||!$.scheduleExpr){this.updateSpecNextRunAt(f,void 0);return}let J=new Date(Y$($.scheduleExpr,Date.now(),$.timezone)).toISOString();this.updateSpecNextRunAt(f,J)}materializeDueScheduleRun(f){let $=f.nowMs,J=new Date($).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let H=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f.specId);if(!H)return this.db.exec("COMMIT;"),{queued:!1};let W=w0(H);if(W.triggerKind!=="schedule"||!W.enabled||W.removed||W.parseStatus!=="valid"||!W.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let Q=W.nextRunAt;if(!Q){let P=new Date(Y$(W.scheduleExpr,$,W.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(P,J,W.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:P}}if(new Date(Q).getTime()>$)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:Q};let Z=`crun_${D2()}`,j;try{j=new Date(Y$(W.scheduleExpr,$,W.timezone)).toISOString()}catch{j=void 0}return this.db.prepare(`INSERT INTO cron_runs (
163
+ WHERE spec_id = ?`).run($.externalId,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,W?1:0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,Z?.tags?JSON.stringify(Z.tags):null,Z?.metadata?JSON.stringify(Z.metadata):null,H,Q,f)}markSpecRemoved(f){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(Yf(),f)}updateSpecNextRunAt(f,$){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run($??null,Yf(),f)}updateSpecLastRunAt(f,$){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run($,Yf(),f)}updateLastMaterializedRunId(f,$){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run($,Yf(),f)}initializeScheduleNextRun(f){let $=this.getSpec(f);if(!$||$.triggerKind!=="schedule"||!$.enabled||!$.scheduleExpr){this.updateSpecNextRunAt(f,void 0);return}let J=new Date(F$($.scheduleExpr,Date.now(),$.timezone)).toISOString();this.updateSpecNextRunAt(f,J)}materializeDueScheduleRun(f){let $=f.nowMs,J=new Date($).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f.specId);if(!W)return this.db.exec("COMMIT;"),{queued:!1};let H=m0(W);if(H.triggerKind!=="schedule"||!H.enabled||H.removed||H.parseStatus!=="valid"||!H.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let Q=H.nextRunAt;if(!Q){let X=new Date(F$(H.scheduleExpr,$,H.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(X,J,H.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:X}}if(new Date(Q).getTime()>$)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:Q};let Z=`crun_${L2()}`,j;try{j=new Date(F$(H.scheduleExpr,$,H.timezone)).toISOString()}catch{j=void 0}return this.db.prepare(`INSERT INTO cron_runs (
164
164
  run_id, spec_id, spec_revision, trigger_kind, status,
165
165
  scheduled_for, trigger_event_id, attempt_count,
166
166
  created_at, updated_at
167
- ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(Z,W.specId,W.revision,"schedule","queued",Q,null,0,J,J),this.db.prepare(`UPDATE cron_specs SET
167
+ ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(Z,H.specId,H.revision,"schedule","queued",Q,null,0,J,J),this.db.prepare(`UPDATE cron_specs SET
168
168
  last_materialized_run_id = ?,
169
169
  last_run_at = ?,
170
170
  next_run_at = ?,
171
171
  updated_at = ?
172
- WHERE spec_id = ?`).run(Z,J,j??null,J,W.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(Z),nextRunAt:j}}catch(H){throw this.db.exec("ROLLBACK;"),H}}getRun(f){let $=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get(f);return $?yH($):void 0}insertEventLog(f,$={}){let J=jf(),H=$.receivedAtIso??J,W=f.eventId.trim();if(!W)throw Error("automation event requires eventId");let Q=f.eventType.trim();if(!Q)throw Error("automation event requires eventType");let Z=f.source.trim();if(!Z)throw Error("automation event requires source");let j=f.occurredAt.trim()||H,P=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
172
+ WHERE spec_id = ?`).run(Z,J,j??null,J,H.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(Z),nextRunAt:j}}catch(W){throw this.db.exec("ROLLBACK;"),W}}getRun(f){let $=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get(f);return $?y5($):void 0}insertEventLog(f,$={}){let J=Yf(),W=$.receivedAtIso??J,H=f.eventId.trim();if(!H)throw Error("automation event requires eventId");let Q=f.eventType.trim();if(!Q)throw Error("automation event requires eventType");let Z=f.source.trim();if(!Z)throw Error("automation event requires source");let j=f.occurredAt.trim()||W,X=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
173
173
  event_id, event_type, source, subject,
174
174
  occurred_at, received_at, workspace_root, dedupe_key,
175
175
  payload_json, attributes_json, processing_status,
176
176
  matched_spec_count, queued_run_count, suppressed_count,
177
177
  error, created_at, updated_at
178
- ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(W,Q,Z,f.subject?.trim()||null,j,H,f.workspaceRoot?.trim()||null,f.dedupeKey?.trim()||null,q3(f.payload),q3(f.attributes),"received",0,0,0,null,J,J).changes??0,X=this.getEventLog(W);if(!X)throw Error("failed to insert cron_event_log row");return{record:X,created:P===1}}getEventLog(f){let $=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get(f);return $?N3($):void 0}listEventLogs(f={}){let $=[],J=[];if(f.eventType)$.push("event_type = ?"),J.push(f.eventType);if(f.source)$.push("source = ?"),J.push(f.source);if(f.processingStatus)$.push("processing_status = ?"),J.push(f.processingStatus);let H=$.length>0?`WHERE ${$.join(" AND ")}`:"",W=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${H}
178
+ ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(H,Q,Z,f.subject?.trim()||null,j,W,f.workspaceRoot?.trim()||null,f.dedupeKey?.trim()||null,u3(f.payload),u3(f.attributes),"received",0,0,0,null,J,J).changes??0,A=this.getEventLog(H);if(!A)throw Error("failed to insert cron_event_log row");return{record:A,created:X===1}}getEventLog(f){let $=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get(f);return $?v3($):void 0}listEventLogs(f={}){let $=[],J=[];if(f.eventType)$.push("event_type = ?"),J.push(f.eventType);if(f.source)$.push("source = ?"),J.push(f.source);if(f.processingStatus)$.push("processing_status = ?"),J.push(f.processingStatus);let W=$.length>0?`WHERE ${$.join(" AND ")}`:"",H=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${W}
179
179
  ORDER BY received_at DESC, created_at DESC
180
- LIMIT ?`).all(...J,W).map((Z)=>N3(Z))}updateEventLogProcessing(f,$){return(this.db.prepare(`UPDATE cron_event_log SET
180
+ LIMIT ?`).all(...J,H).map((Z)=>v3(Z))}updateEventLogProcessing(f,$){return(this.db.prepare(`UPDATE cron_event_log SET
181
181
  processing_status = ?,
182
182
  matched_spec_count = COALESCE(?, matched_spec_count),
183
183
  queued_run_count = COALESCE(?, queued_run_count),
184
184
  suppressed_count = COALESCE(?, suppressed_count),
185
185
  error = ?,
186
186
  updated_at = ?
187
- WHERE event_id = ?`).run($.status,$.matchedSpecCount??null,$.queuedRunCount??null,$.suppressedCount??null,$.error??null,jf(),f).changes??0)===1}listRuns(f={}){let $=[],J=[];if(f.specId)$.push("spec_id = ?"),J.push(f.specId);if(f.status){let Z=Array.isArray(f.status)?f.status:[f.status];if(Z.length>0){let j=Z.map(()=>"?").join(",");$.push(`status IN (${j})`);for(let P of Z)J.push(P)}}let H=$.length>0?`WHERE ${$.join(" AND ")}`:"",W=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${H} ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Z)=>yH(Z))}hasRecentEventRunForDedupe(f){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
187
+ WHERE event_id = ?`).run($.status,$.matchedSpecCount??null,$.queuedRunCount??null,$.suppressedCount??null,$.error??null,Yf(),f).changes??0)===1}listRuns(f={}){let $=[],J=[];if(f.specId)$.push("spec_id = ?"),J.push(f.specId);if(f.status){let Z=Array.isArray(f.status)?f.status:[f.status];if(Z.length>0){let j=Z.map(()=>"?").join(",");$.push(`status IN (${j})`);for(let X of Z)J.push(X)}}let W=$.length>0?`WHERE ${$.join(" AND ")}`:"",H=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,H).map((Z)=>y5(Z))}hasRecentEventRunForDedupe(f){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
188
188
  INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
189
189
  WHERE r.spec_id = ?
190
190
  AND r.trigger_kind = 'event'
@@ -202,7 +202,7 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
202
202
  AND r.status = 'queued'
203
203
  AND e.dedupe_key = ?
204
204
  ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
205
- LIMIT 1`).get(f.specId,f.dedupeKey);return $?yH($):void 0}updateQueuedEventRunForDebounce(f){let $=jf();if((this.db.prepare(`UPDATE cron_runs SET
205
+ LIMIT 1`).get(f.specId,f.dedupeKey);return $?y5($):void 0}updateQueuedEventRunForDebounce(f){let $=Yf();if((this.db.prepare(`UPDATE cron_runs SET
206
206
  trigger_event_id = ?,
207
207
  scheduled_for = ?,
208
208
  updated_at = ?
@@ -211,12 +211,12 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
211
211
  AND status = 'queued'`).run(f.triggerEventId,f.scheduledFor,$,f.runId).changes??0)!==1)return;return this.getRun(f.runId)}hasOneOffRunForRevision(f,$){return!!this.db.prepare(`SELECT run_id FROM cron_runs
212
212
  WHERE spec_id = ? AND spec_revision = ?
213
213
  AND trigger_kind = 'one_off'
214
- LIMIT 1`).get(f,$)}enqueueRun(f){let $=`crun_${D2()}`,J=jf();this.db.prepare(`INSERT INTO cron_runs (
214
+ LIMIT 1`).get(f,$)}enqueueRun(f){let $=`crun_${L2()}`,J=Yf();this.db.prepare(`INSERT INTO cron_runs (
215
215
  run_id, spec_id, spec_revision, trigger_kind, status,
216
216
  scheduled_for, trigger_event_id, attempt_count,
217
217
  created_at, updated_at
218
- ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run($,f.specId,f.specRevision,f.triggerKind,"queued",f.scheduledFor??null,f.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId(f.specId,$);let H=this.getRun($);if(!H)throw Error("failed to insert cron_run row");return H}cancelQueuedRunsForSpec(f){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
219
- WHERE spec_id = ? AND status = 'queued'`).run(jf(),f).changes??0}claimDueRuns(f){let $=f.nowIso,J=Math.max(1000,Math.floor(f.leaseMs)),H=new Date(new Date($).getTime()+J).toISOString(),W=Math.max(1,Math.floor(f.limit??25)),Q=[];this.db.exec("BEGIN IMMEDIATE;");try{let Z=this.db.prepare(`SELECT * FROM cron_runs
218
+ ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run($,f.specId,f.specRevision,f.triggerKind,"queued",f.scheduledFor??null,f.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId(f.specId,$);let W=this.getRun($);if(!W)throw Error("failed to insert cron_run row");return W}cancelQueuedRunsForSpec(f){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
219
+ WHERE spec_id = ? AND status = 'queued'`).run(Yf(),f).changes??0}claimDueRuns(f){let $=f.nowIso,J=Math.max(1000,Math.floor(f.leaseMs)),W=new Date(new Date($).getTime()+J).toISOString(),H=Math.max(1,Math.floor(f.limit??25)),Q=[];this.db.exec("BEGIN IMMEDIATE;");try{let Z=this.db.prepare(`SELECT * FROM cron_runs
220
220
  WHERE (
221
221
  status = 'queued'
222
222
  OR (
@@ -228,7 +228,7 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
228
228
  )
229
229
  AND (scheduled_for IS NULL OR scheduled_for <= ?)
230
230
  ORDER BY COALESCE(scheduled_for, created_at) ASC
231
- LIMIT ?`).all($,$,W);for(let j of Z){let P=i(j.run_id);if(!P)continue;let X=`cclaim_${D2()}`;if((this.db.prepare(`UPDATE cron_runs SET
231
+ LIMIT ?`).all($,$,H);for(let j of Z){let X=a(j.run_id);if(!X)continue;let A=`cclaim_${L2()}`;if((this.db.prepare(`UPDATE cron_runs SET
232
232
  status = 'running',
233
233
  claim_token = ?,
234
234
  claim_started_at = ?,
@@ -249,8 +249,8 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
249
249
  AND claim_until_at <= ?
250
250
  AND completed_at IS NULL
251
251
  )
252
- )`).run(X,$,H,$,$,P,$).changes??0)!==1)continue;let Y=this.getRun(P);if(!Y)continue;Q.push({run:Y,claimToken:X,claimUntilAt:H})}this.db.exec("COMMIT;")}catch(Z){throw this.db.exec("ROLLBACK;"),Z}return Q}renewClaim(f,$,J){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
253
- WHERE run_id = ? AND claim_token = ?`).run(J,jf(),f,$).changes??0)===1}completeRun(f,$){let J=$.completedAtIso??jf(),H=$.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
252
+ )`).run(A,$,W,$,$,X,$).changes??0)!==1)continue;let B=this.getRun(X);if(!B)continue;Q.push({run:B,claimToken:A,claimUntilAt:W})}this.db.exec("COMMIT;")}catch(Z){throw this.db.exec("ROLLBACK;"),Z}return Q}renewClaim(f,$,J){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
253
+ WHERE run_id = ? AND claim_token = ?`).run(J,Yf(),f,$).changes??0)===1}completeRun(f,$){let J=$.completedAtIso??Yf(),W=$.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
254
254
  status = ?,
255
255
  session_id = COALESCE(?, session_id),
256
256
  report_path = COALESCE(?, report_path),
@@ -260,7 +260,7 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
260
260
  claim_token = NULL,
261
261
  claim_until_at = NULL,
262
262
  updated_at = ?
263
- ${H}`).run($.status,$.sessionId??null,$.reportPath??null,$.error??null,J,J,f,...$.claimToken?[$.claimToken]:[]).changes??0)>0}requeueRun(f){let $=jf();return(this.db.prepare(`UPDATE cron_runs SET
263
+ ${W}`).run($.status,$.sessionId??null,$.reportPath??null,$.error??null,J,J,f,...$.claimToken?[$.claimToken]:[]).changes??0)>0}requeueRun(f){let $=Yf();return(this.db.prepare(`UPDATE cron_runs SET
264
264
  status = 'queued',
265
265
  claim_started_at = NULL,
266
266
  claim_token = NULL,
@@ -272,24 +272,24 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
272
272
  error = ?,
273
273
  scheduled_for = COALESCE(?, scheduled_for),
274
274
  updated_at = ?
275
- WHERE run_id = ? AND claim_token = ?`).run(f.error??null,f.scheduledFor??null,$,f.runId,f.claimToken).changes??0)>0}attachSessionIdToRun(f,$){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run($,jf(),f)}attachReportPathToRun(f,$){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run($,jf(),f)}}function w4(f){return f?new Date(f).getTime():void 0}function rY(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function b4(f){let $=f.metadata;return{scheduleId:f.externalId,name:f.title,cronPattern:f.scheduleExpr??"",prompt:f.prompt??"",workspaceRoot:f.workspaceRoot??"",cwd:typeof $?.__hubScheduleCwd==="string"?$.__hubScheduleCwd:void 0,modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:f.enabled&&!f.removed&&f.parseStatus==="valid",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,maxParallel:f.maxParallel??1,createdAt:new Date(f.createdAt).getTime(),updatedAt:new Date(f.updatedAt).getTime(),nextRunAt:w4(f.nextRunAt),lastRunAt:w4(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:rY(f)}}function lY(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function C3(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:w4(f.startedAt),endedAt:w4(f.completedAt),status:lY(f.status),errorMessage:f.error}}class Q1{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new M2({dbPath:f.dbPath}),this.materializer=new y2({store:this.store}),this.runner=new G2({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:"",logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule(f){if(RH(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return b4(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?b4($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>b4($))}updateSchedule(f,$){if($.cronPattern!==void 0)RH($.cronPattern);let J=this.store.getHubSchedule(f);if(!J)return;let H=$.workspaceRoot!==void 0?$.workspaceRoot.trim():J.workspaceRoot;if(($.enabled??J.enabled)&&!H)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule(f,{...$,scheduleId:f});return Q?b4(Q):void 0}deleteSchedule(f){return this.store.deleteHubSchedule(f)}pauseSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!1})}resumeSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!0})}async triggerScheduleNow(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;await this.runner.tick();let J=this.store.getRun($.runId)??$;return C3(J,f)}listScheduleExecutions(f){let $=f.scheduleId?this.store.getHubSchedule(f.scheduleId):void 0,J={specId:$?.specId,limit:f.limit};return this.store.listRuns(J).map((W)=>{let Q=$??this.store.getSpec(W.specId);if(!Q||Q.source!=="hub-schedule")return;return C3(W,Q.externalId)}).filter((W)=>{if(!W)return!1;return!f.status||W.status===f.status})}getScheduleStats(f){let $=this.listScheduleExecutions({scheduleId:f,limit:1e4});if($.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,H=0,W=0,Q;for(let Z of $){if(Z.status==="success"||Z.status==="completed")J+=1;if(!Q&&Z.status!=="success"&&Z.status!=="completed")Q=Z;if(Z.startedAt&&Z.endedAt)W+=Z.endedAt-Z.startedAt,H+=1}return{totalRuns:$.length,successRate:J/$.length,avgDurationSeconds:H>0?W/H/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((f)=>{let $=this.store.getSpec(f.specId);if(!$||$.source!=="hub-schedule"||!f.sessionId)return[];return[{executionId:f.runId,scheduleId:$.externalId,sessionId:f.sessionId,startedAt:f.startedAt??new Date().toISOString(),timeoutAt:$.timeoutSeconds&&f.startedAt?new Date(new Date(f.startedAt).getTime()+$.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(f=20){let $={triggerKind:"schedule",enabled:!0,limit:f};return this.store.listSpecs($).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,H)=>String(J.nextRunAt).localeCompare(String(H.nextRunAt))).slice(0,f).map(({spec:J,nextRunAt:H})=>({scheduleId:J.externalId,name:J.title,nextRunAt:H}))}}o4();import{createSessionId as GA,resolveHubCommandTimeoutMs as hA}from"@cline/shared";import{spawn as eB}from"node:child_process";import{closeSync as fA,mkdirSync as $A,openSync as JA}from"node:fs";import{basename as HA,dirname as WA,join as QA}from"node:path";import{fileURLToPath as ZA}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as jA,isHubDaemonProcess as Z7,withResolvedClineBuildEnv as PA}from"@cline/shared";import{createHash as CB,randomBytes as EB}from"node:crypto";import{existsSync as SB}from"node:fs";import{chmod as kB,mkdir as DH,readFile as o3,rm as MH,writeFile as e3}from"node:fs/promises";import{dirname as f7,join as _H}from"node:path";import{resolveClineDataDir as S2,resolveClineDir as $7}from"@cline/shared/storage";var n3="0.0.38";var a3={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:n3,repository:{type:"git",url:"https://github.com/cline/sdk",directory:"packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{development:"./src/index.ts",types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{development:"./src/hub/index.ts",types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{development:"./src/hub/daemon/entry.ts",types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{development:"./src/services/telemetry/index.ts",types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"rm -rf dist && bun run ./bun.mts && bun tsc -p tsconfig.build.json",clean:"rm -rf dist node_modules",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: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:*","@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:"^1.21.7","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"^3.32.3",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var mB="CLINE_HUB_DISCOVERY_PATH",IB="CLINE_HUB_BUILD_ID",t3=30000,xB=15000,gB=100;function vB(f){return f.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function uB(f){return CB("sha256").update(f).digest("hex").slice(0,12)}function cB(f){if(!Number.isInteger(f)||!f||f<=0)return!1;try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function e4(){return EB(32).toString("hex")}function dB(f){return new Promise(($)=>setTimeout($,f))}function rB(f){return`${f}.lock`}async function lB(f){try{let $=JSON.parse(await o3(_H(f,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function s3(f){await MH(f,{recursive:!0,force:!0}).catch(()=>{return})}function S0(){return process.env[IB]?.trim()||String(a3.version)}function y0(f=process.argv[1]?.trim()||process.cwd()){let $=`hub-${uB(f)}`,J=process.env[mB]?.trim()||_H(S2(),"locks","hub","owners",`${vB($)}.json`);return{ownerId:$,discoveryPath:J}}function J7(f=`hub-${Date.now().toString(36)}`){return y0(f)}async function Qf(f){try{let $=JSON.parse(await o3(f,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,buildId:typeof $.buildId==="string"?$.buildId:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function f6(f,$){await DH(f7(f),{recursive:!0}),await MH(f,{force:!0}).catch(()=>{return}),await e3(f,`${JSON.stringify($,null,2)}
276
- `,{encoding:"utf8",mode:384}),await kB(f,384)}async function zf(f){await MH(f,{force:!0}).catch(()=>{return})}async function $6(f,$){let J=rB(f);await DH(f7(J),{recursive:!0});let H=Date.now()+xB;while(!0)try{await DH(J,{recursive:!1}),await e3(_H(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
277
- `,"utf8");try{return await $()}finally{await s3(J)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let Z=await lB(J),j=Z?Date.now()-Date.parse(Z.acquiredAt):t3+1;if(!Z||!cB(Z.pid)||j>t3){await s3(J);continue}if(Date.now()>=H)throw Error(`Timed out waiting for hub startup lock ${J}`);await dB(gB)}}async function Pf(f){try{let $=await fetch(LH(f));if(!$.ok)return;return await $.json()}catch{return}}function cf(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function LH(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function H7(f){return SB(f)}import{CLINE_HUB_DEV_PORT as pB,CLINE_HUB_PORT as iB,resolveClineBuildEnv as nB}from"@cline/shared";var aB="CLINE_HUB_HOST",tB="CLINE_HUB_PORT",sB="CLINE_HUB_PATHNAME",zH="127.0.0.1",OH=iB,NH="/hub";function W7(f){return nB(f)==="development"?pB:OH}function qH(f={}){return(f.env??process.env)[aB]?.trim()||zH}function V1(f={}){let J=(f.env??process.env)[tB]?.trim();if(!J)return W7(f);let H=Number.parseInt(J,10);if(!Number.isInteger(H)||H<1||H>65535)return W7(f);return H}function bH(f={}){return(f.env??process.env)[sB]?.trim()||NH}function tf(f={},$={}){return{host:f.host??qH($),port:f.port??V1($),pathname:f.pathname??bH($)}}var oB="shared:cline";function Q7(f){let $=V0(f.trim());return y0(`workspace:${$||f.trim()}`)}function Xf(f=oB){return y0(f)}var XA=8000,VA=200,YA=3000,BA=100,AA="--cline-hub-daemon";function RA(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function FA(){try{let f=QA(S2(),"logs","hub-daemon.log");return $A(WA(f),{recursive:!0}),{fd:JA(f,"a"),logPath:f}}catch{return}}function k2(f){let $=f.buildId?.trim();return!!$&&$===S0()}async function yA(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await Pf(f).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,BA))}return!1}async function m2(f,$){if(k2(f))return;if(await I2(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await yA(f.url,YA),await zf($).catch(()=>{return})}function KA(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return ZA(new URL(`./entry.${f}`,import.meta.url))}function UA(f,$){let J=KA(),H=process.execPath?.trim();if(!H)throw Error("unable to resolve runtime executable for hub daemon");let W=HA(H).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),Z=W&&J.toLowerCase().endsWith(".ts"),j=Q?[AA]:[...Z?["--conditions=development"]:[],J];return{launcher:H,args:[...j,"--cwd",f,...RA($)],cwd:f,env:{...PA(process.env),CLINE_NO_INTERACTIVE:"1",[jA]:"1"}}}function Y1(f,$={}){if(Z7())return;let J=UA(f,$),H=FA();try{eB(J.launcher,J.args,{detached:!0,stdio:H?["ignore",H.fd,H.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(H)fA(H.fd)}}function J6(f,$={}){if(Z7())return;let J=Xf(),H=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=tf($),Q=cf(W.host,W.port,W.pathname);Qf(J.discoveryPath).then(async(Z)=>{if(Z?.url){let V=await Pf(Z.url);if(V?.url&&k2(V)&&await sf(V.url,{authToken:Z.authToken}))return;if(V?.url)await m2({...V,authToken:Z.authToken},J.discoveryPath);else await zf(J.discoveryPath).catch(()=>{return})}let j=await Pf(Q);if(j?.url)await m2(j,J.discoveryPath);let X=!H&&W.port!==0?{...W,port:0}:W;Y1(f,X)}).catch(()=>{})}async function j7(f,$={}){let J=Xf(),H=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=tf($),Z=cf(Q.host,Q.port,Q.pathname),j=(A)=>{if(!H)k0(A.url,A.authToken);return A},P=await Qf(J.discoveryPath);if(P?.url){let A=await Pf(P.url);if(A?.url&&k2(A)&&await sf(A.url,{authToken:P.authToken}))return j({url:A.url,authToken:P.authToken});if(A?.url)await m2({...A,authToken:P.authToken},J.discoveryPath);else await zf(J.discoveryPath).catch(()=>{return})}let X=await Pf(Z);if(X?.url)await m2(X,J.discoveryPath);let Y=!W&&Q.port!==0?{...Q,port:0}:Q;Y1(f,Y);let B=Date.now()+XA;while(Date.now()<B){let A=await Qf(J.discoveryPath);if(A?.url){let U=await Pf(A.url);if(U?.url&&k2(U)&&await sf(U.url,{authToken:A.authToken}))return j({url:U.url,authToken:A.authToken})}let R=await Pf(Z);if(R?.url&&!k2(R))await m2(R,J.discoveryPath);await new Promise((U)=>setTimeout(U,VA))}throw Error("Timed out waiting for detached hub startup.")}function TA(){let f=globalThis.WebSocket;if(!f)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return f}function B7(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();if(f&&typeof f==="object"&&"data"in f&&typeof f.data<"u")return B7(f.data);return String(f)}function DA(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString("utf8");if(f instanceof ArrayBuffer)return Buffer.from(f).toString("utf8");return""}function P7(f){let $=f,J=DA($.reason);return new Rf("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:wH,{closeCode:$.code,closeReason:J||void 0})}function MA(f,$){if(f instanceof Rf)return f;if(f instanceof Error)return new Rf("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new Rf("hub_connect_failed",f.error.message);let J=f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"?f.message.trim():"";if(J)return new Rf("hub_connect_failed",J);let H=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new Rf("hub_connect_failed",H?`Failed to connect to hub at ${$.toString()} (${H} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var _A=8000,LA=200,X7="*",V7=8000,zA="cline-hub-auth.",A7=new Map,R7=new Set,OA=3000,NA=3000,qA=100,wH="Hub connection closed",bA=250,wA=5000,Y7=0.5;class Rf extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function SH(f){return f instanceof Rf}class B1 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function H6(f,$){return f instanceof B1&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function F7(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=kH(f.toString());return J?A7.get(J):void 0}function CA(f){try{let J=new URL(f).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function kH(f){if(!CA(f))return;let $=new URL(m0(f));return $.search="",$.hash="",$.toString()}function CH(f){let $=kH(f);return!!$&&R7.has($)}function k0(f,$){let J=kH(f);if(J){if(R7.add(J),$?.trim())A7.set(J,$)}return f}class df{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new Rf("hub_connection_closed",wH);sawSocketClose=!1;registered=!1;constructor(f){this.options=f;this.clientId=f.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=f.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let f=new URL(this.currentUrl),$=this.options.authToken?.trim()||F7(f);f.hash="";let H=new(TA())(f.toString(),$?[`${zA}${$}`]:void 0);this.socket=H;let W=!1;this.connectPromise=new Promise((Q,Z)=>{let j=!1,P=setTimeout(()=>{if(j)return;j=!0,W=!0,this.lastCloseError=new Rf("hub_connect_timeout",`Timed out connecting to hub after ${V7}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{H.close()}catch{}Z(this.lastCloseError)},V7);H.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(P),Q()}),H.addEventListener("error",(X)=>{if(j)return;j=!0,clearTimeout(P),this.lastCloseError=MA(X,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)}),H.addEventListener("close",(X)=>{if(j)return;if(j=!0,clearTimeout(P),!W)this.lastCloseError=P7(X),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)})}),H.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(B7(Q)))}),H.addEventListener("close",(Q)=>{if(this.socket!==H)return;if(!W)this.lastCloseError=P7(Q),this.sawSocketClose=!0;this.registered=!1;for(let Z of this.pendingReplies.values())Z.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe(f,$){let J=$?.sessionId?.trim()||void 0,H={listener:f,sessionId:J};return this.listeners.add(H),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(H))return;this.adjustSubscriptionCount(J,-1)}}async command(f,$,J,H){let W=0,Q=f!=="client.register"&&f!=="client.unregister";while(!0)try{return await this.commandOnce(f,$,J,H)}catch(Z){if(!Q||W>=1||!await this.recoverLocalHubTransport(Z))throw Z;W+=1}}async commandOnce(f,$,J,H){await this.connect();let W=GA("hubreq_"),Q=hA(f,H?.timeoutMs),Z=new Promise((P,X)=>{let V=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;X(new B1(f,"hub_command_timeout",`Hub command ${f} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${W}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(W,{resolve:(Y)=>{if(V)clearTimeout(V);P(Y)},reject:(Y)=>{if(V)clearTimeout(V);X(Y)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:f,requestId:W,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:$}})}catch(P){throw this.pendingReplies.delete(W),P}let j=await Z;if(!j.ok)throw new B1(f,j.error?.code,j.error?.message??`Hub command ${f} failed`);return j}async recoverLocalHubTransport(f){if(!CH(this.currentUrl)||!SH(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await K$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let f=Math.min(bA*2**this.reconnectAttempt,wA),$=Math.round(f*(1-Y7)+Math.random()*f*Y7);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!CH(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await K$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(f){this.currentUrl=f,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let f=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!f)return;this.lastCloseError=new Rf("hub_connection_closed",wH),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{f.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(f){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new Rf("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(f))}sendSubscriptionFrame(f,$){this.sendFrame({kind:f,clientId:this.clientId,...$?{sessionId:$}:{}})}adjustSubscriptionCount(f,$){let J=this.subscriptionKeyForSessionId(f),H=(this.subscriptionCounts.get(J)??0)+$;if(H<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",f);return}if(this.subscriptionCounts.set(J,H),$>0&&H===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",f)}subscriptionKeyForSessionId(f){return f??X7}subscriptionSessionIdFromKey(f){return f===X7?void 0:f}handleFrame(f){switch(f.kind){case"reply":{let $=f.envelope.requestId;if(!$)return;let J=this.pendingReplies.get($);if(!J)return;this.pendingReplies.delete($),J.resolve(f.envelope);return}case"event":for(let $ of this.listeners){if($.sessionId&&$.sessionId!==f.envelope.sessionId?.trim())continue;$.listener(f.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function m0(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function sf(f,$){let J=new df({url:f,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function EH(f,$){let J=m0(f),H=await Pf(J);if(!H)return{status:"unreachable",url:J};let W=S0(),Q=H.buildId?.trim();if(!Q||Q!==W)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await sf(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function EA(f){let $=Date.now()+_A;while(Date.now()<$){let J=await Qf(f.discoveryPath);if(J?.url){let H=await EH(J.url,{verifyConnection:!0,authToken:J.authToken});if(H.status==="compatible")return k0(H.url,J.authToken)}await new Promise((H)=>setTimeout(H,LA))}return}async function SA(f){let $=Date.now()+NA;while(Date.now()<$){if(!(await Pf(f).catch(()=>{return}))?.url)return!0;await new Promise((H)=>setTimeout(H,qA))}return!1}function kA(f,$){try{return m0(f)===m0($)}catch{return!1}}function mA(f){return(f&&typeof f==="object"&&Array.isArray(f.sessions)?f.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let H=J;if(H.status==="running"||H.status==="idle")return!0;return Array.isArray(H.participants)&&H.participants.length>0})}async function IA(f,$,J){let H=new df({url:f,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let W=await H.command("session.list",{limit:500},void 0,{timeoutMs:OA});return!mA(W.payload)}catch{return!1}finally{await H.dispose().catch(()=>{return})}}async function x2(f={}){if(f.endpoint?.trim()){let W=await EH(f.endpoint);return W.status==="compatible"?W.url:void 0}let $=Xf(),J=await Qf($.discoveryPath);if(!J?.url)return;let H=await EH(J.url);if(H.status==="compatible")return k0(H.url,J.authToken);if(H.status==="build_mismatch")await zf($.discoveryPath).catch(()=>{return});return}async function K$(f={}){let $=await x2(f);if($&&await sf($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=Xf();return Y1(f.workspaceRoot??process.cwd()),await EA(J)}async function I2(f,$){let J=new URL(f),H=$?.trim()||F7(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:H?{authorization:`Bearer ${H}`}:void 0})).ok}async function mH(){let f=Xf(),$=await Qf(f.discoveryPath);if(!$?.url)return!1;try{if(await I2($.url,$.authToken))return!0}catch{}return!1}async function W6(f){if(!CH(f.url))return;let $=Xf(),J=await Qf($.discoveryPath);if(!J?.url||!kA(J.url,f.url))return;if(!await IA(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await mH())return;if(!await SA(J.url))return;return await zf($.discoveryPath).catch(()=>{return}),await K$({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}function xA(f,$){if(f instanceof Error)return f;if(f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"&&f.message.trim())return Error(f.message.trim());let J=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return Error(J?`Failed to connect to hub at ${$} (${J} event before socket open).`:`Failed to connect to hub at ${$}.`)}var gA="cline-hub-auth.";function vA(f){return f.host!==void 0||f.port!==void 0||f.pathname!==void 0}function uA(f,$){let J=new URL(f),H=new URL($);return J.search="",J.hash="",H.search="",H.hash="",J.toString()===H.toString()}async function cA(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=Xf(),H=await Qf(J.discoveryPath);if(H?.url&&uA(f.toString(),H.url))return H.authToken;return}async function IH(f={}){let $=tf(f);if(!vA(f)){let J=Xf(),H=await Qf(J.discoveryPath);if(H?.url)return H.url}return cf($.host,$.port,$.pathname)}async function Q6(f){return await new Promise(($,J)=>{(async()=>{let H=new URL(f),W=await cA(H);H.hash="";let Q=new WebSocket(H.toString(),W?[`${gA}${W}`]:void 0),Z=new Map,j=0;Q.addEventListener("open",()=>{$({send(P){let X=P.requestId??`hub-client-${++j}`;return new Promise((V,Y)=>{Z.set(X,{resolve:V,reject:Y});let B={kind:"command",envelope:{...P,requestId:X}};Q.send(JSON.stringify(B))})},close(){Q.close()}})}),Q.addEventListener("message",(P)=>{let X=JSON.parse(String(P.data));if(X.kind==="reply"&&X.envelope.requestId){let V=Z.get(X.envelope.requestId);if(V)Z.delete(X.envelope.requestId),V.resolve(X.envelope)}}),Q.addEventListener("close",()=>{for(let P of Z.values())P.reject(Error("Hub connection closed"));Z.clear()}),Q.addEventListener("error",(P)=>{J(xA(P,f))})})().catch(J)})}async function y7(f){try{return(await Q6(f)).close(),!0}catch{return!1}}async function K7(f,$){let J=await IH(f),H=await Q6(J);try{return await H.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{H.close()}}function of(f){return f?JSON.parse(JSON.stringify(f)):{}}function Z6(f){let $=f?.session&&typeof f.session==="object"?f.session:void 0;if(!$)return;let J=$.metadata&&typeof $.metadata==="object"?of($.metadata):void 0;return{sessionId:typeof $.sessionId==="string"?$.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function U7(f,$){return f.error?.message??`hub command failed: ${$}`}function dA(f){let $=of(f);if(typeof $.error==="string"&&$.error.trim())return{...$,error:$.error.trim()};let J=$.result&&typeof $.result==="object"?$.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...$,error:J.text.trim()};let H=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof H?.message==="string"&&H.message.trim())return{...$,error:H.message.trim()};return $}function rA(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))throw Error("hub checkpoint restore returned no checkpoint");let J=$;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function lA(f){let $=f.sessionId?.trim();if(!$)return;switch(f.event){case"iteration.started":return{sessionId:$,eventType:"runtime.chat.iteration_start",payload:of(f.payload)};case"iteration.finished":return{sessionId:$,eventType:"runtime.chat.iteration_end",payload:of(f.payload)};case"assistant.delta":return{sessionId:$,eventType:"runtime.chat.text_delta",payload:of(f.payload)};case"tool.started":return{sessionId:$,eventType:"runtime.chat.tool_call_start",payload:of(f.payload)};case"tool.finished":return{sessionId:$,eventType:"runtime.chat.tool_call_end",payload:of(f.payload)};case"approval.requested":return{sessionId:$,eventType:"approval.requested",payload:of(f.payload)};case"run.aborted":return{sessionId:$,eventType:"runtime.chat.aborted",payload:of(f.payload)};case"run.failed":return{sessionId:$,eventType:"runtime.chat.failed",payload:dA(f.payload)};case"run.completed":return{sessionId:$,eventType:"runtime.chat.completed",payload:of(f.payload)};default:return}}class xH{options;client;metadataApplied=!1;constructor(f){this.options=f;this.client=new df({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-session-client",displayName:f.displayName??"hub session client",workspaceRoot:f.workspaceRoot,cwd:f.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.create",{workspaceRoot:f.workspaceRoot,cwd:f.cwd,sessionConfig:{providerId:f.provider,modelId:f.model,apiKey:f.apiKey,cwd:f.cwd??f.workspaceRoot,workspaceRoot:f.workspaceRoot,systemPrompt:f.systemPrompt??"",mode:f.mode??"act",rules:f.rules,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawnAgent:f.enableSpawn!==!1,enableAgentTeams:f.enableTeams!==!1,disableMcpSettingsTools:f.disableMcpSettingsTools,missionLogIntervalSteps:f.missionStepInterval,missionLogIntervalMs:f.missionTimeIntervalMs},metadata:{source:f.source??"cli",provider:f.provider,model:f.model,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,prompt:void 0,interactive:f.interactive!==!1},runtimeOptions:{mode:f.mode,systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,autoApproveTools:f.autoApproveTools,toolExecutors:f.toolExecutors,configExtensions:f.configExtensions},modelSelection:{provider:f.provider,model:f.model,apiKey:f.apiKey},toolPolicies:f.toolPolicies}),J=Z6($.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession(f,$,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:$.prompt,attachments:$.attachments,delivery:$.delivery,timeoutSeconds:$.config.timeoutSeconds},f,J)).payload?.result}}async stopRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:f},f),{applied:!0}}async abortRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:f},f),{applied:!0}}async updateSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:f.sessionId,metadata:f.metadata},f.sessionId),{updated:!0}}async getSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.get",void 0,f);return Z6($.payload)}async readMessages(f){let $=f.trim();if(!$)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(U7(J,"session.messages"));let H=J.payload?.messages;return Array.isArray(H)?H:[]}async restore(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let H=f.config,W=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...H?{workspaceRoot:H.workspaceRoot,cwd:H.cwd,sessionConfig:{providerId:H.provider,modelId:H.model,apiKey:H.apiKey,cwd:H.cwd??H.workspaceRoot,workspaceRoot:H.workspaceRoot,systemPrompt:H.systemPrompt??"",mode:H.mode??"act",rules:H.rules,maxIterations:H.maxIterations,enableTools:H.enableTools,enableSpawnAgent:H.enableSpawn!==!1,enableAgentTeams:H.enableTeams!==!1,disableMcpSettingsTools:H.disableMcpSettingsTools,missionLogIntervalSteps:H.missionStepInterval,missionLogIntervalMs:H.missionTimeIntervalMs},metadata:{source:H.source??"cli",provider:H.provider,model:H.model,enableTools:H.enableTools,enableSpawn:H.enableSpawn,enableTeams:H.enableTeams,prompt:void 0,interactive:H.interactive!==!1},runtimeOptions:{mode:H.mode,systemPrompt:H.systemPrompt,maxIterations:H.maxIterations,enableTools:H.enableTools,enableSpawn:H.enableSpawn,enableTeams:H.enableTeams,autoApproveTools:H.autoApproveTools,configExtensions:H.configExtensions},modelSelection:{provider:H.provider,model:H.model,apiKey:H.apiKey},toolPolicies:H.toolPolicies}:{}},$);if(!W.ok)throw Error(U7(W,"session.restore"));let Q=Z6(W.payload);if(J&&!Q?.sessionId)throw Error("hub checkpoint restore returned no session id");let Z=Array.isArray(W.payload?.messages)?W.payload.messages:void 0,j=rA(W.payload);return{sessionId:Q?.sessionId,startResult:Q?.sessionId?{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}:void 0,...Z?{messages:Z}:{},checkpoint:j}}async listSessions(f){await this.ensureMetadataApplied();let $=await this.client.command("session.list",{limit:f?.limit??200});return(Array.isArray($.payload?.sessions)?$.payload?.sessions:[]).map((H)=>Z6({session:H})).filter((H)=>Boolean(H?.sessionId))}async deleteSession(f,$=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:f,deleteCheckpointRefs:$})).payload?.deleted===!0}async respondToolApproval(f){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:f.approvalId,approved:f.approved,payload:f.reason?{reason:f.reason}:void 0,responderClientId:f.responderClientId})}streamEvents(f,$){let J=new Set((f.sessionIds??[]).map((W)=>W.trim()).filter(Boolean)),H=this.client.subscribe((W)=>{let Q=lA(W);if(!Q)return;if(J.size>0&&!J.has(Q.sessionId))return;$.onEvent?.(Q)});return this.ensureMetadataApplied().catch((W)=>{$.onError?.(W instanceof Error?W:Error(String(W)))}),H}streamTeamProgress(f,$){let J=this.client.subscribe((H)=>{if(H.event!=="team.progress"||!H.payload)return;$.onProjection?.(H.payload)});return this.ensureMetadataApplied().catch((H)=>{$.onError?.(H instanceof Error?H:Error(String(H)))}),J}async createSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",f)).payload?.schedule}async listSchedules(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.list");return Array.isArray($.payload?.schedules)?$.payload?.schedules:[]}async getSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:f})).payload?.schedule}async updateSchedule(f,$){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:f,...$})).payload?.schedule}async pauseSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:f})).payload?.schedule}async resumeSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:f})).payload?.schedule}async deleteSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:f})).payload?.deleted===!0}async triggerScheduleNow(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:f})).payload?.execution}async listScheduleExecutions(f,$){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:f,limit:$});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let f=await this.client.command("schedule.active");return Array.isArray(f.payload?.executions)?f.payload?.executions:[]}async getUpcomingScheduledRuns(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.upcoming",{limit:f});return Array.isArray($.payload?.upcoming)?$.payload?.upcoming:[]}}class gH{client;constructor(f){this.client=new df({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-ui-client",displayName:f.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify(f){await this.client.command("ui.notify",f)}async sendShowWindow(f){await this.client.command("ui.show_window",f??{})}async listClients(){let f=await this.client.command("client.list");return Array.isArray(f.payload?.clients)?f.payload.clients:[]}async listSessions(f=200){let $=await this.client.command("session.list",{limit:f});return Array.isArray($.payload?.sessions)?$.payload.sessions:[]}subscribeUI(f){return this.client.subscribe(($)=>{switch($.event){case"ui.notify":f.onNotify?.($.payload);break;case"ui.show_window":f.onShowWindow?.($.payload);break;case"hub.client.registered":f.onClientRegistered?.($.payload??{});break;case"hub.client.disconnected":f.onClientDisconnected?.($.payload??{});break;case"session.created":f.onSessionCreated?.($.payload??{});break;case"session.updated":f.onSessionUpdated?.($.payload??{});break;case"session.detached":f.onSessionDetached?.($.payload??{});break}})}}import{normalizeProviderId as PL}from"@cline/llms";var HV={};N(HV,{LocalRuntimeHost:()=>j0});import{homedir as $L}from"node:os";import{isAbsolute as JL,join as o9,resolve as HL}from"node:path";import{createSessionId as WL,isLikelyAuthError as QL,normalizeUserInput as ZL}from"@cline/shared";import{setHomeDirIfUnset as jL}from"@cline/shared/storage";var v7={};N(v7,{createContextCompactionPrepareTurn:()=>d2});import{createHandler as sA}from"@cline/llms";var G7=200000,h7=0.95;var vH=20000;var T7=8;function pA(f){return Math.max(1,Math.ceil(f.length/4))}function U$(f,$){if(f.length<=$)return f;return`${f.slice(0,$)}
278
- ...[truncated ${f.length-$} chars]`}function iA(f){if(typeof f==="string")return U$(f,2000);return f.map(($)=>{switch($.type){case"text":return $.text;case"file":return`<file path="${$.path}">
279
- ${U$($.content,2000)}
275
+ WHERE run_id = ? AND claim_token = ?`).run(f.error??null,f.scheduledFor??null,$,f.runId,f.claimToken).changes??0)>0}attachSessionIdToRun(f,$){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run($,Yf(),f)}attachReportPathToRun(f,$){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run($,Yf(),f)}}function m4(f){return f?new Date(f).getTime():void 0}function PY(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function I4(f){let $=f.metadata;return{scheduleId:f.externalId,name:f.title,cronPattern:f.scheduleExpr??"",prompt:f.prompt??"",workspaceRoot:f.workspaceRoot??"",cwd:typeof $?.__hubScheduleCwd==="string"?$.__hubScheduleCwd:void 0,modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:f.enabled&&!f.removed&&f.parseStatus==="valid",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,maxParallel:f.maxParallel??1,createdAt:new Date(f.createdAt).getTime(),updatedAt:new Date(f.updatedAt).getTime(),nextRunAt:m4(f.nextRunAt),lastRunAt:m4(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:PY(f)}}function BY(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function r3(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:m4(f.startedAt),endedAt:m4(f.completedAt),status:BY(f.status),errorMessage:f.error}}class j1{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new h2({dbPath:f.dbPath}),this.materializer=new U2({store:this.store}),this.runner=new D2({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:"",logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule(f){if(F5(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return I4(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?I4($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>I4($))}updateSchedule(f,$){if($.cronPattern!==void 0)F5($.cronPattern);let J=this.store.getHubSchedule(f);if(!J)return;let W=$.workspaceRoot!==void 0?$.workspaceRoot.trim():J.workspaceRoot;if(($.enabled??J.enabled)&&!W)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule(f,{...$,scheduleId:f});return Q?I4(Q):void 0}deleteSchedule(f){return this.store.deleteHubSchedule(f)}pauseSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!1})}resumeSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!0})}async triggerScheduleNow(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;await this.runner.tick();let J=this.store.getRun($.runId)??$;return r3(J,f)}listScheduleExecutions(f){let $=f.scheduleId?this.store.getHubSchedule(f.scheduleId):void 0,J={specId:$?.specId,limit:f.limit};return this.store.listRuns(J).map((H)=>{let Q=$??this.store.getSpec(H.specId);if(!Q||Q.source!=="hub-schedule")return;return r3(H,Q.externalId)}).filter((H)=>{if(!H)return!1;return!f.status||H.status===f.status})}getScheduleStats(f){let $=this.listScheduleExecutions({scheduleId:f,limit:1e4});if($.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,W=0,H=0,Q;for(let Z of $){if(Z.status==="success"||Z.status==="completed")J+=1;if(!Q&&Z.status!=="success"&&Z.status!=="completed")Q=Z;if(Z.startedAt&&Z.endedAt)H+=Z.endedAt-Z.startedAt,W+=1}return{totalRuns:$.length,successRate:J/$.length,avgDurationSeconds:W>0?H/W/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((f)=>{let $=this.store.getSpec(f.specId);if(!$||$.source!=="hub-schedule"||!f.sessionId)return[];return[{executionId:f.runId,scheduleId:$.externalId,sessionId:f.sessionId,startedAt:f.startedAt??new Date().toISOString(),timeoutAt:$.timeoutSeconds&&f.startedAt?new Date(new Date(f.startedAt).getTime()+$.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(f=20){let $={triggerKind:"schedule",enabled:!0,limit:f};return this.store.listSpecs($).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,W)=>String(J.nextRunAt).localeCompare(String(W.nextRunAt))).slice(0,f).map(({spec:J,nextRunAt:W})=>({scheduleId:J.externalId,name:J.title,nextRunAt:W}))}}H6();import{createSessionId as uV,resolveHubCommandTimeoutMs as cV}from"@cline/shared";import{spawn as GV}from"node:child_process";import{closeSync as TV,mkdirSync as DV,openSync as _V}from"node:fs";import{basename as MV,dirname as LV,join as hV}from"node:path";import{fileURLToPath as OV}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as zV,isHubDaemonProcess as UQ,withResolvedClineBuildEnv as NV}from"@cline/shared";import{createHash as oY,randomBytes as eY}from"node:crypto";import{existsSync as fV}from"node:fs";import{chmod as $V,mkdir as M5,readFile as PQ,rm as L5,writeFile as BQ}from"node:fs/promises";import{dirname as YQ,join as h5}from"node:path";import{resolveClineDataDir as I2,resolveClineDir as VQ}from"@cline/shared/storage";var ZQ="0.0.39";var jQ={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:ZQ,repository:{type:"git",url:"https://github.com/cline/sdk",directory:"packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"rm -rf dist && bun run ./bun.mts && bun tsc -p tsconfig.build.json",clean:"rm -rf dist node_modules",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: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:*","@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:"^1.21.7","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"^3.32.3",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var JV="CLINE_HUB_DISCOVERY_PATH",WV="CLINE_HUB_BUILD_ID",XQ=30000,HV=15000,QV=100;function ZV(f){return f.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function jV(f){return oY("sha256").update(f).digest("hex").slice(0,12)}function XV(f){if(!Number.isInteger(f)||!f||f<=0)return!1;try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function Q6(){return eY(32).toString("hex")}function AV(f){return new Promise(($)=>setTimeout($,f))}function PV(f){return`${f}.lock`}async function BV(f){try{let $=JSON.parse(await PQ(h5(f,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function AQ(f){await L5(f,{recursive:!0,force:!0}).catch(()=>{return})}function v0(){return process.env[WV]?.trim()||String(jQ.version)}function D0(f=process.argv[1]?.trim()||process.cwd()){let $=`hub-${jV(f)}`,J=process.env[JV]?.trim()||h5(I2(),"locks","hub","owners",`${ZV($)}.json`);return{ownerId:$,discoveryPath:J}}function RQ(f=`hub-${Date.now().toString(36)}`){return D0(f)}async function Af(f){try{let $=JSON.parse(await PQ(f,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,buildId:typeof $.buildId==="string"?$.buildId:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function Z6(f,$){await M5(YQ(f),{recursive:!0}),await L5(f,{force:!0}).catch(()=>{return}),await BQ(f,`${JSON.stringify($,null,2)}
276
+ `,{encoding:"utf8",mode:384}),await $V(f,384)}async function bf(f){await L5(f,{force:!0}).catch(()=>{return})}async function j6(f,$){let J=PV(f);await M5(YQ(J),{recursive:!0});let W=Date.now()+HV;while(!0)try{await M5(J,{recursive:!1}),await BQ(h5(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
277
+ `,"utf8");try{return await $()}finally{await AQ(J)}}catch(H){if((H instanceof Error&&"code"in H?String(H.code):"")!=="EEXIST")throw H;let Z=await BV(J),j=Z?Date.now()-Date.parse(Z.acquiredAt):XQ+1;if(!Z||!XV(Z.pid)||j>XQ){await AQ(J);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${J}`);await AV(QV)}}async function Vf(f){try{let $=await fetch(O5(f));if(!$.ok)return;return await $.json()}catch{return}}function lf(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function O5(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function FQ(f){return fV(f)}import{CLINE_HUB_DEV_PORT as YV,CLINE_HUB_PORT as VV,resolveClineBuildEnv as RV}from"@cline/shared";var FV="CLINE_HUB_HOST",KV="CLINE_HUB_PORT",yV="CLINE_HUB_PATHNAME",z5="127.0.0.1",N5=VV,q5="/hub";function KQ(f){return RV(f)==="development"?YV:N5}function w5(f={}){return(f.env??process.env)[FV]?.trim()||z5}function Y1(f={}){let J=(f.env??process.env)[KV]?.trim();if(!J)return KQ(f);let W=Number.parseInt(J,10);if(!Number.isInteger(W)||W<1||W>65535)return KQ(f);return W}function b5(f={}){return(f.env??process.env)[yV]?.trim()||q5}function of(f={},$={}){return{host:f.host??w5($),port:f.port??Y1($),pathname:f.pathname??b5($)}}var UV="shared:cline";function yQ(f){let $=R0(f.trim());return D0(`workspace:${$||f.trim()}`)}function Rf(f=UV){return D0(f)}var qV=8000,wV=200,bV=3000,CV=100,EV=[100,250,500,1000,2000],SV="--cline-hub-daemon";function kV(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function IV(){try{let f=hV(I2(),"logs","hub-daemon.log");return DV(LV(f),{recursive:!0}),{fd:_V(f,"a"),logPath:f}}catch{return}}function m2(f){let $=f.buildId?.trim();return!!$&&$===v0()}async function mV(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await Vf(f).catch(()=>{return}))?.url)return!0;await new Promise((H)=>setTimeout(H,CV))}return!1}async function x2(f,$){if(m2(f))return;if(await g2(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await mV(f.url,bV),await bf($).catch(()=>{return})}function xV(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return OV(new URL(`./entry.${f}`,import.meta.url))}function gV(f,$){let J=xV(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let H=MV(W).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),Z=H&&J.toLowerCase().endsWith(".ts"),j=Q?[SV]:[...Z?["--conditions=development"]:[],J];return{launcher:W,args:[...j,"--cwd",f,...kV($)],cwd:f,env:{...NV(process.env),CLINE_NO_INTERACTIVE:"1",[zV]:"1"}}}function vV(f){if(!f||typeof f!=="object")return!1;if(("code"in f?f.code:void 0)==="ETXTBSY")return!0;let J="message"in f?f.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function C5(f,$={}){if(UQ())return;let J=gV(f,$),W=IV();try{GV(J.launcher,J.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(W)TV(W.fd)}}async function V1(f,$={}){for(let J=0;;J++)try{C5(f,$);return}catch(W){let H=EV[J];if(!vV(W)||H===void 0)throw W;await new Promise((Q)=>setTimeout(Q,H))}}function X6(f,$={}){if(UQ())return;let J=Rf(),W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),H=of($),Q=lf(H.host,H.port,H.pathname);Af(J.discoveryPath).then(async(Z)=>{if(Z?.url){let P=await Vf(Z.url);if(P?.url&&m2(P)&&await ef(P.url,{authToken:Z.authToken}))return;if(P?.url)await x2({...P,authToken:Z.authToken},J.discoveryPath);else await bf(J.discoveryPath).catch(()=>{return})}let j=await Vf(Q);if(j?.url)await x2(j,J.discoveryPath);let A=!W&&H.port!==0?{...H,port:0}:H;await V1(f,A)}).catch(()=>{})}async function GQ(f,$={}){let J=Rf(),W=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),H=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=of($),Z=lf(Q.host,Q.port,Q.pathname),j=(V)=>{if(!W)u0(V.url,V.authToken);return V},X=await Af(J.discoveryPath);if(X?.url){let V=await Vf(X.url);if(V?.url&&m2(V)&&await ef(V.url,{authToken:X.authToken}))return j({url:V.url,authToken:X.authToken});if(V?.url)await x2({...V,authToken:X.authToken},J.discoveryPath);else await bf(J.discoveryPath).catch(()=>{return})}let A=await Vf(Z);if(A?.url)await x2(A,J.discoveryPath);let B=!H&&Q.port!==0?{...Q,port:0}:Q;await V1(f,B);let Y=Date.now()+qV;while(Date.now()<Y){let V=await Af(J.discoveryPath);if(V?.url){let U=await Vf(V.url);if(U?.url&&m2(U)&&await ef(U.url,{authToken:V.authToken}))return j({url:U.url,authToken:V.authToken})}let R=await Vf(Z);if(R?.url&&!m2(R))await x2(R,J.discoveryPath);await new Promise((U)=>setTimeout(U,wV))}throw Error("Timed out waiting for detached hub startup.")}function dV(){let f=globalThis.WebSocket;if(!f)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return f}function LQ(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();if(f&&typeof f==="object"&&"data"in f&&typeof f.data<"u")return LQ(f.data);return String(f)}function rV(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString("utf8");if(f instanceof ArrayBuffer)return Buffer.from(f).toString("utf8");return""}function TQ(f){let $=f,J=rV($.reason);return new Df("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:E5,{closeCode:$.code,closeReason:J||void 0})}function lV(f,$){if(f instanceof Df)return f;if(f instanceof Error)return new Df("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new Df("hub_connect_failed",f.error.message);let J=f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"?f.message.trim():"";if(J)return new Df("hub_connect_failed",J);let W=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new Df("hub_connect_failed",W?`Failed to connect to hub at ${$.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var pV=8000,iV=200,DQ="*",_Q=8000,nV="cline-hub-auth.",hQ=new Map,OQ=new Set,aV=3000,tV=3000,sV=100,E5="Hub connection closed",oV=250,eV=5000,MQ=0.5;class Df extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function I5(f){return f instanceof Df}class R1 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function A6(f,$){return f instanceof R1&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function zQ(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=m5(f.toString());return J?hQ.get(J):void 0}function fR(f){try{let J=new URL(f).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function m5(f){if(!fR(f))return;let $=new URL(c0(f));return $.search="",$.hash="",$.toString()}function S5(f){let $=m5(f);return!!$&&OQ.has($)}function u0(f,$){let J=m5(f);if(J){if(OQ.add(J),$?.trim())hQ.set(J,$)}return f}class pf{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new Df("hub_connection_closed",E5);sawSocketClose=!1;registered=!1;constructor(f){this.options=f;this.clientId=f.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=f.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let f=new URL(this.currentUrl),$=this.options.authToken?.trim()||zQ(f);f.hash="";let W=new(dV())(f.toString(),$?[`${nV}${$}`]:void 0);this.socket=W;let H=!1;this.connectPromise=new Promise((Q,Z)=>{let j=!1,X=setTimeout(()=>{if(j)return;j=!0,H=!0,this.lastCloseError=new Df("hub_connect_timeout",`Timed out connecting to hub after ${_Q}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}Z(this.lastCloseError)},_Q);W.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(X),Q()}),W.addEventListener("error",(A)=>{if(j)return;j=!0,clearTimeout(X),this.lastCloseError=lV(A,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)}),W.addEventListener("close",(A)=>{if(j)return;if(j=!0,clearTimeout(X),!H)this.lastCloseError=TQ(A),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)})}),W.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(LQ(Q)))}),W.addEventListener("close",(Q)=>{if(this.socket!==W)return;if(!H)this.lastCloseError=TQ(Q),this.sawSocketClose=!0;this.registered=!1;for(let Z of this.pendingReplies.values())Z.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe(f,$){let J=$?.sessionId?.trim()||void 0,W={listener:f,sessionId:J};return this.listeners.add(W),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(W))return;this.adjustSubscriptionCount(J,-1)}}async command(f,$,J,W){let H=0,Q=f!=="client.register"&&f!=="client.unregister";while(!0)try{return await this.commandOnce(f,$,J,W)}catch(Z){if(!Q||H>=1||!await this.recoverLocalHubTransport(Z))throw Z;H+=1}}async commandOnce(f,$,J,W){await this.connect();let H=uV("hubreq_"),Q=cV(f,W?.timeoutMs),Z=new Promise((X,A)=>{let P=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(H))return;A(new R1(f,"hub_command_timeout",`Hub command ${f} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${H}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(H,{resolve:(B)=>{if(P)clearTimeout(P);X(B)},reject:(B)=>{if(P)clearTimeout(P);A(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:f,requestId:H,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:$}})}catch(X){throw this.pendingReplies.delete(H),X}let j=await Z;if(!j.ok)throw new R1(f,j.error?.code,j.error?.message??`Hub command ${f} failed`);return j}async recoverLocalHubTransport(f){if(!S5(this.currentUrl)||!I5(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await T$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let f=Math.min(oV*2**this.reconnectAttempt,eV),$=Math.round(f*(1-MQ)+Math.random()*f*MQ);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!S5(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await T$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(f){this.currentUrl=f,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let f=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!f)return;this.lastCloseError=new Df("hub_connection_closed",E5),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{f.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(f){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new Df("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(f))}sendSubscriptionFrame(f,$){this.sendFrame({kind:f,clientId:this.clientId,...$?{sessionId:$}:{}})}adjustSubscriptionCount(f,$){let J=this.subscriptionKeyForSessionId(f),W=(this.subscriptionCounts.get(J)??0)+$;if(W<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",f);return}if(this.subscriptionCounts.set(J,W),$>0&&W===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",f)}subscriptionKeyForSessionId(f){return f??DQ}subscriptionSessionIdFromKey(f){return f===DQ?void 0:f}handleFrame(f){switch(f.kind){case"reply":{let $=f.envelope.requestId;if(!$)return;let J=this.pendingReplies.get($);if(!J)return;this.pendingReplies.delete($),J.resolve(f.envelope);return}case"event":for(let $ of this.listeners){if($.sessionId&&$.sessionId!==f.envelope.sessionId?.trim())continue;$.listener(f.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function c0(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function ef(f,$){let J=new pf({url:f,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function k5(f,$){let J=c0(f),W=await Vf(J);if(!W)return{status:"unreachable",url:J};let H=v0(),Q=W.buildId?.trim();if(!Q||Q!==H)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await ef(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function $R(f){let $=Date.now()+pV;while(Date.now()<$){let J=await Af(f.discoveryPath);if(J?.url){let W=await k5(J.url,{verifyConnection:!0,authToken:J.authToken});if(W.status==="compatible")return u0(W.url,J.authToken)}await new Promise((W)=>setTimeout(W,iV))}return}async function JR(f){let $=Date.now()+tV;while(Date.now()<$){if(!(await Vf(f).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,sV))}return!1}function WR(f,$){try{return c0(f)===c0($)}catch{return!1}}function HR(f){return(f&&typeof f==="object"&&Array.isArray(f.sessions)?f.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let W=J;if(W.status==="running"||W.status==="idle")return!0;return Array.isArray(W.participants)&&W.participants.length>0})}async function QR(f,$,J){let W=new pf({url:f,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let H=await W.command("session.list",{limit:500},void 0,{timeoutMs:aV});return!HR(H.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function v2(f={}){if(f.endpoint?.trim()){let H=await k5(f.endpoint);return H.status==="compatible"?H.url:void 0}let $=Rf(),J=await Af($.discoveryPath);if(!J?.url)return;let W=await k5(J.url);if(W.status==="compatible")return u0(W.url,J.authToken);if(W.status==="build_mismatch")await bf($.discoveryPath).catch(()=>{return});return}async function T$(f={}){let $=await v2(f);if($&&await ef($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=Rf();return await V1(f.workspaceRoot??process.cwd()),await $R(J)}async function g2(f,$){let J=new URL(f),W=$?.trim()||zQ(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:W?{authorization:`Bearer ${W}`}:void 0})).ok}async function x5(){let f=Rf(),$=await Af(f.discoveryPath);if(!$?.url)return!1;try{if(await g2($.url,$.authToken))return!0}catch{}return!1}async function P6(f){if(!S5(f.url))return;let $=Rf(),J=await Af($.discoveryPath);if(!J?.url||!WR(J.url,f.url))return;if(!await QR(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await x5())return;if(!await JR(J.url))return;return await bf($.discoveryPath).catch(()=>{return}),await T$({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}function ZR(f,$){if(f instanceof Error)return f;if(f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"&&f.message.trim())return Error(f.message.trim());let J=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return Error(J?`Failed to connect to hub at ${$} (${J} event before socket open).`:`Failed to connect to hub at ${$}.`)}var jR="cline-hub-auth.";function XR(f){return f.host!==void 0||f.port!==void 0||f.pathname!==void 0}function AR(f,$){let J=new URL(f),W=new URL($);return J.search="",J.hash="",W.search="",W.hash="",J.toString()===W.toString()}async function PR(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=Rf(),W=await Af(J.discoveryPath);if(W?.url&&AR(f.toString(),W.url))return W.authToken;return}async function g5(f={}){let $=of(f);if(!XR(f)){let J=Rf(),W=await Af(J.discoveryPath);if(W?.url)return W.url}return lf($.host,$.port,$.pathname)}async function B6(f){return await new Promise(($,J)=>{(async()=>{let W=new URL(f),H=await PR(W);W.hash="";let Q=new WebSocket(W.toString(),H?[`${jR}${H}`]:void 0),Z=new Map,j=0;Q.addEventListener("open",()=>{$({send(X){let A=X.requestId??`hub-client-${++j}`;return new Promise((P,B)=>{Z.set(A,{resolve:P,reject:B});let Y={kind:"command",envelope:{...X,requestId:A}};Q.send(JSON.stringify(Y))})},close(){Q.close()}})}),Q.addEventListener("message",(X)=>{let A=JSON.parse(String(X.data));if(A.kind==="reply"&&A.envelope.requestId){let P=Z.get(A.envelope.requestId);if(P)Z.delete(A.envelope.requestId),P.resolve(A.envelope)}}),Q.addEventListener("close",()=>{for(let X of Z.values())X.reject(Error("Hub connection closed"));Z.clear()}),Q.addEventListener("error",(X)=>{J(ZR(X,f))})})().catch(J)})}async function NQ(f){try{return(await B6(f)).close(),!0}catch{return!1}}async function qQ(f,$){let J=await g5(f),W=await B6(J);try{return await W.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{W.close()}}function nf(f){return f?JSON.parse(JSON.stringify(f)):{}}function Y6(f){let $=f?.session&&typeof f.session==="object"?f.session:void 0;if(!$)return;let J=$.metadata&&typeof $.metadata==="object"?nf($.metadata):void 0;return{sessionId:typeof $.sessionId==="string"?$.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function wQ(f,$){return f.error?.message??`hub command failed: ${$}`}function BR(f){let $=nf(f);if(typeof $.error==="string"&&$.error.trim())return{...$,error:$.error.trim()};let J=$.result&&typeof $.result==="object"?$.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...$,error:J.text.trim()};let W=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof W?.message==="string"&&W.message.trim())return{...$,error:W.message.trim()};return $}function YR(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))throw Error("hub checkpoint restore returned no checkpoint");let J=$;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function VR(f){let $=f.sessionId?.trim();if(!$)return;switch(f.event){case"iteration.started":return{sessionId:$,eventType:"runtime.chat.iteration_start",payload:nf(f.payload)};case"iteration.finished":return{sessionId:$,eventType:"runtime.chat.iteration_end",payload:nf(f.payload)};case"assistant.delta":return{sessionId:$,eventType:"runtime.chat.text_delta",payload:nf(f.payload)};case"usage.updated":return{sessionId:$,eventType:"runtime.chat.usage",payload:nf(f.payload)};case"tool.started":return{sessionId:$,eventType:"runtime.chat.tool_call_start",payload:nf(f.payload)};case"tool.finished":return{sessionId:$,eventType:"runtime.chat.tool_call_end",payload:nf(f.payload)};case"approval.requested":return{sessionId:$,eventType:"approval.requested",payload:nf(f.payload)};case"run.aborted":return{sessionId:$,eventType:"runtime.chat.aborted",payload:nf(f.payload)};case"run.failed":return{sessionId:$,eventType:"runtime.chat.failed",payload:BR(f.payload)};case"run.completed":return{sessionId:$,eventType:"runtime.chat.completed",payload:nf(f.payload)};default:return}}class v5{options;client;metadataApplied=!1;constructor(f){this.options=f;this.client=new pf({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-session-client",displayName:f.displayName??"hub session client",workspaceRoot:f.workspaceRoot,cwd:f.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.create",{workspaceRoot:f.workspaceRoot,cwd:f.cwd,sessionConfig:{providerId:f.provider,modelId:f.model,apiKey:f.apiKey,cwd:f.cwd??f.workspaceRoot,workspaceRoot:f.workspaceRoot,systemPrompt:f.systemPrompt??"",mode:f.mode??"act",rules:f.rules,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawnAgent:f.enableSpawn!==!1,enableAgentTeams:f.enableTeams!==!1,disableMcpSettingsTools:f.disableMcpSettingsTools,missionLogIntervalSteps:f.missionStepInterval,missionLogIntervalMs:f.missionTimeIntervalMs},metadata:{source:f.source??"cli",provider:f.provider,model:f.model,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,prompt:void 0,interactive:f.interactive!==!1},runtimeOptions:{mode:f.mode,systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,autoApproveTools:f.autoApproveTools,toolExecutors:f.toolExecutors,configExtensions:f.configExtensions},modelSelection:{provider:f.provider,model:f.model,apiKey:f.apiKey},toolPolicies:f.toolPolicies}),J=Y6($.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession(f,$,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:$.prompt,attachments:$.attachments,delivery:$.delivery,timeoutSeconds:$.config.timeoutSeconds},f,J)).payload?.result}}async stopRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:f},f),{applied:!0}}async abortRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:f},f),{applied:!0}}async updateSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:f.sessionId,metadata:f.metadata},f.sessionId),{updated:!0}}async getSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.get",void 0,f);return Y6($.payload)}async readMessages(f){let $=f.trim();if(!$)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(wQ(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async restore(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let W=f.config,H=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...W?{workspaceRoot:W.workspaceRoot,cwd:W.cwd,sessionConfig:{providerId:W.provider,modelId:W.model,apiKey:W.apiKey,cwd:W.cwd??W.workspaceRoot,workspaceRoot:W.workspaceRoot,systemPrompt:W.systemPrompt??"",mode:W.mode??"act",rules:W.rules,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawnAgent:W.enableSpawn!==!1,enableAgentTeams:W.enableTeams!==!1,disableMcpSettingsTools:W.disableMcpSettingsTools,missionLogIntervalSteps:W.missionStepInterval,missionLogIntervalMs:W.missionTimeIntervalMs},metadata:{source:W.source??"cli",provider:W.provider,model:W.model,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,prompt:void 0,interactive:W.interactive!==!1},runtimeOptions:{mode:W.mode,systemPrompt:W.systemPrompt,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,autoApproveTools:W.autoApproveTools,configExtensions:W.configExtensions},modelSelection:{provider:W.provider,model:W.model,apiKey:W.apiKey},toolPolicies:W.toolPolicies}:{}},$);if(!H.ok)throw Error(wQ(H,"session.restore"));let Q=Y6(H.payload);if(J&&!Q?.sessionId)throw Error("hub checkpoint restore returned no session id");let Z=Array.isArray(H.payload?.messages)?H.payload.messages:void 0,j=YR(H.payload);return{sessionId:Q?.sessionId,startResult:Q?.sessionId?{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}:void 0,...Z?{messages:Z}:{},checkpoint:j}}async listSessions(f){await this.ensureMetadataApplied();let $=await this.client.command("session.list",{limit:f?.limit??200});return(Array.isArray($.payload?.sessions)?$.payload?.sessions:[]).map((W)=>Y6({session:W})).filter((W)=>Boolean(W?.sessionId))}async deleteSession(f,$=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:f,deleteCheckpointRefs:$})).payload?.deleted===!0}async respondToolApproval(f){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:f.approvalId,approved:f.approved,payload:f.reason?{reason:f.reason}:void 0,responderClientId:f.responderClientId})}streamEvents(f,$){let J=new Set((f.sessionIds??[]).map((H)=>H.trim()).filter(Boolean)),W=this.client.subscribe((H)=>{let Q=VR(H);if(!Q)return;if(J.size>0&&!J.has(Q.sessionId))return;$.onEvent?.(Q)});return this.ensureMetadataApplied().catch((H)=>{$.onError?.(H instanceof Error?H:Error(String(H)))}),W}streamTeamProgress(f,$){let J=this.client.subscribe((W)=>{if(W.event!=="team.progress"||!W.payload)return;$.onProjection?.(W.payload)});return this.ensureMetadataApplied().catch((W)=>{$.onError?.(W instanceof Error?W:Error(String(W)))}),J}async createSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",f)).payload?.schedule}async listSchedules(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.list");return Array.isArray($.payload?.schedules)?$.payload?.schedules:[]}async getSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:f})).payload?.schedule}async updateSchedule(f,$){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:f,...$})).payload?.schedule}async pauseSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:f})).payload?.schedule}async resumeSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:f})).payload?.schedule}async deleteSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:f})).payload?.deleted===!0}async triggerScheduleNow(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:f})).payload?.execution}async listScheduleExecutions(f,$){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:f,limit:$});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let f=await this.client.command("schedule.active");return Array.isArray(f.payload?.executions)?f.payload?.executions:[]}async getUpcomingScheduledRuns(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.upcoming",{limit:f});return Array.isArray($.payload?.upcoming)?$.payload?.upcoming:[]}}class u5{client;constructor(f){this.client=new pf({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-ui-client",displayName:f.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify(f){await this.client.command("ui.notify",f)}async sendShowWindow(f){await this.client.command("ui.show_window",f??{})}async listClients(){let f=await this.client.command("client.list");return Array.isArray(f.payload?.clients)?f.payload.clients:[]}async listSessions(f=200){let $=await this.client.command("session.list",{limit:f});return Array.isArray($.payload?.sessions)?$.payload.sessions:[]}subscribeUI(f){return this.client.subscribe(($)=>{switch($.event){case"ui.notify":f.onNotify?.($.payload);break;case"ui.show_window":f.onShowWindow?.($.payload);break;case"hub.client.registered":f.onClientRegistered?.($.payload??{});break;case"hub.client.disconnected":f.onClientDisconnected?.($.payload??{});break;case"session.created":f.onSessionCreated?.($.payload??{});break;case"session.updated":f.onSessionUpdated?.($.payload??{});break;case"session.detached":f.onSessionDetached?.($.payload??{});break}})}}import{normalizeProviderId as th}from"@cline/llms";var LP={};N(LP,{LocalRuntimeHost:()=>X0});import{readdirSync as uh}from"node:fs";import{homedir as ch}from"node:os";import{isAbsolute as dh,join as A3,resolve as P3}from"node:path";import{createSessionId as rh,isLikelyAuthError as lh,normalizeUserInput as ph}from"@cline/shared";import{setHomeDirIfUnset as ih}from"@cline/shared/storage";var oQ={};N(oQ,{createContextCompactionPrepareTurn:()=>l2});import{createHandler as GR}from"@cline/llms";var bQ=200000,CQ=0.95;var c5=20000;var EQ=8;function RR(f){return Math.max(1,Math.ceil(f.length/4))}function D$(f,$){if(f.length<=$)return f;return`${f.slice(0,$)}
278
+ ...[truncated ${f.length-$} chars]`}function FR(f){if(typeof f==="string")return D$(f,2000);return f.map(($)=>{switch($.type){case"text":return $.text;case"file":return`<file path="${$.path}">
279
+ ${D$($.content,2000)}
280
280
  </file>`;case"image":return`[image:${$.mediaType}]`;default:return""}}).join(`
281
- `)}function nA(f){return Object.entries(f).map(([$,J])=>`${$}=${JSON.stringify(J)}`).join(", ")}function D7(f){if(typeof f.content==="string")return`[${f.role==="user"?"User":"Bot"}]: ${f.content}`;let $=[];for(let J of f.content)switch(J.type){case"text":$.push(`[${f.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":$.push(`[Bot thinking]: ${U$(J.thinking,2000)}`);break;case"redacted_thinking":$.push("[Bot thinking]: [redacted]");break;case"tool_use":$.push(`[Bot tool calls]: ${J.name}(${nA(J.input)})`);break;case"tool_result":$.push(`[Tool result]: ${iA(J.content)}`);break;case"file":$.push(`[${f.role==="user"?"User":"Bot"} file ${J.path}]: ${U$(J.content,2000)}`);break;case"image":$.push(`[${f.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return $.join(`
282
- `)}function M7(f){return f.map(D7).join(`
281
+ `)}function KR(f){return Object.entries(f).map(([$,J])=>`${$}=${JSON.stringify(J)}`).join(", ")}function SQ(f){if(typeof f.content==="string")return`[${f.role==="user"?"User":"Bot"}]: ${f.content}`;let $=[];for(let J of f.content)switch(J.type){case"text":$.push(`[${f.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":$.push(`[Bot thinking]: ${D$(J.thinking,2000)}`);break;case"redacted_thinking":$.push("[Bot thinking]: [redacted]");break;case"tool_use":$.push(`[Bot tool calls]: ${J.name}(${KR(J.input)})`);break;case"tool_result":$.push(`[Tool result]: ${FR(J.content)}`);break;case"file":$.push(`[${f.role==="user"?"User":"Bot"} file ${J.path}]: ${D$(J.content,2000)}`);break;case"image":$.push(`[${f.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return $.join(`
282
+ `)}function kQ(f){return f.map(SQ).join(`
283
283
 
284
- `).trim()}function _7(){let f=new WeakMap;return($)=>{let J=$,H=f.get(J);if(typeof H==="number")return H;let W=pA(D7($));return f.set(J,W),W}}function u2(f){return f.metadata?.kind==="compaction_summary"}function uH(f){if(!u2(f))return;let $=f.metadata;if(!$)return;let J=$.details;return{kind:"compaction_summary",summary:String($.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((H)=>typeof H==="string").map((H)=>H.trim()).filter((H)=>H.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((H)=>typeof H==="string").map((H)=>H.trim()).filter((H)=>H.length>0):[]},tokensBefore:Number($.tokensBefore??0),generatedAt:Number($.generatedAt??0)}}function aA(f){if(f.role!=="user"||!Array.isArray(f.content))return!1;return f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}function L7(f){return f.role==="user"&&!aA(f)&&!u2(f)}function z7(f){for(let $=0;$<f.length;$+=1)if(L7(f[$]))return $;return-1}function cH(f){for(let $=f.length-1;$>=0;$-=1)if(L7(f[$]))return $;return 0}function O7(f){for(let $=f.length-1;$>=0;$-=1)if(f[$].role==="assistant")return $;return-1}function N7(f){for(let $=f.length-1;$>=0;$-=1)if(u2(f[$]))return $;return-1}function q7(f,$,J){let H=cH(f);if(H<=0)return 0;let W=0,Q=f.length;for(let Z=f.length-1;Z>=0;Z-=1)if(W+=J(f[Z]),Q=Z,W>=$)break;if(Q<=0)return 0;return Math.min(Q,H)}function v2(f){if(typeof f==="string"&&f.trim().length>0)return[f];if(Array.isArray(f))return f.flatMap(($)=>v2($));if(f&&typeof f==="object"){let $=f,J=[];for(let H of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...v2($[H]));if(Array.isArray($.files)){for(let H of $.files)if(H&&typeof H==="object")J.push(...v2(H.path))}if(Array.isArray($.file_paths))J.push(...v2($.file_paths));return J}return[]}function g2(f,$){let J=new Set(f);for(let H of $){let W=H.trim();if(!W)continue;J.add(W)}return[...J].sort((H,W)=>H.localeCompare(W))}function b7(f){let $=[],J=[];for(let H of f){let W=uH(H);if(W){$=g2($,W.details.readFiles),J=g2(J,W.details.modifiedFiles);continue}if(!Array.isArray(H.content))continue;for(let Q of H.content){if(Q.type==="file"){$=g2($,[Q.path]);continue}if(Q.type!=="tool_use")continue;let Z=v2(Q.input);if(Q.name==="read_files"){$=g2($,Z);continue}if(Q.name==="editor"||Q.name==="apply_patch")J=g2(J,Z)}}return{readFiles:$,modifiedFiles:J}}function tA(f){let $=f.readFiles.length>0?f.readFiles.map((H)=>`- ${H}`).join(`
285
- `):"- none",J=f.modifiedFiles.length>0?f.modifiedFiles.map((H)=>`- ${H}`).join(`
284
+ `).trim()}function IQ(){let f=new WeakMap;return($)=>{let J=$,W=f.get(J);if(typeof W==="number")return W;let H=RR(SQ($));return f.set(J,H),H}}function d2(f){return f.metadata?.kind==="compaction_summary"}function d5(f){if(!d2(f))return;let $=f.metadata;if(!$)return;let J=$.details;return{kind:"compaction_summary",summary:String($.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[]},tokensBefore:Number($.tokensBefore??0),generatedAt:Number($.generatedAt??0)}}function yR(f){if(f.role!=="user"||!Array.isArray(f.content))return!1;return f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}function mQ(f){return f.role==="user"&&!yR(f)&&!d2(f)}function xQ(f){for(let $=0;$<f.length;$+=1)if(mQ(f[$]))return $;return-1}function r5(f){for(let $=f.length-1;$>=0;$-=1)if(mQ(f[$]))return $;return 0}function gQ(f){for(let $=f.length-1;$>=0;$-=1)if(f[$].role==="assistant")return $;return-1}function vQ(f){for(let $=f.length-1;$>=0;$-=1)if(d2(f[$]))return $;return-1}function uQ(f,$,J){let W=r5(f);if(W<=0)return 0;let H=0,Q=f.length;for(let Z=f.length-1;Z>=0;Z-=1)if(H+=J(f[Z]),Q=Z,H>=$)break;if(Q<=0)return 0;return Math.min(Q,W)}function c2(f){if(typeof f==="string"&&f.trim().length>0)return[f];if(Array.isArray(f))return f.flatMap(($)=>c2($));if(f&&typeof f==="object"){let $=f,J=[];for(let W of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...c2($[W]));if(Array.isArray($.files)){for(let W of $.files)if(W&&typeof W==="object")J.push(...c2(W.path))}if(Array.isArray($.file_paths))J.push(...c2($.file_paths));return J}return[]}function u2(f,$){let J=new Set(f);for(let W of $){let H=W.trim();if(!H)continue;J.add(H)}return[...J].sort((W,H)=>W.localeCompare(H))}function cQ(f){let $=[],J=[];for(let W of f){let H=d5(W);if(H){$=u2($,H.details.readFiles),J=u2(J,H.details.modifiedFiles);continue}if(!Array.isArray(W.content))continue;for(let Q of W.content){if(Q.type==="file"){$=u2($,[Q.path]);continue}if(Q.type!=="tool_use")continue;let Z=c2(Q.input);if(Q.name==="read_files"){$=u2($,Z);continue}if(Q.name==="editor"||Q.name==="apply_patch")J=u2(J,Z)}}return{readFiles:$,modifiedFiles:J}}function UR(f){let $=f.readFiles.length>0?f.readFiles.map((W)=>`- ${W}`).join(`
285
+ `):"- none",J=f.modifiedFiles.length>0?f.modifiedFiles.map((W)=>`- ${W}`).join(`
286
286
  `):"- none";return`## Files
287
287
  Read:
288
288
  ${$}
289
289
  Modified:
290
- ${J}`}function w7(f,$){if(/^## Files$/im.test(f))return f.trim();return`${f.trim()}
290
+ ${J}`}function dQ(f,$){if(/^## Files$/im.test(f))return f.trim();return`${f.trim()}
291
291
 
292
- ${tA($)}`.trim()}function C7(f){let $=[`Summarize this session for continuation. Be concise and factual.
292
+ ${UR($)}`.trim()}function rQ(f){let $=[`Summarize this session for continuation. Be concise and factual.
293
293
 
294
294
  ## Goal
295
295
  One sentence: what is being built or fixed.
@@ -311,11 +311,11 @@ Edited: ${f.fileOps.modifiedFiles.join(", ")||"none"}`];if(f.previousSummary?.tr
311
311
  ${f.previousSummary.trim()}`);return $.push(`Conversation:
312
312
  ${f.conversationText||"(empty)"}`),$.join(`
313
313
 
314
- `)}function E7(f){let $=f.summarizer;if(!$)return{...f.activeProviderConfig,maxOutputTokens:1024,thinking:!1};let J=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0;return{...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:$.knownModels??J?.knownModels,maxOutputTokens:$.maxOutputTokens??1024,thinking:!1}}function S7(f){return{role:"user",content:`Context summary:
314
+ `)}function lQ(f){let $=f.summarizer;if(!$)return{...f.activeProviderConfig,maxOutputTokens:1024,thinking:!1};let J=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0;return{...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:$.knownModels??J?.knownModels,maxOutputTokens:$.maxOutputTokens??1024,thinking:!1}}function pQ(f){return{role:"user",content:`Context summary:
315
315
 
316
- ${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fileOps,tokensBefore:f.tokensBefore,generatedAt:Date.now()}}}async function oA(f){let $=sA(f.providerConfig),J="";for await(let H of $.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:f.request}])){if(H.type==="text"){J+=H.text;continue}if(H.type==="done"&&!H.success&&H.error)throw Error(H.error)}return f.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:f.providerConfig.modelId,providerId:f.providerConfig.providerId}),J.trim()}async function k7(f){let $=f.context.messages;if($.length<2)return;let J=q7($,f.preserveRecentTokens,f.estimateMessageTokens);if(J<=0||J>=$.length)return;let H=$.slice(0,J),W=N7(H),Q=W>=0?uH(H[W])?.summary:void 0,Z=W>=0?H.slice(W+1):H;if(Z.length===0)return;let j=b7(H),P=M7(Z),X=await oA({providerConfig:E7({activeProviderConfig:f.providerConfig,summarizer:f.summarizer}),request:C7({previousSummary:Q,conversationText:P,fileOps:j}),logger:f.logger});if(!X.trim())return;let V=w7(X,j),Y=$.reduce((R,U)=>R+f.estimateMessageTokens(U),0),B=[S7({summary:V,fileOps:j,tokensBefore:Y}),...$.slice(J)],A=B.reduce((R,U)=>R+f.estimateMessageTokens(U),0);return f.logger?.debug("Performed agentic compaction",{messagesBefore:$.length,messagesAfter:B.length,messagesSummarized:J,messagesPreserved:$.length-J,tokensBefore:Y,tokensAfter:A,contextWindowTokens:f.context.contextWindowTokens}),{messages:B}}function x7(f){if(u2(f))return;if(typeof f.content==="string"){let J=f.content.trim();return J?{...f,content:J}:void 0}let $=f.content.filter((J)=>J.type!=="text"||J.text.trim());if($.length===0)return;return{...f,content:$.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J)}}function c2(f,$){return f.reduce((J,H)=>J+$(H),0)}function m7(f,$){let J=Math.max(1,$),H=Math.max(16,J*4);if(typeof f.content==="string"){let Z=U$(f.content,H).trim();return{...f,content:Z||"..."}}let W=H,Q=f.content.map((Z)=>{if(Z.type!=="text"||W<=0)return Z;let j=U$(Z.text,W).trim();return W-=j.length,{...Z,text:j||"..."}});return{...f,content:Q}}function eA(f,$){let J=z7(f),H=cH(f),W=O7(f),Q=[];for(let Z=0;Z<f.length;Z+=1){let j=x7(f[Z]);if(!j)continue;Q.push({index:Z,message:j,estimatedTokens:$(j),isFirstUser:Z===J,isLastUser:Z===H,isLastAssistant:Z===W})}return Q}function I7(f,$,J,H){let W=f[$];W.message=J,W.estimatedTokens=H(J)}function j6(f,$,J,H){let W=c2(f.map((Q)=>Q.message),H);for(let Q=0;Q<f.length&&W>J;){if(!$(f[Q])){Q+=1;continue}W-=f[Q].estimatedTokens,f.splice(Q,1)}}function fR(f,$,J){let H=c2(f.map((Q)=>Q.message),J);if(H<=$)return;for(let Q=f.length-1;Q>=0&&H>$;Q-=1){let Z=f[Q];if(Z.isFirstUser)continue;let j=Math.max(T7,Z.estimatedTokens-(H-$));if(j>=Z.estimatedTokens)continue;I7(f,Q,m7(Z.message,j),J),H=c2(f.map((P)=>P.message),J)}if(H<=$)return;let W=f.findIndex((Q)=>Q.isFirstUser);if(W>=0){let Q=Math.max(1,f[W].estimatedTokens-(H-$));I7(f,W,m7(f[W].message,Q),J)}}function $R(f,$){return JSON.stringify(f)!==JSON.stringify($)}function g7(f){let $=Math.max(1,Math.min(f.context.triggerTokens,f.context.contextWindowTokens)),J=eA(f.context.messages,f.estimateMessageTokens);if(J.length===0)return;j6(J,(Z)=>Z.message.role==="assistant"&&!Z.isLastAssistant,$,f.estimateMessageTokens),j6(J,(Z)=>Z.message.role==="user"&&!Z.isFirstUser&&!Z.isLastUser,$,f.estimateMessageTokens),j6(J,(Z)=>Z.message.role==="assistant"&&Z.isLastAssistant,$,f.estimateMessageTokens),j6(J,(Z)=>Z.message.role==="user"&&Z.isLastUser&&!Z.isFirstUser,$,f.estimateMessageTokens),fR(J,$,f.estimateMessageTokens);let H=J.map((Z)=>Z.message);if(!$R(f.context.messages,H))return;let W=c2(f.context.messages.map((Z)=>x7(Z)??Z),f.estimateMessageTokens),Q=c2(H,f.estimateMessageTokens);return f.logger?.debug("Performed basic compaction",{messagesBefore:f.context.messages.length,messagesAfter:H.length,messagesRemoved:f.context.messages.length-H.length,tokensBefore:W,tokensAfter:Q,targetTokens:$,contextWindowTokens:f.context.contextWindowTokens}),{messages:H}}var JR={basic:({context:f,estimateMessageTokens:$,logger:J})=>g7({context:f,estimateMessageTokens:$,logger:J}),agentic:({context:f,providerConfig:$,compaction:J,mode:H,estimateMessageTokens:W,logger:Q})=>k7({context:f,providerConfig:$,summarizer:J?.summarizer,preserveRecentTokens:H==="manual"?Math.min(J?.preserveRecentTokens??vH,f.triggerTokens):J?.preserveRecentTokens??vH,estimateMessageTokens:W,logger:Q})};function HR(f){if(typeof f.config.reserveTokens==="number"){let H=Math.max(0,f.config.reserveTokens),W=Math.max(0,f.contextWindowTokens-H);return{shouldCompact:f.inputTokens>W,triggerTokens:W,thresholdRatio:f.contextWindowTokens>0?W/f.contextWindowTokens:0}}let $=f.config.thresholdRatio??h7,J=f.contextWindowTokens*$;return{shouldCompact:f.inputTokens>J,triggerTokens:J,thresholdRatio:$}}function WR(f){let $=typeof f.manualTargetRatio==="number"&&Number.isFinite(f.manualTargetRatio)?f.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,$)),H=Math.max(1,Math.floor(Math.min(f.autoTriggerTokens,f.inputTokens*J)));return{triggerTokens:H,thresholdRatio:f.contextWindowTokens>0?H/f.contextWindowTokens:0}}function d2(f,$={}){let J=f.compaction;if(J?.enabled!==!0)return;let H=f.providerConfig??{providerId:f.providerId,modelId:f.modelId},W=_7(),Q=J?.strategy??"basic",Z=JR[Q],j=$.mode??"auto";return async(P)=>{let X=P.apiMessages.reduce((F,K)=>F+W(K),0),V=J?.contextWindowTokens??P.model.info?.contextWindow??G7;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let Y=HR({inputTokens:X,contextWindowTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if(j==="auto"&&!Y.shouldCompact)return;let B=j==="manual"?WR({inputTokens:X,contextWindowTokens:V,autoTriggerTokens:Y.triggerTokens,manualTargetRatio:$.manualTargetRatio}):Y,A={agentId:P.agentId,conversationId:P.conversationId,parentAgentId:P.parentAgentId,iteration:P.iteration,messages:P.messages,model:P.model,contextWindowTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,utilizationRatio:V>0?X/V:0},R=j==="manual"?"manual_compaction":"auto_compaction";P.emitStatusNotice?.(j==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:P.iteration,triggerTokens:B.triggerTokens,contextWindowTokens:V});let U=P.messages.length,y=J?.compact?await J.compact(A):await Z({context:A,providerConfig:{...H,abortSignal:P.abortSignal},compaction:J,mode:j,estimateMessageTokens:W,logger:f.logger});if(y?.messages){let F=y.messages.reduce((K,M)=>K+W(M),0);f.logger?.log("Context compaction completed",{severity:"info",strategy:Q,contextWindowTokens:V,inputTokens:X,afterTokens:F,tokensSaved:X-F,utilizationBefore:`${(X/V*100).toFixed(1)}%`,utilizationAfter:`${(F/V*100).toFixed(1)}%`,thresholdTrigger:`${(B.thresholdRatio*100).toFixed(1)}%`,messagesBefore:U,messagesAfter:y.messages.length,messagesRemoved:U-y.messages.length})}return y}}var oQ={};N(oQ,{zodToJsonSchema:()=>Ky,validateWithZod:()=>yy,resolveToolRoutingConfig:()=>U1,resolveToolPresetName:()=>G0,resolveCoreSelectedToolIds:()=>G6,getCoreHeadlessToolNames:()=>Z8,getCoreDefaultEnabledToolIds:()=>U6,getCoreBuiltinToolCatalog:()=>O$,getCoreAcpToolNames:()=>h6,createWindowsShellTool:()=>sH,createWebFetchTool:()=>oH,createWebFetchExecutor:()=>W8,createToolPoliciesWithPreset:()=>B6,createSubmitAndExitTool:()=>JW,createSkillsTool:()=>h$,createSearchTool:()=>aH,createSearchExecutor:()=>H8,createReadFilesTool:()=>nH,createFileReadExecutor:()=>J8,createEditorTool:()=>fW,createEditorExecutor:()=>f8,createDefaultToolsWithPreset:()=>A6,createDefaultTools:()=>u0,createDefaultExecutors:()=>y1,createBuiltinTools:()=>N$,createBashTool:()=>tH,createBashExecutor:()=>e2,createAskQuestionTool:()=>$W,createApplyPatchTool:()=>eH,createApplyPatchExecutor:()=>o2,WebFetchRequestSchema:()=>pH,ToolPresets:()=>bf,TEAM_TOOL_NAMES:()=>D1,SubmitInputSchema:()=>s2,SkillsInputSchema:()=>a2,SearchCodebaseInputSchema:()=>l2,RunCommandsInputSchema:()=>A1,ReadFilesInputSchema:()=>r2,ReadFileRequestSchema:()=>I0,FetchWebContentInputSchema:()=>p2,EditFileInputSchema:()=>i2,DefaultToolNames:()=>ff,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>K1,AskQuestionInputSchema:()=>t2,ApplyPatchInputSchema:()=>n2,ALL_DEFAULT_TOOL_NAMES:()=>q0});import{validateWithZod as yy,zodToJsonSchema as Ky}from"@cline/shared";import{createTool as K0,validateWithZod as v0,zodToJsonSchema as f0}from"@cline/shared";import{validateWithZod as n7}from"@cline/shared";import{z as D}from"zod";var x0=6000,dH=D.string().describe("The absolute file path of a text file to read content from"),u7=D.object({start_line:D.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:D.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),I0=D.object({path:dH,start_line:u7.shape.start_line,end_line:u7.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),r2=D.object({files:D.array(I0).describe("Array of file read requests. Omit start_line/end_line or set them to null to return the full file content boundaries; provide integers to return only that inclusive one-based line range. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),c7=D.union([r2,I0,D.array(I0),D.array(D.string()),D.string(),D.object({files:I0}),D.object({file_paths:D.array(dH)}),D.object({file_paths:D.string()}),D.object({paths:D.array(D.union([dH,I0]))}),D.object({paths:I0}),D.object({paths:D.string()})]),l2=D.object({queries:D.array(D.string()).describe("Array of regex search queries to execute")}),d7=D.union([l2,D.array(D.string()),D.string(),D.object({queries:D.string()})]),G$=D.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${x0*2} characters) to avoid timeouts.`),A1=D.object({commands:D.array(G$).describe("Array of shell commands to execute")}),r7=D.union([A1,D.object({commands:G$}),D.object({command:G$}),D.object({cmd:G$}),D.array(D.string()),D.string()]),rH=D.object({command:D.string().min(1).describe("The executable to run directly without shell parsing."),args:D.array(D.string()).optional().describe("Optional argv list passed directly to the executable.")}),l7=D.union([G$,rH]),lH=D.object({commands:D.array(l7).describe("Array of commands to execute. Prefer structured { command, args } entries for portability; plain strings are still supported and are interpreted by the active shell.")}),p7=D.union([A1,lH,D.object({commands:l7}),D.array(rH),rH,D.object({command:G$}),D.object({cmd:G$}),D.array(D.string()),D.string()]),pH=D.object({url:D.string().describe("The URL to fetch"),prompt:D.string().min(2).describe("Analysis prompt for the fetched content")}),p2=D.object({requests:D.array(pH).describe("Array of the URLs for the web fetch requests")}),i2=D.object({path:D.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:D.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 ${x0} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:D.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 ${x0} 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:D.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."),n2=D.object({input:D.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."),i7=D.union([n2,D.string()]),a2=D.object({skill:D.string().min(1).describe("Name of the skill to execute."),args:D.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),t2=D.object({question:D.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:D.array(D.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),s2=D.object({summary:D.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:D.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.
316
+ ${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fileOps,tokensBefore:f.tokensBefore,generatedAt:Date.now()}}}async function TR(f){let $=GR(f.providerConfig),J="";for await(let W of $.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:f.request}])){if(W.type==="text"){J+=W.text;continue}if(W.type==="done"&&!W.success&&W.error)throw Error(W.error)}return f.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:f.providerConfig.modelId,providerId:f.providerConfig.providerId}),J.trim()}async function iQ(f){let $=f.context.messages;if($.length<2)return;let J=uQ($,f.preserveRecentTokens,f.estimateMessageTokens);if(J<=0||J>=$.length)return;let W=$.slice(0,J),H=vQ(W),Q=H>=0?d5(W[H])?.summary:void 0,Z=H>=0?W.slice(H+1):W;if(Z.length===0)return;let j=cQ(W),X=kQ(Z),A=await TR({providerConfig:lQ({activeProviderConfig:f.providerConfig,summarizer:f.summarizer}),request:rQ({previousSummary:Q,conversationText:X,fileOps:j}),logger:f.logger});if(!A.trim())return;let P=dQ(A,j),B=$.reduce((R,U)=>R+f.estimateMessageTokens(U),0),Y=[pQ({summary:P,fileOps:j,tokensBefore:B}),...$.slice(J)],V=Y.reduce((R,U)=>R+f.estimateMessageTokens(U),0);return f.logger?.debug("Performed agentic compaction",{messagesBefore:$.length,messagesAfter:Y.length,messagesSummarized:J,messagesPreserved:$.length-J,tokensBefore:B,tokensAfter:V,contextWindowTokens:f.context.contextWindowTokens}),{messages:Y}}function tQ(f){if(d2(f))return;if(typeof f.content==="string"){let J=f.content.trim();return J?{...f,content:J}:void 0}let $=f.content.filter((J)=>J.type!=="text"||J.text.trim());if($.length===0)return;return{...f,content:$.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J)}}function r2(f,$){return f.reduce((J,W)=>J+$(W),0)}function nQ(f,$){let J=Math.max(1,$),W=Math.max(16,J*4);if(typeof f.content==="string"){let Z=D$(f.content,W).trim();return{...f,content:Z||"..."}}let H=W,Q=f.content.map((Z)=>{if(Z.type!=="text"||H<=0)return Z;let j=D$(Z.text,H).trim();return H-=j.length,{...Z,text:j||"..."}});return{...f,content:Q}}function DR(f,$){let J=xQ(f),W=r5(f),H=gQ(f),Q=[];for(let Z=0;Z<f.length;Z+=1){let j=tQ(f[Z]);if(!j)continue;Q.push({index:Z,message:j,estimatedTokens:$(j),isFirstUser:Z===J,isLastUser:Z===W,isLastAssistant:Z===H})}return Q}function aQ(f,$,J,W){let H=f[$];H.message=J,H.estimatedTokens=W(J)}function V6(f,$,J,W){let H=r2(f.map((Q)=>Q.message),W);for(let Q=0;Q<f.length&&H>J;){if(!$(f[Q])){Q+=1;continue}H-=f[Q].estimatedTokens,f.splice(Q,1)}}function _R(f,$,J){let W=r2(f.map((Q)=>Q.message),J);if(W<=$)return;for(let Q=f.length-1;Q>=0&&W>$;Q-=1){let Z=f[Q];if(Z.isFirstUser)continue;let j=Math.max(EQ,Z.estimatedTokens-(W-$));if(j>=Z.estimatedTokens)continue;aQ(f,Q,nQ(Z.message,j),J),W=r2(f.map((X)=>X.message),J)}if(W<=$)return;let H=f.findIndex((Q)=>Q.isFirstUser);if(H>=0){let Q=Math.max(1,f[H].estimatedTokens-(W-$));aQ(f,H,nQ(f[H].message,Q),J)}}function MR(f,$){return JSON.stringify(f)!==JSON.stringify($)}function sQ(f){let $=Math.max(1,Math.min(f.context.triggerTokens,f.context.contextWindowTokens)),J=DR(f.context.messages,f.estimateMessageTokens);if(J.length===0)return;V6(J,(Z)=>Z.message.role==="assistant"&&!Z.isLastAssistant,$,f.estimateMessageTokens),V6(J,(Z)=>Z.message.role==="user"&&!Z.isFirstUser&&!Z.isLastUser,$,f.estimateMessageTokens),V6(J,(Z)=>Z.message.role==="assistant"&&Z.isLastAssistant,$,f.estimateMessageTokens),V6(J,(Z)=>Z.message.role==="user"&&Z.isLastUser&&!Z.isFirstUser,$,f.estimateMessageTokens),_R(J,$,f.estimateMessageTokens);let W=J.map((Z)=>Z.message);if(!MR(f.context.messages,W))return;let H=r2(f.context.messages.map((Z)=>tQ(Z)??Z),f.estimateMessageTokens),Q=r2(W,f.estimateMessageTokens);return f.logger?.debug("Performed basic compaction",{messagesBefore:f.context.messages.length,messagesAfter:W.length,messagesRemoved:f.context.messages.length-W.length,tokensBefore:H,tokensAfter:Q,targetTokens:$,contextWindowTokens:f.context.contextWindowTokens}),{messages:W}}var LR={basic:({context:f,estimateMessageTokens:$,logger:J})=>sQ({context:f,estimateMessageTokens:$,logger:J}),agentic:({context:f,providerConfig:$,compaction:J,mode:W,estimateMessageTokens:H,logger:Q})=>iQ({context:f,providerConfig:$,summarizer:J?.summarizer,preserveRecentTokens:W==="manual"?Math.min(J?.preserveRecentTokens??c5,f.triggerTokens):J?.preserveRecentTokens??c5,estimateMessageTokens:H,logger:Q})};function hR(f){if(typeof f.config.reserveTokens==="number"){let W=Math.max(0,f.config.reserveTokens),H=Math.max(0,f.contextWindowTokens-W);return{shouldCompact:f.inputTokens>H,triggerTokens:H,thresholdRatio:f.contextWindowTokens>0?H/f.contextWindowTokens:0}}let $=f.config.thresholdRatio??CQ,J=f.contextWindowTokens*$;return{shouldCompact:f.inputTokens>J,triggerTokens:J,thresholdRatio:$}}function OR(f){let $=typeof f.manualTargetRatio==="number"&&Number.isFinite(f.manualTargetRatio)?f.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,$)),W=Math.max(1,Math.floor(Math.min(f.autoTriggerTokens,f.inputTokens*J)));return{triggerTokens:W,thresholdRatio:f.contextWindowTokens>0?W/f.contextWindowTokens:0}}function l2(f,$={}){let J=f.compaction;if(J?.enabled!==!0)return;let W=f.providerConfig??{providerId:f.providerId,modelId:f.modelId},H=IQ(),Q=J?.strategy??"basic",Z=LR[Q],j=$.mode??"auto";return async(X)=>{let A=X.apiMessages.reduce((F,y)=>F+H(y),0),P=J?.contextWindowTokens??X.model.info?.contextWindow??bQ;if(typeof P!=="number"||!Number.isFinite(P)||P<=0)return;let B=hR({inputTokens:A,contextWindowTokens:P,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if(j==="auto"&&!B.shouldCompact)return;let Y=j==="manual"?OR({inputTokens:A,contextWindowTokens:P,autoTriggerTokens:B.triggerTokens,manualTargetRatio:$.manualTargetRatio}):B,V={agentId:X.agentId,conversationId:X.conversationId,parentAgentId:X.parentAgentId,iteration:X.iteration,messages:X.messages,model:X.model,contextWindowTokens:P,triggerTokens:Y.triggerTokens,thresholdRatio:Y.thresholdRatio,utilizationRatio:P>0?A/P:0},R=j==="manual"?"manual_compaction":"auto_compaction";X.emitStatusNotice?.(j==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:X.iteration,triggerTokens:Y.triggerTokens,contextWindowTokens:P});let U=X.messages.length,K=J?.compact?await J.compact(V):await Z({context:V,providerConfig:{...W,abortSignal:X.abortSignal},compaction:J,mode:j,estimateMessageTokens:H,logger:f.logger});if(K?.messages){let F=K.messages.reduce((y,D)=>y+H(D),0);f.logger?.log("Context compaction completed",{severity:"info",strategy:Q,contextWindowTokens:P,inputTokens:A,afterTokens:F,tokensSaved:A-F,utilizationBefore:`${(A/P*100).toFixed(1)}%`,utilizationAfter:`${(F/P*100).toFixed(1)}%`,thresholdTrigger:`${(Y.thresholdRatio*100).toFixed(1)}%`,messagesBefore:U,messagesAfter:K.messages.length,messagesRemoved:U-K.messages.length})}return K}}var BZ={};N(BZ,{zodToJsonSchema:()=>gK,validateWithZod:()=>xK,resolveToolRoutingConfig:()=>T1,resolveToolPresetName:()=>L0,resolveCoreSelectedToolIds:()=>L6,getCoreHeadlessToolNames:()=>X8,getCoreDefaultEnabledToolIds:()=>M6,getCoreBuiltinToolCatalog:()=>w$,getCoreAcpToolNames:()=>h6,createWindowsShellTool:()=>e5,createWebFetchTool:()=>fW,createWebFetchExecutor:()=>Z8,createToolPoliciesWithPreset:()=>U6,createSubmitAndExitTool:()=>HW,createSkillsTool:()=>M$,createSearchTool:()=>s5,createSearchExecutor:()=>Q8,createReadFilesTool:()=>t5,createFileReadExecutor:()=>H8,createEditorTool:()=>JW,createEditorExecutor:()=>J8,createDefaultToolsWithPreset:()=>G6,createDefaultTools:()=>i0,createDefaultExecutors:()=>U1,createBuiltinTools:()=>b$,createBashTool:()=>o5,createBashExecutor:()=>$8,createAskQuestionTool:()=>WW,createApplyPatchTool:()=>$W,createApplyPatchExecutor:()=>f8,WebFetchRequestSchema:()=>n5,ToolPresets:()=>kf,TEAM_TOOL_NAMES:()=>L1,SubmitInputSchema:()=>e2,SkillsInputSchema:()=>s2,SearchCodebaseInputSchema:()=>i2,RunCommandsInputSchema:()=>F1,ReadFilesInputSchema:()=>p2,ReadFileRequestSchema:()=>d0,FetchWebContentInputSchema:()=>n2,EditFileInputSchema:()=>a2,DefaultToolNames:()=>Jf,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>G1,AskQuestionInputSchema:()=>o2,ApplyPatchInputSchema:()=>t2,ALL_DEFAULT_TOOL_NAMES:()=>k0});import{validateWithZod as xK,zodToJsonSchema as gK}from"@cline/shared";import{createTool as _0,validateWithZod as p0,zodToJsonSchema as $0}from"@cline/shared";import{validateWithZod as Z7}from"@cline/shared";import{z as G}from"zod";var r0=6000,l5=G.string().describe("The absolute file path of a text file to read content from"),eQ=G.object({start_line:G.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:G.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),d0=G.object({path:l5,start_line:eQ.shape.start_line,end_line:eQ.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),p2=G.object({files:G.array(d0).describe("Array of file read requests. Omit start_line/end_line or set them to null to return the full file content boundaries; provide integers to return only that inclusive one-based line range. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),f7=G.union([p2,d0,G.array(d0),G.array(G.string()),G.string(),G.object({files:d0}),G.object({file_paths:G.array(l5)}),G.object({file_paths:G.string()}),G.object({paths:G.array(G.union([l5,d0]))}),G.object({paths:d0}),G.object({paths:G.string()})]),i2=G.object({queries:G.array(G.string()).describe("Array of regex search queries to execute")}),$7=G.union([i2,G.array(G.string()),G.string(),G.object({queries:G.string()})]),_$=G.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${r0*2} characters) to avoid timeouts.`),F1=G.object({commands:G.array(_$).describe("Array of shell commands to execute")}),J7=G.union([F1,G.object({commands:_$}),G.object({command:_$}),G.object({cmd:_$}),G.array(G.string()),G.string()]),p5=G.object({command:G.string().min(1).describe("The executable to run directly without shell parsing."),args:G.array(G.string()).optional().describe("Optional argv list passed directly to the executable.")}),W7=G.union([_$,p5]),i5=G.object({commands:G.array(W7).describe("Array of commands to execute. Prefer structured { command, args } entries for portability; plain strings are still supported and are interpreted by the active shell.")}),H7=G.union([F1,i5,G.object({commands:W7}),G.array(p5),p5,G.object({command:_$}),G.object({cmd:_$}),G.array(G.string()),G.string()]),n5=G.object({url:G.string().describe("The URL to fetch"),prompt:G.string().min(2).describe("Analysis prompt for the fetched content")}),n2=G.object({requests:G.array(n5).describe("Array of the URLs for the web fetch requests")}),a2=G.object({path:G.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:G.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 ${r0} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:G.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 ${r0} 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:G.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."),t2=G.object({input:G.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."),Q7=G.union([t2,G.string()]),s2=G.object({skill:G.string().min(1).describe("Name of the skill to execute."),args:G.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),o2=G.object({question:G.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:G.array(G.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),e2=G.object({summary:G.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:G.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.
317
317
  'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
318
- 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 g0(f){if(f instanceof Error)return f.message;return String(f)}function a7(f){if(typeof f.old_text==="string"&&f.old_text.length>x0)return`Editor input too large: old_text was ${f.old_text.length} characters, exceeding the recommended limit of ${x0}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if(f.new_text.length>x0)return`Editor input too large: new_text was ${f.new_text.length} characters, exceeding the recommended limit of ${x0}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}function ef(f,$,J){return Promise.race([f,new Promise((H,W)=>{setTimeout(()=>W(Error(J)),$)})])}function t7(f){let $=n7(c7,f);if(typeof $==="string")return[{path:$}];if(Array.isArray($))return $.map((J)=>typeof J==="string"?{path:J}:J);if("files"in $)return Array.isArray($.files)?$.files:[$.files];if("file_paths"in $)return(Array.isArray($.file_paths)?$.file_paths:[$.file_paths]).map((H)=>({path:H}));if("paths"in $)return(Array.isArray($.paths)?$.paths:[$.paths]).map((H)=>typeof H==="string"?{path:H}:H);return[$]}function P6(f){let{path:$,start_line:J,end_line:H}=f;if(J==null&&H==null)return $;return`${$}:${J??1}-${H??"EOF"}`}function s7(f){let{start_line:$,end_line:J}=f;if($==null||J==null||$<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${$}, end_line: ${J})`}function o7(f){let $=n7(p7,f);if(typeof $==="string")return[$];if(Array.isArray($))return $;if("commands"in $)return Array.isArray($.commands)?$.commands:[$.commands];if("command"in $)return"args"in $?[$]:[$.command];if("cmd"in $)return[$.cmd];return[$]}function iH(f){if(typeof f==="string")return f;let $=f.args??[];if($.length===0)return f.command;let J=$.map((H)=>/[\s"]/u.test(H)?JSON.stringify(H):H);return`${f.command} ${J.join(" ")}`}function nH(f,$={}){let J=$.fileReadTimeoutMs??1e4;return K0({name:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Returns file contents or error messages for each path.",inputSchema:f0(r2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(H,W)=>{let Q=t7(H);return Promise.all(Q.map(async(Z)=>{let j=s7(Z);if(j)return{query:P6(Z),result:"",error:`Invalid file range: ${j}`,success:!1};try{let P=await ef(f(Z,W),J,`File read timed out after ${J}ms`);return{query:P6(Z),result:P,success:!0}}catch(P){let X=g0(P);return{query:P6(Z),result:"",error:`Error reading file: ${X}`,success:!1}}}))}})}function aH(f,$={}){let J=$.searchTimeoutMs??30000,H=$.cwd??process.cwd();return K0({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:f0(l2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(W,Q)=>{let Z=v0(d7,W),j=Array.isArray(Z)?Z:typeof Z==="object"?Array.isArray(Z.queries)?Z.queries:[Z.queries]:[Z];return Promise.all(j.map(async(P)=>{try{let X=await ef(f(P,H,Q),J,`Search timed out after ${J}ms`),V=X.length>0&&!X.includes("No results found");return{query:P,result:X,success:V}}catch(X){let V=g0(X);return{query:P,result:"",error:`Search failed: ${V}`,success:!1}}}))}})}function tH(f,$={}){let J=$.bashTimeoutMs??30000,H=$.cwd??process.cwd();return K0({name:"run_commands",description:"Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped.",inputSchema:f0(A1),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(W,Q)=>{let Z=v0(r7,W),j;if(typeof Z==="string")j=[Z];else if(Array.isArray(Z))j=Z;else if("commands"in Z)j=Array.isArray(Z.commands)?Z.commands:[Z.commands];else if("command"in Z)j=[Z.command];else j=[Z.cmd];return Promise.all(j.map(async(P)=>{try{let X=await ef(f(P,H,Q),J,`Command timed out after ${J}ms`);return{query:P,result:X,success:!0}}catch(X){let V=g0(X);return{query:P,result:"",error:`Command failed: ${V}`,success:!1}}}))}})}function sH(f,$={}){let J=$.bashTimeoutMs??30000,H=$.cwd??process.cwd();return K0({name:"run_commands",description:"Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped.",inputSchema:f0(lH),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(W,Q)=>{let Z=o7(W);return Promise.all(Z.map(async(j)=>{try{let P=await ef(f(j,H,Q),J,`Command timed out after ${J}ms`);return{query:iH(j),result:P,success:!0}}catch(P){let X=g0(P);return{query:iH(j),result:"",error:`Command failed: ${X}`,success:!1}}}))}})}function oH(f,$={}){let J=$.webFetchTimeoutMs??30000;return K0({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract.",inputSchema:f0(p2),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(H,W)=>{let Q=v0(p2,H);return Promise.all(Q.requests.map(async(Z)=>{try{let j=await ef(f(Z.url,Z.prompt,W),J,`Web fetch timed out after ${J}ms`);return{query:Z.url,result:j,success:!0}}catch(j){let P=g0(j);return{query:Z.url,result:"",error:`Error fetching web content: ${P}`,success:!1}}}))}})}var QR=`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:
318
+ 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 l0(f){if(f instanceof Error)return f.message;return String(f)}function j7(f){if(typeof f.old_text==="string"&&f.old_text.length>r0)return`Editor input too large: old_text was ${f.old_text.length} characters, exceeding the recommended limit of ${r0}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if(f.new_text.length>r0)return`Editor input too large: new_text was ${f.new_text.length} characters, exceeding the recommended limit of ${r0}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}function f0(f,$,J){return Promise.race([f,new Promise((W,H)=>{setTimeout(()=>H(Error(J)),$)})])}function X7(f){let $=Z7(f7,f);if(typeof $==="string")return[{path:$}];if(Array.isArray($))return $.map((J)=>typeof J==="string"?{path:J}:J);if("files"in $)return Array.isArray($.files)?$.files:[$.files];if("file_paths"in $)return(Array.isArray($.file_paths)?$.file_paths:[$.file_paths]).map((W)=>({path:W}));if("paths"in $)return(Array.isArray($.paths)?$.paths:[$.paths]).map((W)=>typeof W==="string"?{path:W}:W);return[$]}function R6(f){let{path:$,start_line:J,end_line:W}=f;if(J==null&&W==null)return $;return`${$}:${J??1}-${W??"EOF"}`}function A7(f){let{start_line:$,end_line:J}=f;if($==null||J==null||$<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${$}, end_line: ${J})`}function P7(f){let $=Z7(H7,f);if(typeof $==="string")return[$];if(Array.isArray($))return $;if("commands"in $)return Array.isArray($.commands)?$.commands:[$.commands];if("command"in $)return"args"in $?[$]:[$.command];if("cmd"in $)return[$.cmd];return[$]}function a5(f){if(typeof f==="string")return f;let $=f.args??[];if($.length===0)return f.command;let J=$.map((W)=>/[\s"]/u.test(W)?JSON.stringify(W):W);return`${f.command} ${J.join(" ")}`}function t5(f,$={}){let J=$.fileReadTimeoutMs??1e4;return _0({name:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Returns file contents or error messages for each path.",inputSchema:$0(p2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(W,H)=>{let Q=X7(W);return Promise.all(Q.map(async(Z)=>{let j=A7(Z);if(j)return{query:R6(Z),result:"",error:`Invalid file range: ${j}`,success:!1};try{let X=await f0(f(Z,H),J,`File read timed out after ${J}ms`);return{query:R6(Z),result:X,success:!0}}catch(X){let A=l0(X);return{query:R6(Z),result:"",error:`Error reading file: ${A}`,success:!1}}}))}})}function s5(f,$={}){let J=$.searchTimeoutMs??30000,W=$.cwd??process.cwd();return _0({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:$0(i2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(H,Q)=>{let Z=p0($7,H),j=Array.isArray(Z)?Z:typeof Z==="object"?Array.isArray(Z.queries)?Z.queries:[Z.queries]:[Z];return Promise.all(j.map(async(X)=>{try{let A=await f0(f(X,W,Q),J,`Search timed out after ${J}ms`),P=A.length>0&&!A.includes("No results found");return{query:X,result:A,success:P}}catch(A){let P=l0(A);return{query:X,result:"",error:`Search failed: ${P}`,success:!1}}}))}})}function o5(f,$={}){let J=$.bashTimeoutMs??30000,W=$.cwd??process.cwd();return _0({name:"run_commands",description:"Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped.",inputSchema:$0(F1),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=p0(J7,H),j;if(typeof Z==="string")j=[Z];else if(Array.isArray(Z))j=Z;else if("commands"in Z)j=Array.isArray(Z.commands)?Z.commands:[Z.commands];else if("command"in Z)j=[Z.command];else j=[Z.cmd];return Promise.all(j.map(async(X)=>{try{let A=await f0(f(X,W,Q),J,`Command timed out after ${J}ms`);return{query:X,result:A,success:!0}}catch(A){let P=l0(A);return{query:X,result:"",error:`Command failed: ${P}`,success:!1}}}))}})}function e5(f,$={}){let J=$.bashTimeoutMs??30000,W=$.cwd??process.cwd();return _0({name:"run_commands",description:"Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped.",inputSchema:$0(i5),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=P7(H);return Promise.all(Z.map(async(j)=>{try{let X=await f0(f(j,W,Q),J,`Command timed out after ${J}ms`);return{query:a5(j),result:X,success:!0}}catch(X){let A=l0(X);return{query:a5(j),result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function fW(f,$={}){let J=$.webFetchTimeoutMs??30000;return _0({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract.",inputSchema:$0(n2),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(W,H)=>{let Q=p0(n2,W);return Promise.all(Q.requests.map(async(Z)=>{try{let j=await f0(f(Z.url,Z.prompt,H),J,`Web fetch timed out after ${J}ms`);return{query:Z.url,result:j,success:!0}}catch(j){let X=l0(j);return{query:Z.url,result:"",error:`Error fetching web content: ${X}`,success:!1}}}))}})}var zR=`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:
319
319
 
320
320
  *** Begin Patch
321
321
  *** Update File: path/to/file.ts
@@ -351,68 +351,68 @@ Example:
351
351
  </div>
352
352
  );
353
353
  }
354
- *** End Patch`;function eH(f,$={}){let J=$.applyPatchTimeoutMs??30000,H=$.cwd??process.cwd();return K0({name:"apply_patch",description:QR,inputSchema:f0(n2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,Q)=>{let Z=v0(i7,W),j=typeof Z==="string"?Z:Z.input;try{return{query:"apply_patch",result:await ef(f({input:j},H,Q),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(P){return{query:"apply_patch",result:"",error:`apply_patch failed: ${g0(P)}`,success:!1}}}})}function fW(f,$={}){let J=$.editorTimeoutMs??30000,H=$.cwd??process.cwd();return K0({name:"editor",description:"An editor for controlled filesystem edits on the text file at the provided path. Provide `insert_line` to insert `new_text` at a specific line number. Otherwise, the tool replaces `old_text` with `new_text`, or creates the file with `new_text` if file does not exist. Use this tools for making small, precise edits to existing files or creating new files over shell commands.",inputSchema:f0(i2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,Q)=>{let Z=v0(i2,W),j=Z.insert_line==null?"edit":"insert",P=a7(Z);if(P)return{query:`${j}:${Z.path}`,result:"",error:P,success:!1};try{let X=await ef(f(Z,H,Q),J,`Editor operation timed out after ${J}ms`);return{query:`${j}:${Z.path}`,result:X,success:!0}}catch(X){let V=g0(X);return{query:`${j}:${Z.path}`,result:"",error:`Editor operation failed: ${V}`,success:!1}}}})}function h$(f,$={}){let J=$.skillsTimeoutMs??15000,H='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',W=K0({name:"skills",description:H,inputSchema:f0(a2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,Z)=>{let j=v0(a2,Q);return ef(f(j.skill,j.args||void 0,Z),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(W,"description",{get(){let Q=f.configuredSkills?.filter((Z)=>!Z.disabled).map((Z)=>Z.name);if(Q&&Q.length>0)return`${H} Available skills: ${Q.join(", ")}.`;return H},enumerable:!0,configurable:!0}),W}function $W(f){return{name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:f0(t2),retryable:!1,maxRetries:0,execute:async($,J)=>{let H=v0(t2,$);return f(H.question,H.options,J)}}}function JW(f,$={}){let J=$.submitTimeoutMs??15000;return K0({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. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:f0(s2),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(H,W)=>{let Q=v0(s2,H);return ef(f(Q.summary,Q.verified,W),J,`submit_and_exit timed out after ${J}ms`)}})}function u0(f){let{executors:$,enableReadFiles:J=!0,enableSearch:H=!0,enableBash:W=!0,enableWebFetch:Q=!0,enableApplyPatch:Z=!1,enableEditor:j=!0,enableSkills:P=!0,enableAskQuestion:X=!0,enableSubmitAndExit:V=!1,...Y}=f,B=[];if(J&&$.readFile)B.push(nH($.readFile,Y));if(H&&$.search)B.push(aH($.search,Y));if(W&&$.bash)if(process.platform==="win32")B.push(sH($.bash,Y));else B.push(tH($.bash,Y));if(Q&&$.webFetch)B.push(oH($.webFetch,Y));if(j&&$.editor)B.push(fW($.editor,Y));else if(Z&&$.applyPatch)B.push(eH($.applyPatch,Y));if(P&&$.skills)B.push(h$($.skills,Y));let A=V?$.submit:void 0;if(X&&$.askQuestion&&!A)B.push($W($.askQuestion));if(A)B.push(JW(A,Y));return B}import*as Nf from"node:fs/promises";import*as qf from"node:path";var I={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},fQ=["%%bash","apply_patch","EOF","```"];class Jf extends Error{constructor(f){super(f);this.name="DiffError"}}function Of(f){let $={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return f.normalize("NFC").replace(/./gu,(J)=>$[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class HW{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor(f,$){this.lines=f;this.currentFiles=$}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning(f){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push(f)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(I.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(I.END)??!1}parseNextAction(){let f=this.lines[this.index];if(f?.startsWith(I.UPDATE)){this.parseUpdate(f.substring(I.UPDATE.length).trim());return}if(f?.startsWith(I.DELETE)){this.parseDelete(f.substring(I.DELETE.length).trim());return}if(f?.startsWith(I.ADD)){this.parseAdd(f.substring(I.ADD.length).trim());return}throw new Jf(`Unknown line while parsing: ${f}`)}checkDuplicate(f,$){if(f in this.patch.actions)throw new Jf(`Duplicate ${$} for file: ${f}`)}parseUpdate(f){this.checkDuplicate(f,"update"),this.currentPath=f,this.index++;let $=this.lines[this.index]?.startsWith(I.MOVE)?(this.lines[this.index++]??"").substring(I.MOVE.length).trim():void 0;if(!(f in this.currentFiles))throw new Jf(`Update File Error: Missing File: ${f}`);let J=this.currentFiles[f]??"",H=this.parseUpdateFile(J,f);H.movePath=$,this.patch.actions[f]=H,this.currentPath=void 0}parseUpdateFile(f,$){let J={type:"update",chunks:[]},H=f.split(`
355
- `),W=0,Q=[I.END,I.UPDATE,I.DELETE,I.ADD,I.END_FILE];while(!Q.some((Z)=>this.lines[this.index]?.startsWith(Z.trim()))){let Z=this.lines[this.index],j=Z?.startsWith("@@ ")?Z.substring(3):void 0;if(j!==void 0||(Z==="@@"?Z:void 0)!==void 0)this.index++;else if(W!==0)throw new Jf(`Invalid Line:
356
- ${this.lines[this.index]}`);if(j?.trim()){let y=Of(j.trim());for(let F=W;F<H.length;F++){let K=H[F];if(K&&(Of(K)===y||Of(K.trim())===y)){if(W=F+1,Of(K.trim())===y&&Of(K)!==y)this.fuzz++;break}}}let[X,V,Y,B]=PR(this.lines,this.index),[A,R,U]=jR(H,X,W,B);if(A===-1){let y=X.join(`
357
- `);this.addWarning({path:this.currentPath||$,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${U.toFixed(2)}). Chunk skipped.`,context:y.length>200?`${y.substring(0,200)}...`:y}),this.index=Y}else{this.fuzz+=R;for(let y of V)y.origIndex+=A,J.chunks.push(y);W=A+X.length,this.index=Y}}return J}parseDelete(f){if(this.checkDuplicate(f,"delete"),!(f in this.currentFiles))throw new Jf(`Delete File Error: Missing File: ${f}`);this.patch.actions[f]={type:"delete",chunks:[]},this.index++}parseAdd(f){if(this.checkDuplicate(f,"add"),f in this.currentFiles)throw new Jf(`Add File Error: File already exists: ${f}`);this.index++;let $=[],J=[I.END,I.UPDATE,I.DELETE,I.ADD];while(this.hasMoreLines()&&!J.some((H)=>this.lines[this.index]?.startsWith(H.trim()))){let H=this.lines[this.index++];if(H===void 0)break;if(!H.startsWith("+"))throw new Jf(`Invalid Add File line (missing '+'): ${H}`);$.push(H.substring(1))}this.patch.actions[f]={type:"add",newFile:$.join(`
358
- `),chunks:[]}}}function e7(f,$){let J=f.length>$.length?f:$,H=f.length>$.length?$:f;if(J.length===0)return 1;let W=ZR(H,J);return(J.length-W)/J.length}function ZR(f,$){let J=$.length+1,H=f.length+1,W=Array(J*H).fill(0),Q=(j,P)=>W[j*H+P]??0,Z=(j,P,X)=>{W[j*H+P]=X};for(let j=0;j<=$.length;j++)Z(j,0,j);for(let j=0;j<=f.length;j++)Z(0,j,j);for(let j=1;j<=$.length;j++)for(let P=1;P<=f.length;P++)if($[j-1]===f[P-1])Z(j,P,Q(j-1,P-1));else Z(j,P,1+Math.min(Q(j-1,P-1),Q(j,P-1),Q(j-1,P)));return Q($.length,f.length)}function jR(f,$,J,H){if($.length===0)return[J,0,1];let W=0,Q=(Z)=>{let j=Of($.join(`
359
- `));for(let X=Z;X<f.length;X++){let V=Of(f.slice(X,X+$.length).join(`
360
- `));if(V===j)return[X,0,1];let Y=e7(V,j);if(Y>W)W=Y}for(let X=Z;X<f.length;X++){let V=Of(f.slice(X,X+$.length).map((B)=>B.trimEnd()).join(`
361
- `)),Y=Of($.map((B)=>B.trimEnd()).join(`
362
- `));if(V===Y)return[X,1,1]}for(let X=Z;X<f.length;X++){let V=Of(f.slice(X,X+$.length).map((B)=>B.trim()).join(`
363
- `)),Y=Of($.map((B)=>B.trim()).join(`
364
- `));if(V===Y)return[X,100,1]}let P=0.66;for(let X=Z;X<f.length;X++){let V=Of(f.slice(X,X+$.length).join(`
365
- `)),Y=e7(V,j);if(Y>=P)return[X,1000,Y];if(Y>W)W=Y}return[-1,0,W]};if(H){let[Z,j,P]=Q(f.length-$.length);if(Z!==-1)return[Z,j,P];return[Z,j,P]=Q(J),[Z,j+1e4,P]}return Q(J)}function PR(f,$){let J=$,H=[],W=[],Q=[],Z=[],j="keep",P=["@@",I.END,I.UPDATE,I.DELETE,I.ADD,I.END_FILE];while(J<f.length){let X=f[J];if(!X||P.some((B)=>X.startsWith(B.trim())))break;if(X==="***")break;if(X.startsWith("***"))throw new Jf(`Invalid line: ${X}`);J++;let V=j,Y=X;if(Y[0]==="+")j="add";else if(Y[0]==="-")j="delete";else if(Y[0]===" ")j="keep";else j="keep",Y=` ${Y}`;if(Y=Y.slice(1),j==="keep"&&V!==j){if(Q.length||W.length)Z.push({origIndex:H.length-W.length,delLines:W,insLines:Q});W=[],Q=[]}if(j==="delete")W.push(Y),H.push(Y);else if(j==="add")Q.push(Y);else H.push(Y)}if(Q.length||W.length)Z.push({origIndex:H.length-W.length,delLines:W,insLines:Q});if(J<f.length&&f[J]===I.END_FILE)return J++,[H,Z,J,!0];return[H,Z,J,!1]}function WW(f,$,J){let H=qf.isAbsolute($),W=H?qf.normalize($):qf.resolve(f,$);if(!J||H)return W;let Q=qf.relative(f,W);if(Q.startsWith("..")||qf.isAbsolute(Q))throw new Jf(`Path must stay within cwd: ${$}`);return W}function XR(f){return f.split(`
366
- `).map(($)=>$.replace(/\r$/,""))}function $Q(f){if(f.trim()==="")return!1;return fQ.some(($)=>f.startsWith($))}function VR(f){let $=0,J=f.length;while($<J&&$Q(f[$]??""))$++;while(J>$&&$Q(f[J-1]??""))J--;return f.slice($,J)}function YR(f){let $=XR(f),J=$.findIndex((Z)=>Z.startsWith(I.BEGIN)),H=-1;for(let Z=$.length-1;Z>=0;Z--)if($[Z]?.startsWith(I.END)){H=Z;break}if(J!==-1||H!==-1){if(J===-1||H===-1||H<J)throw new Jf("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:$.slice(J,H+1)}}let W=VR($);while(W.length>0&&W[0]==="")W.shift();while(W.length>0&&W[W.length-1]==="")W.pop();return{lines:[I.BEGIN,...W,I.END]}}function BR(f,$){let J=new Set;for(let H of f)for(let W of $)if(H.startsWith(W)){J.add(H.substring(W.length).trim());break}return[...J]}function AR(f,$,J){if($.length===0)return f;let H=f.split(`
367
- `),W=[],Q=0;for(let Z of $){if(Z.origIndex>H.length)throw new Jf(`${J}: chunk.origIndex ${Z.origIndex} > lines.length ${H.length}`);if(Q>Z.origIndex)throw new Jf(`${J}: currentIndex ${Q} > chunk.origIndex ${Z.origIndex}`);W.push(...H.slice(Q,Z.origIndex)),W.push(...Z.insLines),Q=Z.origIndex+Z.delLines.length}return W.push(...H.slice(Q)),W.join(`
368
- `)}async function RR(f,$,J,H){let W=BR(f,[I.UPDATE,I.DELETE]),Q={};for(let Z of W){let j=WW($,Z,H),P;try{P=await Nf.readFile(j,J)}catch{throw new Jf(`File not found: ${Z}`)}Q[Z]=P.replace(/\r\n/g,`
369
- `)}return Q}function FR(f,$){let J={};for(let[H,W]of Object.entries(f.actions))switch(W.type){case"delete":J[H]={type:"delete",oldContent:$[H]};break;case"add":if(W.newFile===void 0)throw new Jf("ADD action without file content");J[H]={type:"add",newContent:W.newFile};break;case"update":J[H]={type:"update",oldContent:$[H],newContent:AR($[H]??"",W.chunks,H),movePath:W.movePath};break}return J}async function yR(f,$,J,H){let W=[];for(let[Q,Z]of Object.entries(f)){let j=WW($,Q,H);switch(Z.type){case"delete":await Nf.rm(j,{force:!0}),W.push(`${Q}: [deleted]`);break;case"add":if(Z.newContent===void 0)throw new Jf(`Cannot create ${Q} with no content`);await Nf.mkdir(qf.dirname(j),{recursive:!0}),await Nf.writeFile(j,Z.newContent,{encoding:J}),W.push(Q);break;case"update":{if(Z.newContent===void 0)throw new Jf(`UPDATE change for ${Q} has no new content`);if(Z.movePath){let P=WW($,Z.movePath,H);await Nf.mkdir(qf.dirname(P),{recursive:!0}),await Nf.writeFile(P,Z.newContent,{encoding:J}),await Nf.rm(j,{force:!0}),W.push(`${Q} -> ${Z.movePath}`)}else await Nf.writeFile(j,Z.newContent,{encoding:J}),W.push(Q);break}}}return W}function o2(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0}=f;return async(H,W,Q)=>{let Z=YR(H.input),j=await RR(Z.lines,W,$,J),P=new HW(Z.lines,j),{patch:X,fuzz:V}=P.parse(),Y=FR(X,j),B=await yR(Y,W,$,J),A=["Successfully applied patch to the following files:"];for(let R of B)A.push(R);if(V>0)A.push(`Note: Patch applied with fuzz factor ${V}`);if(X.warnings&&X.warnings.length>0)for(let R of X.warnings)A.push(`Warning (${R.path}): ${R.message}`);return A.join(`
370
- `)}}import{spawn as JQ}from"node:child_process";import{getDefaultShell as KR,getShellArgs as UR}from"@cline/shared";function GR(f,$,J,H,W){return new Promise((Q,Z)=>{let j=process.platform==="win32",P=JQ(f.executable,f.args,{cwd:f.cwd,env:{...process.env,...f.env},stdio:["pipe","pipe","pipe"],detached:!j}),X=P.pid,V="",Y="",B=0,A=!1,R=!1,U=(G)=>{if(R)return;R=!0,G()},y=()=>{if(!X)return;if(j){JQ("taskkill",["/pid",String(X),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-X,"SIGKILL")}catch{P.kill("SIGKILL")}},F=(G)=>{A=!0,y(),U(()=>Z(G))},K=setTimeout(()=>F(Error(`Command timed out after ${J}ms`)),J),M=()=>F(Error("Command was aborted"));if($.signal)$.signal.addEventListener("abort",M);let T=()=>{clearTimeout(K),$.signal?.removeEventListener("abort",M)};P.stdout?.on("data",(G)=>{if(B+=G.length,B<=H)V+=G.toString()}),P.stderr?.on("data",(G)=>{if(B+=G.length,B<=H)Y+=G.toString()}),P.on("close",(G)=>{if(T(),A)return;let h=W?V+(Y?`
354
+ *** End Patch`;function $W(f,$={}){let J=$.applyPatchTimeoutMs??30000,W=$.cwd??process.cwd();return _0({name:"apply_patch",description:zR,inputSchema:$0(t2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=p0(Q7,H),j=typeof Z==="string"?Z:Z.input;try{return{query:"apply_patch",result:await f0(f({input:j},W,Q),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(X){return{query:"apply_patch",result:"",error:`apply_patch failed: ${l0(X)}`,success:!1}}}})}function JW(f,$={}){let J=$.editorTimeoutMs??30000,W=$.cwd??process.cwd();return _0({name:"editor",description:"An editor for controlled filesystem edits on the text file at the provided path. Provide `insert_line` to insert `new_text` at a specific line number. Otherwise, the tool replaces `old_text` with `new_text`, or creates the file with `new_text` if file does not exist. Use this tools for making small, precise edits to existing files or creating new files over shell commands.",inputSchema:$0(a2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=p0(a2,H),j=Z.insert_line==null?"edit":"insert",X=j7(Z);if(X)return{query:`${j}:${Z.path}`,result:"",error:X,success:!1};try{let A=await f0(f(Z,W,Q),J,`Editor operation timed out after ${J}ms`);return{query:`${j}:${Z.path}`,result:A,success:!0}}catch(A){let P=l0(A);return{query:`${j}:${Z.path}`,result:"",error:`Editor operation failed: ${P}`,success:!1}}}})}function M$(f,$={}){let J=$.skillsTimeoutMs??15000,W='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',H=_0({name:"skills",description:W,inputSchema:$0(s2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,Z)=>{let j=p0(s2,Q);return f0(f(j.skill,j.args||void 0,Z),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(H,"description",{get(){let Q=f.configuredSkills?.filter((Z)=>!Z.disabled).map((Z)=>Z.name);if(Q&&Q.length>0)return`${W} Available skills: ${Q.join(", ")}.`;return W},enumerable:!0,configurable:!0}),H}function WW(f){return{name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:$0(o2),retryable:!1,maxRetries:0,execute:async($,J)=>{let W=p0(o2,$);return f(W.question,W.options,J)}}}function HW(f,$={}){let J=$.submitTimeoutMs??15000;return _0({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. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:$0(e2),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,H)=>{let Q=p0(e2,W);return f0(f(Q.summary,Q.verified,H),J,`submit_and_exit timed out after ${J}ms`)}})}function i0(f){let{executors:$,enableReadFiles:J=!0,enableSearch:W=!0,enableBash:H=!0,enableWebFetch:Q=!0,enableApplyPatch:Z=!1,enableEditor:j=!0,enableSkills:X=!0,enableAskQuestion:A=!0,enableSubmitAndExit:P=!1,...B}=f,Y=[];if(J&&$.readFile)Y.push(t5($.readFile,B));if(W&&$.search)Y.push(s5($.search,B));if(H&&$.bash)if(process.platform==="win32")Y.push(e5($.bash,B));else Y.push(o5($.bash,B));if(Q&&$.webFetch)Y.push(fW($.webFetch,B));if(j&&$.editor)Y.push(JW($.editor,B));else if(Z&&$.applyPatch)Y.push($W($.applyPatch,B));if(X&&$.skills)Y.push(M$($.skills,B));let V=P?$.submit:void 0;if(A&&$.askQuestion&&!V)Y.push(WW($.askQuestion));if(V)Y.push(HW(V,B));return Y}import*as Ef from"node:fs/promises";import*as Sf from"node:path";var x={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},Y7=["%%bash","apply_patch","EOF","```"];class Qf extends Error{constructor(f){super(f);this.name="DiffError"}}function Cf(f){let $={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return f.normalize("NFC").replace(/./gu,(J)=>$[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class QW{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor(f,$){this.lines=f;this.currentFiles=$}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning(f){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push(f)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(x.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(x.END)??!1}parseNextAction(){let f=this.lines[this.index];if(f?.startsWith(x.UPDATE)){this.parseUpdate(f.substring(x.UPDATE.length).trim());return}if(f?.startsWith(x.DELETE)){this.parseDelete(f.substring(x.DELETE.length).trim());return}if(f?.startsWith(x.ADD)){this.parseAdd(f.substring(x.ADD.length).trim());return}throw new Qf(`Unknown line while parsing: ${f}`)}checkDuplicate(f,$){if(f in this.patch.actions)throw new Qf(`Duplicate ${$} for file: ${f}`)}parseUpdate(f){this.checkDuplicate(f,"update"),this.currentPath=f,this.index++;let $=this.lines[this.index]?.startsWith(x.MOVE)?(this.lines[this.index++]??"").substring(x.MOVE.length).trim():void 0;if(!(f in this.currentFiles))throw new Qf(`Update File Error: Missing File: ${f}`);let J=this.currentFiles[f]??"",W=this.parseUpdateFile(J,f);W.movePath=$,this.patch.actions[f]=W,this.currentPath=void 0}parseUpdateFile(f,$){let J={type:"update",chunks:[]},W=f.split(`
355
+ `),H=0,Q=[x.END,x.UPDATE,x.DELETE,x.ADD,x.END_FILE];while(!Q.some((Z)=>this.lines[this.index]?.startsWith(Z.trim()))){let Z=this.lines[this.index],j=Z?.startsWith("@@ ")?Z.substring(3):void 0;if(j!==void 0||(Z==="@@"?Z:void 0)!==void 0)this.index++;else if(H!==0)throw new Qf(`Invalid Line:
356
+ ${this.lines[this.index]}`);if(j?.trim()){let K=Cf(j.trim());for(let F=H;F<W.length;F++){let y=W[F];if(y&&(Cf(y)===K||Cf(y.trim())===K)){if(H=F+1,Cf(y.trim())===K&&Cf(y)!==K)this.fuzz++;break}}}let[A,P,B,Y]=wR(this.lines,this.index),[V,R,U]=qR(W,A,H,Y);if(V===-1){let K=A.join(`
357
+ `);this.addWarning({path:this.currentPath||$,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${U.toFixed(2)}). Chunk skipped.`,context:K.length>200?`${K.substring(0,200)}...`:K}),this.index=B}else{this.fuzz+=R;for(let K of P)K.origIndex+=V,J.chunks.push(K);H=V+A.length,this.index=B}}return J}parseDelete(f){if(this.checkDuplicate(f,"delete"),!(f in this.currentFiles))throw new Qf(`Delete File Error: Missing File: ${f}`);this.patch.actions[f]={type:"delete",chunks:[]},this.index++}parseAdd(f){if(this.checkDuplicate(f,"add"),f in this.currentFiles)throw new Qf(`Add File Error: File already exists: ${f}`);this.index++;let $=[],J=[x.END,x.UPDATE,x.DELETE,x.ADD];while(this.hasMoreLines()&&!J.some((W)=>this.lines[this.index]?.startsWith(W.trim()))){let W=this.lines[this.index++];if(W===void 0)break;if(!W.startsWith("+"))throw new Qf(`Invalid Add File line (missing '+'): ${W}`);$.push(W.substring(1))}this.patch.actions[f]={type:"add",newFile:$.join(`
358
+ `),chunks:[]}}}function B7(f,$){let J=f.length>$.length?f:$,W=f.length>$.length?$:f;if(J.length===0)return 1;let H=NR(W,J);return(J.length-H)/J.length}function NR(f,$){let J=$.length+1,W=f.length+1,H=Array(J*W).fill(0),Q=(j,X)=>H[j*W+X]??0,Z=(j,X,A)=>{H[j*W+X]=A};for(let j=0;j<=$.length;j++)Z(j,0,j);for(let j=0;j<=f.length;j++)Z(0,j,j);for(let j=1;j<=$.length;j++)for(let X=1;X<=f.length;X++)if($[j-1]===f[X-1])Z(j,X,Q(j-1,X-1));else Z(j,X,1+Math.min(Q(j-1,X-1),Q(j,X-1),Q(j-1,X)));return Q($.length,f.length)}function qR(f,$,J,W){if($.length===0)return[J,0,1];let H=0,Q=(Z)=>{let j=Cf($.join(`
359
+ `));for(let A=Z;A<f.length;A++){let P=Cf(f.slice(A,A+$.length).join(`
360
+ `));if(P===j)return[A,0,1];let B=B7(P,j);if(B>H)H=B}for(let A=Z;A<f.length;A++){let P=Cf(f.slice(A,A+$.length).map((Y)=>Y.trimEnd()).join(`
361
+ `)),B=Cf($.map((Y)=>Y.trimEnd()).join(`
362
+ `));if(P===B)return[A,1,1]}for(let A=Z;A<f.length;A++){let P=Cf(f.slice(A,A+$.length).map((Y)=>Y.trim()).join(`
363
+ `)),B=Cf($.map((Y)=>Y.trim()).join(`
364
+ `));if(P===B)return[A,100,1]}let X=0.66;for(let A=Z;A<f.length;A++){let P=Cf(f.slice(A,A+$.length).join(`
365
+ `)),B=B7(P,j);if(B>=X)return[A,1000,B];if(B>H)H=B}return[-1,0,H]};if(W){let[Z,j,X]=Q(f.length-$.length);if(Z!==-1)return[Z,j,X];return[Z,j,X]=Q(J),[Z,j+1e4,X]}return Q(J)}function wR(f,$){let J=$,W=[],H=[],Q=[],Z=[],j="keep",X=["@@",x.END,x.UPDATE,x.DELETE,x.ADD,x.END_FILE];while(J<f.length){let A=f[J];if(!A||X.some((Y)=>A.startsWith(Y.trim())))break;if(A==="***")break;if(A.startsWith("***"))throw new Qf(`Invalid line: ${A}`);J++;let P=j,B=A;if(B[0]==="+")j="add";else if(B[0]==="-")j="delete";else if(B[0]===" ")j="keep";else j="keep",B=` ${B}`;if(B=B.slice(1),j==="keep"&&P!==j){if(Q.length||H.length)Z.push({origIndex:W.length-H.length,delLines:H,insLines:Q});H=[],Q=[]}if(j==="delete")H.push(B),W.push(B);else if(j==="add")Q.push(B);else W.push(B)}if(Q.length||H.length)Z.push({origIndex:W.length-H.length,delLines:H,insLines:Q});if(J<f.length&&f[J]===x.END_FILE)return J++,[W,Z,J,!0];return[W,Z,J,!1]}function ZW(f,$,J){let W=Sf.isAbsolute($),H=W?Sf.normalize($):Sf.resolve(f,$);if(!J||W)return H;let Q=Sf.relative(f,H);if(Q.startsWith("..")||Sf.isAbsolute(Q))throw new Qf(`Path must stay within cwd: ${$}`);return H}function bR(f){return f.split(`
366
+ `).map(($)=>$.replace(/\r$/,""))}function V7(f){if(f.trim()==="")return!1;return Y7.some(($)=>f.startsWith($))}function CR(f){let $=0,J=f.length;while($<J&&V7(f[$]??""))$++;while(J>$&&V7(f[J-1]??""))J--;return f.slice($,J)}function ER(f){let $=bR(f),J=$.findIndex((Z)=>Z.startsWith(x.BEGIN)),W=-1;for(let Z=$.length-1;Z>=0;Z--)if($[Z]?.startsWith(x.END)){W=Z;break}if(J!==-1||W!==-1){if(J===-1||W===-1||W<J)throw new Qf("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:$.slice(J,W+1)}}let H=CR($);while(H.length>0&&H[0]==="")H.shift();while(H.length>0&&H[H.length-1]==="")H.pop();return{lines:[x.BEGIN,...H,x.END]}}function SR(f,$){let J=new Set;for(let W of f)for(let H of $)if(W.startsWith(H)){J.add(W.substring(H.length).trim());break}return[...J]}function kR(f,$,J){if($.length===0)return f;let W=f.split(`
367
+ `),H=[],Q=0;for(let Z of $){if(Z.origIndex>W.length)throw new Qf(`${J}: chunk.origIndex ${Z.origIndex} > lines.length ${W.length}`);if(Q>Z.origIndex)throw new Qf(`${J}: currentIndex ${Q} > chunk.origIndex ${Z.origIndex}`);H.push(...W.slice(Q,Z.origIndex)),H.push(...Z.insLines),Q=Z.origIndex+Z.delLines.length}return H.push(...W.slice(Q)),H.join(`
368
+ `)}async function IR(f,$,J,W){let H=SR(f,[x.UPDATE,x.DELETE]),Q={};for(let Z of H){let j=ZW($,Z,W),X;try{X=await Ef.readFile(j,J)}catch{throw new Qf(`File not found: ${Z}`)}Q[Z]=X.replace(/\r\n/g,`
369
+ `)}return Q}function mR(f,$){let J={};for(let[W,H]of Object.entries(f.actions))switch(H.type){case"delete":J[W]={type:"delete",oldContent:$[W]};break;case"add":if(H.newFile===void 0)throw new Qf("ADD action without file content");J[W]={type:"add",newContent:H.newFile};break;case"update":J[W]={type:"update",oldContent:$[W],newContent:kR($[W]??"",H.chunks,W),movePath:H.movePath};break}return J}async function xR(f,$,J,W){let H=[];for(let[Q,Z]of Object.entries(f)){let j=ZW($,Q,W);switch(Z.type){case"delete":await Ef.rm(j,{force:!0}),H.push(`${Q}: [deleted]`);break;case"add":if(Z.newContent===void 0)throw new Qf(`Cannot create ${Q} with no content`);await Ef.mkdir(Sf.dirname(j),{recursive:!0}),await Ef.writeFile(j,Z.newContent,{encoding:J}),H.push(Q);break;case"update":{if(Z.newContent===void 0)throw new Qf(`UPDATE change for ${Q} has no new content`);if(Z.movePath){let X=ZW($,Z.movePath,W);await Ef.mkdir(Sf.dirname(X),{recursive:!0}),await Ef.writeFile(X,Z.newContent,{encoding:J}),await Ef.rm(j,{force:!0}),H.push(`${Q} -> ${Z.movePath}`)}else await Ef.writeFile(j,Z.newContent,{encoding:J}),H.push(Q);break}}}return H}function f8(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0}=f;return async(W,H,Q)=>{let Z=ER(W.input),j=await IR(Z.lines,H,$,J),X=new QW(Z.lines,j),{patch:A,fuzz:P}=X.parse(),B=mR(A,j),Y=await xR(B,H,$,J),V=["Successfully applied patch to the following files:"];for(let R of Y)V.push(R);if(P>0)V.push(`Note: Patch applied with fuzz factor ${P}`);if(A.warnings&&A.warnings.length>0)for(let R of A.warnings)V.push(`Warning (${R.path}): ${R.message}`);return V.join(`
370
+ `)}}import{spawn as R7}from"node:child_process";import{getDefaultShell as gR,getShellArgs as vR}from"@cline/shared";function uR(f,$,J,W,H){return new Promise((Q,Z)=>{let j=process.platform==="win32",X=R7(f.executable,f.args,{cwd:f.cwd,env:{...process.env,...f.env},stdio:["pipe","pipe","pipe"],detached:!j}),A=X.pid,P="",B="",Y=0,V=!1,R=!1,U=(T)=>{if(R)return;R=!0,T()},K=()=>{if(!A)return;if(j){R7("taskkill",["/pid",String(A),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-A,"SIGKILL")}catch{X.kill("SIGKILL")}},F=(T)=>{V=!0,K(),U(()=>Z(T))},y=setTimeout(()=>F(Error(`Command timed out after ${J}ms`)),J),D=()=>F(Error("Command was aborted"));if($.signal)$.signal.addEventListener("abort",D);let M=()=>{clearTimeout(y),$.signal?.removeEventListener("abort",D)};X.stdout?.on("data",(T)=>{if(Y+=T.length,Y<=W)P+=T.toString()}),X.stderr?.on("data",(T)=>{if(Y+=T.length,Y<=W)B+=T.toString()}),X.on("close",(T)=>{if(M(),V)return;let _=H?P+(B?`
371
371
  [stderr]
372
- ${Y}`:""):V;if(B>H)h+=`
372
+ ${B}`:""):P;if(Y>W)_+=`
373
373
 
374
- [Output truncated: ${B} bytes total, showing first ${H} bytes]`;if(G!==0)U(()=>Z(Error(Y||`Command exited with code ${G}`)));else U(()=>Q(h))}),P.on("error",(G)=>{T(),U(()=>Z(Error(`Failed to execute command: ${G.message}`)))})})}function e2(f={}){let{shell:$=KR(process.platform),timeoutMs:J=30000,maxOutputBytes:H=1e6,env:W={},combineOutput:Q=!0}=f;return(Z,j,P)=>{let X=typeof Z!=="string";return GR({executable:X?Z.command:$,args:X?Z.args??[]:UR($,Z),cwd:j,env:W},P,J,H,Q)}}import*as lf from"node:fs/promises";import*as rf from"node:path";function hR(f,$,J){let H=rf.isAbsolute($),W=H?rf.normalize($):rf.resolve(f,$);if(!J)return W;if(H)return W;let Q=rf.relative(f,W);if(Q.startsWith("..")||rf.isAbsolute(Q))throw Error(`Path must stay within cwd: ${$}`);return W}function TR(f,$){if($.length===0)return 0;return f.split($).length-1}function DR(f,$,J){let H=f.split(`
375
- `),W=$.split(`
376
- `),Q=Math.max(H.length,W.length),Z=["```diff"],j=0;for(let P=0;P<Q;P++){if(j>=J){Z.push("... diff truncated ...");break}let X=H[P],V=W[P];if(X===V)continue;let Y=P+1;if(X!==void 0)Z.push(`-${Y}: ${X}`),j++;if(V!==void 0&&j<J)Z.push(`+${Y}: ${V}`),j++}return Z.push("```"),Z.join(`
377
- `)}async function MR(f,$,J){return await lf.mkdir(rf.dirname(f),{recursive:!0}),await lf.writeFile(f,$,{encoding:J}),`File created successfully at: ${f}`}async function _R(f){try{return await lf.access(f),!0}catch{return!1}}async function LR(f,$,J,H,W){let Q=await lf.readFile(f,H),Z=TR(Q,$);if(Z===0)throw Error(`No replacement performed: text not found in ${f}.`);if(Z>1)throw Error(`No replacement performed: multiple occurrences of text found in ${f}.`);let j=Q.replace($,J??"");await lf.writeFile(f,j,{encoding:H});let P=DR(Q,j,W);return`Edited ${f}
378
- ${P}`}async function zR(f,$,J,H){let Q=(await lf.readFile(f,H)).split(`
374
+ [Output truncated: ${Y} bytes total, showing first ${W} bytes]`;if(T!==0)U(()=>Z(Error(B||`Command exited with code ${T}`)));else U(()=>Q(_))}),X.on("error",(T)=>{M(),U(()=>Z(Error(`Failed to execute command: ${T.message}`)))})})}function $8(f={}){let{shell:$=gR(process.platform),timeoutMs:J=30000,maxOutputBytes:W=1e6,env:H={},combineOutput:Q=!0}=f;return(Z,j,X)=>{let A=typeof Z!=="string";return uR({executable:A?Z.command:$,args:A?Z.args??[]:vR($,Z),cwd:j,env:H},X,J,W,Q)}}import*as tf from"node:fs/promises";import*as af from"node:path";function cR(f,$,J){let W=af.isAbsolute($),H=W?af.normalize($):af.resolve(f,$);if(!J)return H;if(W)return H;let Q=af.relative(f,H);if(Q.startsWith("..")||af.isAbsolute(Q))throw Error(`Path must stay within cwd: ${$}`);return H}function dR(f,$){if($.length===0)return 0;return f.split($).length-1}function rR(f,$,J){let W=f.split(`
375
+ `),H=$.split(`
376
+ `),Q=Math.max(W.length,H.length),Z=["```diff"],j=0;for(let X=0;X<Q;X++){if(j>=J){Z.push("... diff truncated ...");break}let A=W[X],P=H[X];if(A===P)continue;let B=X+1;if(A!==void 0)Z.push(`-${B}: ${A}`),j++;if(P!==void 0&&j<J)Z.push(`+${B}: ${P}`),j++}return Z.push("```"),Z.join(`
377
+ `)}async function lR(f,$,J){return await tf.mkdir(af.dirname(f),{recursive:!0}),await tf.writeFile(f,$,{encoding:J}),`File created successfully at: ${f}`}async function pR(f){try{return await tf.access(f),!0}catch{return!1}}async function iR(f,$,J,W,H){let Q=await tf.readFile(f,W),Z=dR(Q,$);if(Z===0)throw Error(`No replacement performed: text not found in ${f}.`);if(Z>1)throw Error(`No replacement performed: multiple occurrences of text found in ${f}.`);let j=Q.replace($,J??"");await tf.writeFile(f,j,{encoding:W});let X=rR(Q,j,H);return`Edited ${f}
378
+ ${X}`}async function nR(f,$,J,W){let Q=(await tf.readFile(f,W)).split(`
379
379
  `),Z=Q.length+1;if($<1||$>Z)throw Error(`Invalid insert_line: ${$}. insert_line must be a positive one-based boundary line in the range 1-${Z}. Use ${Z} to append at EOF.`);let j=$-1;return Q.splice(j,0,...J.split(`
380
- `)),await lf.writeFile(f,Q.join(`
381
- `),{encoding:H}),`Inserted content at line ${$} in ${f}.`}function f8(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0,maxDiffLines:H=200}=f;return async(W,Q,Z)=>{let j=hR(Q,W.path,J);if(W.insert_line!=null)return zR(j,W.insert_line,W.new_text,$);if(!await _R(j))return MR(j,W.new_text,$);if(W.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return LR(j,W.old_text,W.new_text,$,H)}}import*as $8 from"node:fs/promises";import*as c0 from"node:path";var OR=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),NR={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function J8(f={}){let{maxFileSizeBytes:$,encoding:J,includeLineNumbers:H}={...NR,...f};return async(W,Q)=>{let{path:Z,start_line:j,end_line:P}=W,X=c0.isAbsolute(Z)?c0.normalize(Z):c0.resolve(process.cwd(),Z),V=c0.extname(X).toLowerCase(),Y=OR.get(V),B=await $8.stat(X);if(!B.isFile())throw Error(`Path is not a file: ${X}`);if(B.size>$)throw Error(`File too large: ${B.size} bytes (max: ${$} bytes). Consider reading specific sections or using a different approach.`);if(Y){if(Q.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let K=await $8.readFile(X);return[{type:"text",text:"Successfully read image"},{type:"image",data:K.toString("base64"),mediaType:Y}]}let R=(await $8.readFile(X,J)).split(`
382
- `),U=Math.max((j??1)-1,0),y=Math.min(P??R.length,R.length),F=R.slice(U,y);if(H){let K=String(R.length).length;return F.map((M,T)=>`${String(U+T+1).padStart(K," ")} | ${M}`).join(`
380
+ `)),await tf.writeFile(f,Q.join(`
381
+ `),{encoding:W}),`Inserted content at line ${$} in ${f}.`}function J8(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0,maxDiffLines:W=200}=f;return async(H,Q,Z)=>{let j=cR(Q,H.path,J);if(H.insert_line!=null)return nR(j,H.insert_line,H.new_text,$);if(!await pR(j))return lR(j,H.new_text,$);if(H.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return iR(j,H.old_text,H.new_text,$,W)}}import*as W8 from"node:fs/promises";import*as n0 from"node:path";var aR=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),tR={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function H8(f={}){let{maxFileSizeBytes:$,encoding:J,includeLineNumbers:W}={...tR,...f};return async(H,Q)=>{let{path:Z,start_line:j,end_line:X}=H,A=n0.isAbsolute(Z)?n0.normalize(Z):n0.resolve(process.cwd(),Z),P=n0.extname(A).toLowerCase(),B=aR.get(P),Y=await W8.stat(A);if(!Y.isFile())throw Error(`Path is not a file: ${A}`);if(Y.size>$)throw Error(`File too large: ${Y.size} bytes (max: ${$} bytes). Consider reading specific sections or using a different approach.`);if(B){if(Q.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let y=await W8.readFile(A);return[{type:"text",text:"Successfully read image"},{type:"image",data:y.toString("base64"),mediaType:B}]}let R=(await W8.readFile(A,J)).split(`
382
+ `),U=Math.max((j??1)-1,0),K=Math.min(X??R.length,R.length),F=R.slice(U,K);if(W){let y=String(R.length).length;return F.map((D,M)=>`${String(U+M+1).padStart(y," ")} | ${D}`).join(`
383
383
  `)}return F.join(`
384
- `)}}import{spawn as XQ}from"node:child_process";import*as VQ from"node:fs/promises";import*as Y6 from"node:path";var PQ={};N(PQ,{prewarmFileIndex:()=>V6,getFileIndex:()=>U0,enrichPromptWithMentions:()=>F1});import{spawn as qR}from"node:child_process";import{readdir as bR}from"node:fs/promises";import ZW from"node:path";import{isMainThread as QQ,parentPort as HQ,Worker as wR}from"node:worker_threads";var CR=15000,ER=600000,SR=1000,kR=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function WQ(f){let $=f&&typeof f==="object"&&"code"in f?String(f.code??""):"";return $==="EACCES"||$==="EPERM"||$==="ENOENT"}var R1=new Map;function mR(f){if(R1.size<=1)return;for(let[$,J]of R1.entries()){if(J.pending)continue;if(f-J.lastAccessedAt>ER)R1.delete($)}}function IR(f,$){return ZW.relative(f,$).split(ZW.sep).join("/")}async function xR(f){let J=(await new Promise((H,W)=>{let Q=qR("rg",["--files","--hidden","-g","!.git"],{cwd:f,stdio:["ignore","pipe","pipe"]}),Z="",j="";Q.stdout.on("data",(P)=>{Z+=P.toString()}),Q.stderr.on("data",(P)=>{j+=P.toString()}),Q.on("error",W),Q.on("close",(P)=>{if(P===0){H(Z);return}W(Error(j||`rg exited with code ${P}`))})})).split(/\r?\n/).map((H)=>H.trim()).filter((H)=>H.length>0).map((H)=>H.replace(/\\/g,"/"));return new Set(J)}async function ZQ(f,$,J){let H;try{H=await bR($,{withFileTypes:!0})}catch(W){if(WQ(W))return;throw W}for(let W of H){let Q=ZW.join($,W.name);if(W.isDirectory()){if(kR.has(W.name))continue;try{await ZQ(f,Q,J)}catch(Z){if(WQ(Z))continue;throw Z}continue}if(W.isFile())J.add(IR(f,Q))}}async function gR(f){let $=new Set;return await ZQ(f,f,$),$}async function X6(f){try{return await xR(f)}catch{return gR(f)}}function vR(){if(QQ||!HQ)return;let f=HQ;f.on("message",($)=>{if($.type!=="index")return;X6($.cwd).then((J)=>{let H={type:"indexResult",requestId:$.requestId,files:Array.from(J)};f.postMessage(H)}).catch((J)=>{let H={type:"indexResult",requestId:$.requestId,error:J instanceof Error?J.message:"Failed to build file index"};f.postMessage(H)})})}class jQ{worker=new wR(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",(f)=>{if(f.type!=="indexResult")return;let $=this.pending.get(f.requestId);if(!$)return;if(this.pending.delete(f.requestId),f.error){$.reject(Error(f.error));return}$.resolve(f.files??[])}),this.worker.on("error",(f)=>{this.flushPending(f)}),this.worker.on("exit",(f)=>{if(f!==0)this.flushPending(Error(`File index worker exited with code ${f}`))})}requestIndex(f){let $=++this.nextRequestId,J=new Promise((W,Q)=>{let Z=setTimeout(()=>{this.pending.delete($),W(null)},SR);Z.unref(),this.pending.set($,{resolve:(j)=>{clearTimeout(Z),W(j)},reject:(j)=>{clearTimeout(Z),Q(j)}})}),H={type:"index",requestId:$,cwd:f};return this.worker.postMessage(H),J}flushPending(f){for(let[$,J]of this.pending.entries())J.reject(f),this.pending.delete($)}}vR();var QW;function uR(){if(!QQ)return null;if(QW===void 0)QW=new jQ;return QW}async function cR(f){let $=uR();if(!$)return X6(f);try{let J=await $.requestIndex(f);if(J===null)return X6(f);return new Set(J)}catch{return X6(f)}}async function U0(f,$={}){let J=$.ttlMs??CR,H=Date.now();mR(H);let W=R1.get(f);if(W&&J>0&&H-W.lastBuiltAt<=J&&W.files.size>0)return W.lastAccessedAt=H,W.files;if(W?.pending)return W.lastAccessedAt=H,W.pending;let Q=cR(f).then((Z)=>{return R1.set(f,{files:Z,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),Z});return R1.set(f,{files:W?.files??new Set,lastBuiltAt:W?.lastBuiltAt??0,lastAccessedAt:H,pending:Q}),Q}async function V6(f,$={}){await U0(f,{...$,ttlMs:0})}import{stat as dR}from"node:fs/promises";import T$ from"node:path";var rR=/[),.:;!?`'"]+$/,lR=/^[(`'"]+/;function pR(f){let $=f.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let H of $){let W=(H[2]??"").trim();if(W.length===0)continue;let Q=W.replace(lR,"").replace(rR,"");if(Q.length===0||Q.includes("@"))continue;J.push(Q)}return Array.from(new Set(J))}function iR(f,$){let J=f.replace(/\\/g,"/"),H=T$.isAbsolute(J)?T$.resolve(J):T$.resolve($,J),W=T$.relative($,H);if(W.startsWith("..")||T$.isAbsolute(W))return;return W.split(T$.sep).join("/")}async function F1(f,$,J={}){let H=pR(f);if(H.length===0)return{prompt:f,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:W,maxFileBytes:Q,maxTotalBytes:Z}=J,j=await U0($,{ttlMs:J.ttlMs}),P=[],X=[],V=[],Y=0;for(let B of H){if(W&&V.length>=W){X.push(B);continue}let A=iR(B,$);if(!A||!j.has(A)){X.push(B);continue}if(!Q||!Z){P.push(A);continue}let R=T$.join($,A);try{if(!(await dR(R)).isFile()){X.push(B);continue}let y=Y+Q;if(y>Z){X.push(B);continue}Y=y,P.push(A)}catch{X.push(B)}}return{prompt:f,mentions:H,matchedFiles:P,ignoredMentions:X}}var nR=["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"],aR=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],D$=null;function tR(){if(D$!==null)return Promise.resolve(D$);return new Promise((f)=>{let $=XQ("rg",["--version"],{stdio:["ignore","pipe","pipe"]});$.on("close",(J)=>{D$=J===0,f(D$)}),$.on("error",()=>{D$=!1,f(!1)}),setTimeout(()=>{if(!$.killed)$.kill("SIGTERM");if(D$===null)D$=!1,f(!1)},1000)})}function sR(f,$,J,H,W=5000,Q){return new Promise((Z)=>{let j=XQ("rg",["--json",`--context=${H}`,"--max-count=1","-i",f],{cwd:$,stdio:["ignore","pipe","pipe"]}),P="",X=!1,V=()=>{if(!j.killed)j.kill("SIGTERM")},Y=setTimeout(()=>{if(!X)X=!0,V(),Z(null)},W),B=(A)=>{if(!X)X=!0,clearTimeout(Y),V(),Z(A)};if(Q?.aborted){V(),Z(null);return}Q?.addEventListener("abort",()=>{B(null)}),j.stdout.on("data",(A)=>{P+=A.toString()}),j.stderr.on("data",()=>{}),j.on("close",(A)=>{if(A===0||A===1){try{let R=[],U=P.split(`
385
- `).filter((y)=>y.trim());for(let y of U){if(R.length>=J)break;let F=JSON.parse(y);if(F.type==="match"){let K=F.data,M=[];if(F.data.submatches&&F.data.submatches.length>0){let T=F.data.submatches[0];R.push({file:K.path.text,line:K.line_number,column:(T?.start??0)+1,match:T?.match?.text??"",context:M})}}else if(F.type==="context"&&R.length>0){let K=R[R.length-1],M=F.data.line_number===K.line?">":" ";K.context.push(`${M} ${F.data.line_number}: ${F.data.lines?.text??F.data.line?.text??""}`)}}B(R.length>0?R:null)}catch{B(null)}return}B(null)}),j.on("error",()=>{B(null)})})}function oR(f,$,J,H){let W=f.split("/"),Q=W[W.length-1]??"";if(W.length-1>H)return!1;for(let P=0;P<W.length-1;P++)if($.has(W[P]??""))return!1;let j=Y6.posix.extname(Q).slice(1).toLowerCase();return J.has(j)||!j&&!Q.startsWith(".")}function H8(f={}){let{includeExtensions:$=nR,excludeDirs:J=aR,maxResults:H=100,contextLines:W=2,maxDepth:Q=20}=f,Z=new Set(J),j=new Set($.map((P)=>P.toLowerCase()));return async(P,X,V)=>{if(V.signal?.aborted)throw Error("Search operation aborted");let Y=await tR(),B=null;if(Y)B=await sR(P,X,H,W,5000,V.signal);if(B){let K=[`Found ${B.length} result${B.length===1?"":"s"} for pattern: ${P}`,""];for(let M of B)K.push(`${M.file}:${M.line}:${M.column}`),K.push(...M.context),K.push("");if(B.length>=H)K.push(`(Showing first ${H} results. Refine your search for more specific results.)`);return K.join(`
386
- `)}let A;try{A=new RegExp(P,"gim")}catch(K){throw Error(`Invalid regex pattern: ${P}. ${K instanceof Error?K.message:""}`)}let R=[],U=0,y=await U0(X);for(let K of y){if(V.signal?.aborted)throw Error("Search operation aborted");if(!oR(K,Z,j,Q))continue;if(R.length>=H)break;U++;let M=Y6.join(X,K);try{let G=(await VQ.readFile(M,"utf-8")).split(`
387
- `);for(let h=0;h<G.length;h++){let z=G[h];A.lastIndex=0;let u=A.exec(z);while(u!==null){if(R.length>=H)break;let gf=Math.max(0,h-W),a=Math.min(G.length-1,h+W),c=[];for(let d=gf;d<=a;d++){let t=d===h?">":" ";c.push(`${t} ${d+1}: ${G[d]}`)}if(R.push({file:K,line:h+1,column:u.index+1,match:u[0],context:c}),u.index===A.lastIndex)A.lastIndex++;u=A.exec(z)}}}catch{}}if(R.length===0)return`No results found for pattern: ${P}
388
- Searched ${U} files.`;let F=[`Found ${R.length} result${R.length===1?"":"s"} for pattern: ${P}`,`Searched ${U} files.`,""];for(let K of R)F.push(`${K.file}:${K.line}:${K.column}`),F.push(...K.context),F.push("");if(R.length>=H)F.push(`(Showing first ${H} results. Refine your search for more specific results.)`);return F.join(`
389
- `)}}function eR(f){return f.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
384
+ `)}}import{spawn as D7}from"node:child_process";import*as _7 from"node:fs/promises";import*as y6 from"node:path";var T7={};N(T7,{prewarmFileIndex:()=>K6,getFileIndex:()=>M0,enrichPromptWithMentions:()=>y1});import{spawn as sR}from"node:child_process";import{readdir as oR}from"node:fs/promises";import XW from"node:path";import{isMainThread as y7,parentPort as F7,Worker as eR}from"node:worker_threads";var fF=15000,$F=600000,JF=1000,WF=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function K7(f){let $=f&&typeof f==="object"&&"code"in f?String(f.code??""):"";return $==="EACCES"||$==="EPERM"||$==="ENOENT"}var K1=new Map;function HF(f){if(K1.size<=1)return;for(let[$,J]of K1.entries()){if(J.pending)continue;if(f-J.lastAccessedAt>$F)K1.delete($)}}function QF(f,$){return XW.relative(f,$).split(XW.sep).join("/")}async function ZF(f){let J=(await new Promise((W,H)=>{let Q=sR("rg",["--files","--hidden","-g","!.git"],{cwd:f,stdio:["ignore","pipe","pipe"]}),Z="",j="";Q.stdout.on("data",(X)=>{Z+=X.toString()}),Q.stderr.on("data",(X)=>{j+=X.toString()}),Q.on("error",H),Q.on("close",(X)=>{if(X===0){W(Z);return}H(Error(j||`rg exited with code ${X}`))})})).split(/\r?\n/).map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>W.replace(/\\/g,"/"));return new Set(J)}async function U7(f,$,J){let W;try{W=await oR($,{withFileTypes:!0})}catch(H){if(K7(H))return;throw H}for(let H of W){let Q=XW.join($,H.name);if(H.isDirectory()){if(WF.has(H.name))continue;try{await U7(f,Q,J)}catch(Z){if(K7(Z))continue;throw Z}continue}if(H.isFile())J.add(QF(f,Q))}}async function jF(f){let $=new Set;return await U7(f,f,$),$}async function F6(f){try{return await ZF(f)}catch{return jF(f)}}function XF(){if(y7||!F7)return;let f=F7;f.on("message",($)=>{if($.type!=="index")return;F6($.cwd).then((J)=>{let W={type:"indexResult",requestId:$.requestId,files:Array.from(J)};f.postMessage(W)}).catch((J)=>{let W={type:"indexResult",requestId:$.requestId,error:J instanceof Error?J.message:"Failed to build file index"};f.postMessage(W)})})}class G7{worker=new eR(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",(f)=>{if(f.type!=="indexResult")return;let $=this.pending.get(f.requestId);if(!$)return;if(this.pending.delete(f.requestId),f.error){$.reject(Error(f.error));return}$.resolve(f.files??[])}),this.worker.on("error",(f)=>{this.flushPending(f)}),this.worker.on("exit",(f)=>{if(f!==0)this.flushPending(Error(`File index worker exited with code ${f}`))})}requestIndex(f){let $=++this.nextRequestId,J=new Promise((H,Q)=>{let Z=setTimeout(()=>{this.pending.delete($),H(null)},JF);Z.unref(),this.pending.set($,{resolve:(j)=>{clearTimeout(Z),H(j)},reject:(j)=>{clearTimeout(Z),Q(j)}})}),W={type:"index",requestId:$,cwd:f};return this.worker.postMessage(W),J}flushPending(f){for(let[$,J]of this.pending.entries())J.reject(f),this.pending.delete($)}}XF();var jW;function AF(){if(!y7)return null;if(jW===void 0)jW=new G7;return jW}async function PF(f){let $=AF();if(!$)return F6(f);try{let J=await $.requestIndex(f);if(J===null)return F6(f);return new Set(J)}catch{return F6(f)}}async function M0(f,$={}){let J=$.ttlMs??fF,W=Date.now();HF(W);let H=K1.get(f);if(H&&J>0&&W-H.lastBuiltAt<=J&&H.files.size>0)return H.lastAccessedAt=W,H.files;if(H?.pending)return H.lastAccessedAt=W,H.pending;let Q=PF(f).then((Z)=>{return K1.set(f,{files:Z,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),Z});return K1.set(f,{files:H?.files??new Set,lastBuiltAt:H?.lastBuiltAt??0,lastAccessedAt:W,pending:Q}),Q}async function K6(f,$={}){await M0(f,{...$,ttlMs:0})}import{stat as BF}from"node:fs/promises";import L$ from"node:path";var YF=/[),.:;!?`'"]+$/,VF=/^[(`'"]+/;function RF(f){let $=f.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let W of $){let H=(W[2]??"").trim();if(H.length===0)continue;let Q=H.replace(VF,"").replace(YF,"");if(Q.length===0||Q.includes("@"))continue;J.push(Q)}return Array.from(new Set(J))}function FF(f,$){let J=f.replace(/\\/g,"/"),W=L$.isAbsolute(J)?L$.resolve(J):L$.resolve($,J),H=L$.relative($,W);if(H.startsWith("..")||L$.isAbsolute(H))return;return H.split(L$.sep).join("/")}async function y1(f,$,J={}){let W=RF(f);if(W.length===0)return{prompt:f,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:H,maxFileBytes:Q,maxTotalBytes:Z}=J,j=await M0($,{ttlMs:J.ttlMs}),X=[],A=[],P=[],B=0;for(let Y of W){if(H&&P.length>=H){A.push(Y);continue}let V=FF(Y,$);if(!V||!j.has(V)){A.push(Y);continue}if(!Q||!Z){X.push(V);continue}let R=L$.join($,V);try{if(!(await BF(R)).isFile()){A.push(Y);continue}let K=B+Q;if(K>Z){A.push(Y);continue}B=K,X.push(V)}catch{A.push(Y)}}return{prompt:f,mentions:W,matchedFiles:X,ignoredMentions:A}}var KF=["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"],yF=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],h$=null;function UF(){if(h$!==null)return Promise.resolve(h$);return new Promise((f)=>{let $=D7("rg",["--version"],{stdio:["ignore","pipe","pipe"]});$.on("close",(J)=>{h$=J===0,f(h$)}),$.on("error",()=>{h$=!1,f(!1)}),setTimeout(()=>{if(!$.killed)$.kill("SIGTERM");if(h$===null)h$=!1,f(!1)},1000)})}function GF(f,$,J,W,H=5000,Q){return new Promise((Z)=>{let j=D7("rg",["--json",`--context=${W}`,"--max-count=1","-i",f],{cwd:$,stdio:["ignore","pipe","pipe"]}),X="",A=!1,P=()=>{if(!j.killed)j.kill("SIGTERM")},B=setTimeout(()=>{if(!A)A=!0,P(),Z(null)},H),Y=(V)=>{if(!A)A=!0,clearTimeout(B),P(),Z(V)};if(Q?.aborted){P(),Z(null);return}Q?.addEventListener("abort",()=>{Y(null)}),j.stdout.on("data",(V)=>{X+=V.toString()}),j.stderr.on("data",()=>{}),j.on("close",(V)=>{if(V===0||V===1){try{let R=[],U=X.split(`
385
+ `).filter((K)=>K.trim());for(let K of U){if(R.length>=J)break;let F=JSON.parse(K);if(F.type==="match"){let y=F.data,D=[];if(F.data.submatches&&F.data.submatches.length>0){let M=F.data.submatches[0];R.push({file:y.path.text,line:y.line_number,column:(M?.start??0)+1,match:M?.match?.text??"",context:D})}}else if(F.type==="context"&&R.length>0){let y=R[R.length-1],D=F.data.line_number===y.line?">":" ";y.context.push(`${D} ${F.data.line_number}: ${F.data.lines?.text??F.data.line?.text??""}`)}}Y(R.length>0?R:null)}catch{Y(null)}return}Y(null)}),j.on("error",()=>{Y(null)})})}function TF(f,$,J,W){let H=f.split("/"),Q=H[H.length-1]??"";if(H.length-1>W)return!1;for(let X=0;X<H.length-1;X++)if($.has(H[X]??""))return!1;let j=y6.posix.extname(Q).slice(1).toLowerCase();return J.has(j)||!j&&!Q.startsWith(".")}function Q8(f={}){let{includeExtensions:$=KF,excludeDirs:J=yF,maxResults:W=100,contextLines:H=2,maxDepth:Q=20}=f,Z=new Set(J),j=new Set($.map((X)=>X.toLowerCase()));return async(X,A,P)=>{if(P.signal?.aborted)throw Error("Search operation aborted");let B=await UF(),Y=null;if(B)Y=await GF(X,A,W,H,5000,P.signal);if(Y){let y=[`Found ${Y.length} result${Y.length===1?"":"s"} for pattern: ${X}`,""];for(let D of Y)y.push(`${D.file}:${D.line}:${D.column}`),y.push(...D.context),y.push("");if(Y.length>=W)y.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return y.join(`
386
+ `)}let V;try{V=new RegExp(X,"gim")}catch(y){throw Error(`Invalid regex pattern: ${X}. ${y instanceof Error?y.message:""}`)}let R=[],U=0,K=await M0(A);for(let y of K){if(P.signal?.aborted)throw Error("Search operation aborted");if(!TF(y,Z,j,Q))continue;if(R.length>=W)break;U++;let D=y6.join(A,y);try{let T=(await _7.readFile(D,"utf-8")).split(`
387
+ `);for(let _=0;_<T.length;_++){let L=T[_];V.lastIndex=0;let q=V.exec(L);while(q!==null){if(R.length>=W)break;let Wf=Math.max(0,_-H),Hf=Math.min(T.length-1,_+H),o=[];for(let c=Wf;c<=Hf;c++){let Gf=c===_?">":" ";o.push(`${Gf} ${c+1}: ${T[c]}`)}if(R.push({file:y,line:_+1,column:q.index+1,match:q[0],context:o}),q.index===V.lastIndex)V.lastIndex++;q=V.exec(L)}}}catch{}}if(R.length===0)return`No results found for pattern: ${X}
388
+ Searched ${U} files.`;let F=[`Found ${R.length} result${R.length===1?"":"s"} for pattern: ${X}`,`Searched ${U} files.`,""];for(let y of R)F.push(`${y.file}:${y.line}:${y.column}`),F.push(...y.context),F.push("");if(R.length>=W)F.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return F.join(`
389
+ `)}}function DF(f){return f.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
390
390
  `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,($,J)=>String.fromCharCode(parseInt(J,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
391
391
  `).replace(/\n{3,}/g,`
392
392
 
393
- `).trim()}function W8(f={}){let{timeoutMs:$=30000,maxResponseBytes:J=5000000,userAgent:H="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:W={},followRedirects:Q=!0}=f;return async(Z,j,P)=>{let X;try{X=new URL(Z)}catch{throw Error(`Invalid URL: ${Z}`)}if(!["http:","https:"].includes(X.protocol))throw Error(`Invalid protocol: ${X.protocol}. Only http and https are supported.`);let V=new AbortController,Y=setTimeout(()=>V.abort(),$),B;if(P.signal)B=()=>V.abort(),P.signal.addEventListener("abort",B);try{let A=await fetch(Z,{method:"GET",headers:{"User-Agent":H,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...W},redirect:Q?"follow":"manual",signal:V.signal});if(clearTimeout(Y),!Q&&A.status>=300&&A.status<400)return`Redirect to: ${A.headers.get("location")}`;if(!A.ok)throw Error(`HTTP ${A.status}: ${A.statusText}`);let R=A.headers.get("content-type")||"",U=A.body?.getReader();if(!U)throw Error("Failed to read response body");let y=[],F=0;while(!0){let{done:z,value:u}=await U.read();if(z)break;if(F+=u.length,F>J)throw U.cancel(),Error(`Response too large: exceeded ${J} bytes`);y.push(u)}let K=new Uint8Array(F),M=0;for(let z of y)K.set(z,M),M+=z.length;let T=new TextDecoder("utf-8").decode(K),G;if(R.includes("text/html")||R.includes("application/xhtml"))G=eR(T);else if(R.includes("application/json"))try{let z=JSON.parse(T);G=JSON.stringify(z,null,2)}catch{G=T}else G=T;let h=[`URL: ${Z}`,`Content-Type: ${R}`,`Size: ${F} bytes`,"","--- Content ---",G.slice(0,50000)];if(G.length>50000)h.push(`
394
- [Content truncated: showing first 50000 of ${G.length} characters]`);return h.push("","--- Analysis Request ---",`Prompt: ${j}`),h.join(`
395
- `)}catch(A){if(clearTimeout(Y),A instanceof Error){if(A.name==="AbortError")throw Error(`Request timed out after ${$}ms`);throw A}throw Error(`Fetch failed: ${String(A)}`)}finally{if(P.signal&&B)P.signal.removeEventListener("abort",B)}}}function y1(f={}){return{readFile:J8(f.fileRead),search:H8(f.search),bash:e2(f.bash),webFetch:W8(f.webFetch),applyPatch:o2(f.applyPatch),editor:f8(f.editor)}}var fF={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"},K1=[{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 YQ(f,$){if(!$||$.length===0)return!0;let J=f.toLowerCase();return $.some((H)=>J.includes(H.toLowerCase()))}function $F(f,$,J,H){if(f.mode&&f.mode!=="any"&&f.mode!==H)return!1;return YQ($,f.providerIdIncludes)&&YQ(J,f.modelIdIncludes)}function U1(f,$,J,H){if(!H||H.length===0)return{};let W=new Map;for(let Z of H){if(!$F(Z,f,$,J))continue;for(let j of Z.disableTools??[])W.set(j,!1);for(let j of Z.enableTools??[])W.set(j,!0)}let Q={};for(let[Z,j]of W.entries())Q[fF[Z]]=j;return Q}var bf={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 G0(f){if(f.mode==="plan")return"plan";if(f.mode==="yolo")return"yolo";return"act"}function B6(f){if(f!=="yolo")return{};let $={enabled:!0,autoApprove:!0},J={"*":$};for(let H of q0)J[H]=$;return J}function A6(f,$){let J=bf[f],{enableSpawnAgent:H,enableAgentTeams:W,...Q}=J;return u0({...Q,...$})}import{createTool as iF,zodToJsonSchema as nF}from"@cline/shared";import{z as yW}from"zod";import{createAgentRuntime as xF}from"@cline/agents";import{createContributionRegistry as gF}from"@cline/shared";import{createGateway as JF,MODEL_COLLECTIONS_BY_PROVIDER_ID as HF}from"@cline/llms";function jW(f){let $=f.providerConfig;if($?.knownModels)return $.knownModels;if(f.knownModels)return f.knownModels;return HF[f.providerId]?.models??void 0}function BQ(f,$){let J=f.providerConfig,H=J?.providerId===f.providerId?J:void 0,W={...H??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??H?.apiKey,baseUrl:f.baseUrl??H?.baseUrl,headers:f.headers??H?.headers,knownModels:jW(f),maxOutputTokens:f.maxTokensPerTurn,reasoningEffort:f.reasoningEffort,thinkingBudgetTokens:f.thinkingBudgetTokens,thinking:f.thinking,logger:$,extensionContext:f.extensionContext};return JF({providerConfigs:[{providerId:W.providerId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,models:W.knownModels?Object.entries(W.knownModels).map(([Q,Z])=>({id:Q,name:Z.name??Q,description:Z.description,contextWindow:Z.contextWindow,maxOutputTokens:Z.maxTokens})):void 0}],logger:$}).createAgentModel({providerId:W.providerId,modelId:W.modelId},{maxTokens:W.maxOutputTokens})}import{normalizeUserInput as AQ}from"@cline/shared";var WF=50000,QF=6000000,RQ=8000,ZF=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),jF=new Set(["read","read_files"]),M$="[outdated - see the latest file content]",FQ="Tool execution was interrupted before a result was produced.",PF=(f)=>`
393
+ `).trim()}function Z8(f={}){let{timeoutMs:$=30000,maxResponseBytes:J=5000000,userAgent:W="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:H={},followRedirects:Q=!0}=f;return async(Z,j,X)=>{let A;try{A=new URL(Z)}catch{throw Error(`Invalid URL: ${Z}`)}if(!["http:","https:"].includes(A.protocol))throw Error(`Invalid protocol: ${A.protocol}. Only http and https are supported.`);let P=new AbortController,B=setTimeout(()=>P.abort(),$),Y;if(X.signal)Y=()=>P.abort(),X.signal.addEventListener("abort",Y);try{let V=await fetch(Z,{method:"GET",headers:{"User-Agent":W,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...H},redirect:Q?"follow":"manual",signal:P.signal});if(clearTimeout(B),!Q&&V.status>=300&&V.status<400)return`Redirect to: ${V.headers.get("location")}`;if(!V.ok)throw Error(`HTTP ${V.status}: ${V.statusText}`);let R=V.headers.get("content-type")||"",U=V.body?.getReader();if(!U)throw Error("Failed to read response body");let K=[],F=0;while(!0){let{done:L,value:q}=await U.read();if(L)break;if(F+=q.length,F>J)throw U.cancel(),Error(`Response too large: exceeded ${J} bytes`);K.push(q)}let y=new Uint8Array(F),D=0;for(let L of K)y.set(L,D),D+=L.length;let M=new TextDecoder("utf-8").decode(y),T;if(R.includes("text/html")||R.includes("application/xhtml"))T=DF(M);else if(R.includes("application/json"))try{let L=JSON.parse(M);T=JSON.stringify(L,null,2)}catch{T=M}else T=M;let _=[`URL: ${Z}`,`Content-Type: ${R}`,`Size: ${F} bytes`,"","--- Content ---",T.slice(0,50000)];if(T.length>50000)_.push(`
394
+ [Content truncated: showing first 50000 of ${T.length} characters]`);return _.push("","--- Analysis Request ---",`Prompt: ${j}`),_.join(`
395
+ `)}catch(V){if(clearTimeout(B),V instanceof Error){if(V.name==="AbortError")throw Error(`Request timed out after ${$}ms`);throw V}throw Error(`Fetch failed: ${String(V)}`)}finally{if(X.signal&&Y)X.signal.removeEventListener("abort",Y)}}}function U1(f={}){return{readFile:H8(f.fileRead),search:Q8(f.search),bash:$8(f.bash),webFetch:Z8(f.webFetch),applyPatch:f8(f.applyPatch),editor:J8(f.editor)}}var _F={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"},G1=[{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 M7(f,$){if(!$||$.length===0)return!0;let J=f.toLowerCase();return $.some((W)=>J.includes(W.toLowerCase()))}function MF(f,$,J,W){if(f.mode&&f.mode!=="any"&&f.mode!==W)return!1;return M7($,f.providerIdIncludes)&&M7(J,f.modelIdIncludes)}function T1(f,$,J,W){if(!W||W.length===0)return{};let H=new Map;for(let Z of W){if(!MF(Z,f,$,J))continue;for(let j of Z.disableTools??[])H.set(j,!1);for(let j of Z.enableTools??[])H.set(j,!0)}let Q={};for(let[Z,j]of H.entries())Q[_F[Z]]=j;return Q}var kf={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 L0(f){if(f.mode==="plan")return"plan";if(f.mode==="yolo")return"yolo";return"act"}function U6(f){if(f!=="yolo")return{};let $={enabled:!0,autoApprove:!0},J={"*":$};for(let W of k0)J[W]=$;return J}function G6(f,$){let J=kf[f],{enableSpawnAgent:W,enableAgentTeams:H,...Q}=J;return i0({...Q,...$})}import{createTool as FK,zodToJsonSchema as KK}from"@cline/shared";import{z as UW}from"zod";import{createAgentRuntime as ZK}from"@cline/agents";import{createContributionRegistry as jK}from"@cline/shared";import{createGateway as LF,MODEL_COLLECTIONS_BY_PROVIDER_ID as hF}from"@cline/llms";function AW(f){let $=f.providerConfig;if($?.knownModels)return $.knownModels;if(f.knownModels)return f.knownModels;return hF[f.providerId]?.models??void 0}function L7(f,$){let J=f.providerConfig,W=J?.providerId===f.providerId?J:void 0,H={...W??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??W?.apiKey,baseUrl:f.baseUrl??W?.baseUrl,headers:f.headers??W?.headers,knownModels:AW(f),maxOutputTokens:f.maxTokensPerTurn,reasoningEffort:f.reasoningEffort,thinkingBudgetTokens:f.thinkingBudgetTokens,thinking:f.thinking,logger:$,extensionContext:f.extensionContext};return LF({providerConfigs:[{providerId:H.providerId,apiKey:H.apiKey,baseUrl:H.baseUrl,headers:H.headers,models:H.knownModels?Object.entries(H.knownModels).map(([Q,Z])=>({id:Q,name:Z.name??Q,description:Z.description,contextWindow:Z.contextWindow,maxOutputTokens:Z.maxTokens})):void 0}],logger:$}).createAgentModel({providerId:H.providerId,modelId:H.modelId},{maxTokens:H.maxOutputTokens})}import{normalizeUserInput as h7}from"@cline/shared";var OF=50000,zF=6000000,O7=8000,NF=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),qF=new Set(["read","read_files"]),O$="[outdated - see the latest file content]",z7="Tool execution was interrupted before a result was produced.",wF=(f)=>`
396
396
 
397
397
  ...[truncated ${f} chars]...
398
398
 
399
- `,XF=(f)=>`
399
+ `,bF=(f)=>`
400
400
 
401
401
  ...[truncated ${f} chars to fit provider request budget]...
402
402
 
403
- `;class XW{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor(f=WF,$=ZF,J=QF){this.maxToolResultChars=f;this.targetToolNames=$;this.maxTotalTextBytes=J}buildForApi(f){this.reindex(f);let J=this.addMissingToolResults(f).map((H)=>{if(!Array.isArray(H.content)){if(H.role==="user"&&typeof H.content==="string"){let Z=AQ(H.content);if(Z!==H.content)return{...H,content:Z}}return H}let W=!1,Q=H.content.map((Z)=>{let j=this.transformBlock(Z,H.role);if(j!==Z)W=!0;return j});return W?{...H,content:Q}:H});return this.truncateToTotalTextBudget(J)}transformBlock(f,$){if($==="user"&&f.type==="text"&&typeof f.text==="string"){let W=AQ(f.text);if(W!==f.text)return{...f,text:W};return f}if(f.type==="file"){let W=this.truncateMiddle(f.content);return W===f.content?f:{...f,content:W}}if(f.type!=="tool_result")return f;let J=this.toolNameByIdCache.get(f.tool_use_id),H=f.content;if(this.isReadTool(J)&&f.is_error!==!0){let W=this.getReadLocators(f);if(W.length>0){let Q=W.filter((Z)=>this.isOutdatedReadLocator(Z,f.tool_use_id));if(Q.length>0)H=this.replaceOutdatedReadContent(H,Q)}}if(this.shouldTruncateTool(J))H=this.truncateToolResultContent(H);return H===f.content?f:{...f,content:H}}reindex(f){let $=this.indexedMessageCount===0||f.length>=this.indexedMessageCount&&f[this.indexedMessageCount-1]===this.indexedTailRef;if(f.length<this.indexedMessageCount||!$)this.resetIndexes();for(let J=this.indexedMessageCount;J<f.length;J++){let H=f[J];if(!Array.isArray(H.content))continue;for(let W=0;W<H.content.length;W++){let Q=H.content[W];if(Q.type==="file")this.latestFullContentOwnerByPathCache.set(Q.path,`file:${J}:${W}`);else if(Q.type==="tool_use"){let Z=Q.name.toLowerCase();if(this.toolNameByIdCache.set(Q.id,Z),this.isReadTool(Z)){let j=this.extractLocatorsFromReadToolInput(Q.input);if(j.length>0)this.readLocatorsByToolUseIdCache.set(Q.id,j)}}else if(Q.type==="tool_result"){let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.isReadTool(Z)||Q.is_error===!0)continue;let j=this.getReadLocators(Q);for(let P of j)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(P),Q.tool_use_id),this.isFullFileRead(P))this.latestFullContentOwnerByPathCache.set(P.path,Q.tool_use_id)}}}this.indexedMessageCount=f.length,this.indexedTailRef=f.length>0?f[f.length-1]:void 0}addMissingToolResults(f){let $=this.collectToolResultIds(f),J=[],H=new Map,W=!1,Q=()=>{if(H.size===0)return;Z(this.createMissingToolResultMessage(H)),H.clear(),W=!0},Z=(j)=>{let P=J.at(-1);if(this.shouldMergeUserAfterToolResults(P,j)){J[J.length-1]={...P,content:[...P.content,...this.contentBlocksForUserMerge(j.content)]},W=!0;return}J.push(j)};for(let j of f){if(this.isToolResultOnlyMessage(j)){if(Z(this.appendMissingToolResults(j,H)),H.size>0)H.clear(),W=!0;continue}if(Array.isArray(j.content)){let P=j.content.filter((V)=>V.type==="tool_result"),X=j.content.filter((V)=>V.type!=="tool_result");if(P.length>0){let V=this.appendMissingToolResults({...j,role:"user",content:P},H);if(Z(V),H.size>0)H.clear();W=!0}if(X.length>0||P.length===0){if(P.length===0)Q();let V=P.length>0?{...j,content:X}:j;if(Z(V),V.role==="assistant")this.trackMissingToolCalls(V,$,H)}continue}Q(),Z(j)}return Q(),W?J:f}appendMissingToolResults(f,$){if($.size===0||!Array.isArray(f.content))return f;return{...f,role:"user",content:[...f.content,...this.createMissingToolResultBlocks($)]}}shouldMergeUserAfterToolResults(f,$){return f?.role==="user"&&$.role==="user"&&this.isToolResultOnlyMessage(f)&&this.contentBlocksForUserMerge($.content).length>0}contentBlocksForUserMerge(f){return typeof f==="string"?f.length>0?[{type:"text",text:f}]:[]:f}collectToolResultIds(f){let $=new Set;for(let J of f){if(!Array.isArray(J.content))continue;for(let H of J.content)if(H.type==="tool_result")$.add(H.tool_use_id)}return $}isToolResultOnlyMessage(f){return f.role==="user"&&Array.isArray(f.content)&&f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}trackMissingToolCalls(f,$,J){if(!Array.isArray(f.content))return;for(let H of f.content){if(H.type!=="tool_use"||$.has(H.id))continue;J.set(H.id,H.name)}}createMissingToolResultMessage(f){return{role:"user",content:this.createMissingToolResultBlocks(f)}}createMissingToolResultBlocks(f){return Array.from(f,([$,J])=>({type:"tool_result",tool_use_id:$,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText(f){return f?`${FQ} Tool: ${f}.`:FQ}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators(f){let $=f,J=this.readResultLocatorCache.get($);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent(f.content),this.readResultLocatorCache.set($,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get(f.tool_use_id)??[]}extractLocatorsFromReadToolInput(f){if(!f||typeof f!=="object")return[];let $=f,J=[],H=this.extractLocatorFromReadRequest($);if(H)J.push(H);if(Array.isArray($.files))for(let W of $.files){let Q=this.extractLocatorFromReadRequest(W);if(Q)J.push(Q)}if(Array.isArray($.file_paths)){for(let W of $.file_paths)if(typeof W==="string"&&W.length>0)J.push({path:W,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent(f){if(typeof f==="string")return this.tryParseReadLocators(f);for(let $ of f){if($.type!=="text")continue;let J=this.tryParseReadLocators($.text);if(J.length>0)return J}return[]}tryParseReadLocators(f){try{return this.extractLocatorsFromParsedReadResult(JSON.parse(f))}catch{return[]}}extractLocatorsFromParsedReadResult(f){if(Array.isArray(f)){let J=[];for(let H of f){let W=this.extractLocatorFromResultEntry(H);if(W)J.push(W)}return this.dedupeReadLocators(J)}let $=this.extractLocatorFromResultEntry(f);return $?[$]:[]}extractLocatorFromReadRequest(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(!J)return;return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)}}extractLocatorFromResultEntry(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(J)return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)};if(typeof $.query==="string"&&$.query.length>0)return this.parseReadQuery($.query);return}extractPath(f){let $=[f.path,f.file_path,f.filePath];for(let J of $)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber(f){return typeof f==="number"&&Number.isInteger(f)?f:null}parseReadQuery(f){let $=/^(.*):(\d+)-(EOF|\d+)$/.exec(f);if(!$)return{path:f,startLine:null,endLine:null};return{path:$[1],startLine:Number($[2]),endLine:$[3]==="EOF"?null:Number($[3])}}dedupeReadLocators(f){let $=new Map;for(let J of f)$.set(this.toReadLocatorKey(J),J);return Array.from($.values())}toReadLocatorKey(f){if(this.isFullFileRead(f))return f.path;return`${f.path}:${f.startLine??1}-${f.endLine??"EOF"}`}isFullFileRead(f){return f.startLine==null&&f.endLine==null}isOutdatedReadLocator(f,$){let J=this.latestFullContentOwnerByPathCache.get(f.path);if(J&&J!==$)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey(f))!==$}replaceOutdatedReadContent(f,$){let J=new Set($.map((Q)=>this.toReadLocatorKey(Q))),H=new Set($.map((Q)=>Q.path));if(typeof f==="string")return this.replaceOutdatedInString(f,J)??M$;let W=0;for(let Q of f)if(Q.type==="text")W+=this.countOutdatedImageEntries(Q.text,J);return f.map((Q)=>{if(Q.type==="file"){if(!H.has(Q.path))return Q;return{...Q,content:M$}}if(Q.type==="image"){if(W===0)return Q;return W-=1,{type:"text",text:M$}}if(Q.type!=="text")return Q;let Z=this.replaceOutdatedInString(Q.text,J);if(Z===null)return{...Q,text:M$};return Z===Q.text?Q:{...Q,text:Z}})}countOutdatedImageEntries(f,$){let J;try{J=JSON.parse(f)}catch{return 0}let H=Array.isArray(J)?J:[J],W=0;for(let Q of H){if(!Q||typeof Q!=="object")continue;let Z=Q,j=this.extractLocatorFromResultEntry(Z);if(!j)continue;if(!$.has(this.toReadLocatorKey(j)))continue;if(Z.result==="Successfully read image"||Z.content==="Successfully read image")W+=1}return W}replaceOutdatedInString(f,$){let J;try{J=JSON.parse(f)}catch{return null}let H=Array.isArray(J)?J.map((W)=>this.replaceOutdatedReadEntry(W,$)):this.replaceOutdatedReadEntry(J,$);return JSON.stringify(H)}replaceOutdatedReadEntry(f,$){if(!f||typeof f!=="object")return f;let J=this.extractLocatorFromResultEntry(f);if(!J||!$.has(this.toReadLocatorKey(J)))return f;let H={...f};if(typeof H.result==="string")H.result=M$;else if(typeof H.content==="string")H.content=M$;else H.result=M$;return H}isReadTool(f){return!!f&&jF.has(f)}shouldTruncateTool(f){return!!f&&this.targetToolNames.has(f)}truncateToolResultContent(f){if(typeof f==="string")return this.truncateMiddle(f);return f.map(($)=>{if($.type==="file"){let H=this.truncateMiddle($.content);return H===$.content?$:{...$,content:H}}if($.type!=="text")return $;let J=this.truncateMiddle($.text);return J===$.text?$:{...$,text:J}})}truncateMiddle(f){return PW(f,this.maxToolResultChars,PF)}truncateToTotalTextBudget(f){if(this.maxTotalTextBytes<=0)return f;let $=this.countMessageTextBytes(f);if($<=this.maxTotalTextBytes)return f;let J=f.map((W)=>{if(!Array.isArray(W.content))return W;return{...W,content:W.content.map((Q)=>YF(Q))}}),H=this.collectTruncationCandidates(J);for(let W of H){if($<=this.maxTotalTextBytes)break;let Q=W.byteLength;if(Q<=RQ)continue;let Z=$-this.maxTotalTextBytes,j=Math.max(RQ,Q-Z),P=VF(W.get(),j,XF);W.set(P),$-=Q-Uf(P)}return J}countMessageTextBytes(f){let $=0;for(let J of f){if(typeof J.content==="string"){$+=Uf(J.content);continue}for(let H of J.content)if(H.type==="text")$+=Uf(H.text);else if(H.type==="thinking")$+=Uf(H.thinking);else if(H.type==="file")$+=Uf(H.content);else if(H.type==="tool_result"){if(typeof H.content==="string")$+=Uf(H.content);else for(let W of H.content)if(W.type==="text")$+=Uf(W.text);else if(W.type==="file")$+=Uf(W.content)}}return $}collectTruncationCandidates(f){let $=[];for(let J of f){if(!Array.isArray(J.content))continue;for(let H of J.content){if(H.type!=="tool_result")continue;let W=this.toolNameByIdCache.get(H.tool_use_id);if(!this.shouldTruncateTool(W))continue;if(typeof H.content==="string"){$.push({byteLength:Uf(H.content),get:()=>H.content,set:(Q)=>{H.content=Q}});continue}for(let Q of H.content)if(Q.type==="text")$.push({byteLength:Uf(Q.text),get:()=>Q.text,set:(Z)=>{Q.text=Z}});else if(Q.type==="file")$.push({byteLength:Uf(Q.content),get:()=>Q.content,set:(Z)=>{Q.content=Z}})}}return $.sort((J,H)=>H.byteLength-J.byteLength)}}function Uf(f){return Buffer.byteLength(f,"utf8")}function PW(f,$,J){if(f.length<=$)return f;let H=J(f.length-$),W=Math.max(0,Math.floor(($-H.length)/2)),Q=Math.max(0,f.length-W*2),Z=J(Q),j=Math.max(0,Math.floor(($-Z.length)/2)),P=f.slice(0,j),X=j>0?f.slice(-j):"";return`${P}${Z}${X}`}function VF(f,$,J){if(Uf(f)<=$)return f;let H=0,W=f.length,Q=PW(f,0,J);while(H<=W){let Z=H+W>>>1,j=PW(f,Z,J);if(Uf(j)<=$)Q=j,H=Z+1;else W=Z-1}return Q}function YF(f){if(f.type!=="tool_result"||typeof f.content==="string")return{...f};return{...f,content:f.content.map(($)=>({...$}))}}function VW(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class YW{messages=[];conversationId=VW();sessionStarted=!1;constructor(f){if((f?.length??0)>0)this.restore(f??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage(f){this.messages.push(f)}appendMessages(f){if(f.length===0)return;this.messages.push(...f)}replaceMessages(f){this.messages=[...f]}resetForRun(){this.messages=[],this.conversationId=VW(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=VW(),this.sessionStarted=!1}restore(f){this.messages=[...f],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function BF(f){let $=RF(f.content),J=[],H=f.id??KF(),W=0,Q=[],Z=()=>{if(Q.length===0)return;let j=W===0?H:`${H}_part_${W}`;W+=1,J.push({id:j,role:f.role,content:Q.map(FF),createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:yQ(f.metrics)}),Q=[]};if($.length===0)return J.push({id:H,role:f.role,content:[],createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:yQ(f.metrics)}),J;for(let j of $){if(j.type!=="tool_result"){Q.push(j);continue}Z(),J.push({id:`${H}_tool_${j.tool_use_id}`,role:"tool",content:[GQ(j)],createdAt:f.ts??Date.now(),metadata:f.metadata})}return Z(),J}function R6(f){return f.flatMap(BF)}function AF(f){let $=f.content.map(hQ).filter((J)=>J!==void 0);return{id:f.id,role:f.role==="tool"?"user":f.role,content:$,ts:f.createdAt,metadata:f.metadata,modelInfo:f.modelInfo,metrics:yF(f.metrics)}}function G1(f){return f.map(AF)}function UQ(f){let $=[];for(let J of f){let H=J.content.map(hQ).filter((Z)=>Z!==void 0),W=J.role==="tool"?"user":J.role,Q=$[$.length-1];if(W==="user"&&H.length>0&&H.every((Z)=>Z.type==="tool_result")&&Q?.role==="user"&&Array.isArray(Q.content)&&Q.content.every((Z)=>Z.type==="tool_result")){Q.content.push(...H);continue}$.push({role:W,content:H})}return $}function RF(f){if(typeof f==="string")return f.length>0?[{type:"text",text:f}]:[];return[...f]}function FF(f){switch(f.type){case"text":return{type:"text",text:f.text};case"thinking":return{type:"reasoning",text:f.thinking,metadata:f.signature?{signature:f.signature,details:f.details}:f.details?{details:f.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:f.data}};case"image":return{type:"image",image:f.data,mediaType:f.mediaType};case"file":return{type:"file",path:f.path,content:f.content};case"tool_use":return{type:"tool-call",toolCallId:f.id,toolName:f.name,input:f.input,metadata:f.signature?{signature:f.signature}:void 0};case"tool_result":return GQ(f)}}function GQ(f){return{type:"tool-result",toolCallId:f.tool_use_id,toolName:"",output:f.content,isError:f.is_error}}function hQ(f){switch(f.type){case"text":return{type:"text",text:f.text};case"reasoning":{if(f.redacted===!0)return{type:"redacted_thinking",data:f.metadata?.data??""};let $=f.metadata;return{type:"thinking",thinking:f.text,signature:$?.signature,details:$?.details}}case"image":return typeof f.image==="string"?{type:"image",data:f.image,mediaType:f.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:f.path,content:f.content};case"tool-call":return{type:"tool_use",id:f.toolCallId,name:f.toolName,input:f.input??{},signature:f.metadata?.signature};case"tool-result":{let $=f.output,J=typeof $==="string"?$:Array.isArray($)?$:JSON.stringify($);return{type:"tool_result",tool_use_id:f.toolCallId,content:J,is_error:f.isError}}}}function yQ(f){if(!f)return;return{inputTokens:f.inputTokens??0,outputTokens:f.outputTokens??0,cacheReadTokens:f.cacheReadTokens??0,cacheWriteTokens:f.cacheWriteTokens??0,cost:f.cost}}function yF(f){if(!f)return;return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,cost:f.cost}}var KQ=0;function KF(){return KQ+=1,`msg_${Date.now().toString(36)}_${KQ.toString(36)}`}function TQ(f){let{agentConfig:$}=f,J=UF($),H=GF($),W=f.hooks,Q=hF($.maxParallelToolCalls);return{sessionId:f.sessionId??$.sessionId,agentId:f.agentId,conversationId:f.conversationId,parentAgentId:f.parentAgentId,agentRole:f.agentRole,systemPrompt:f.systemPrompt??$.systemPrompt,messageModelInfo:H,model:f.model,modelOptions:J,tools:f.tools,hooks:W,prepareTurn:f.prepareTurn,consumePendingUserMessage:$.consumePendingUserMessage,plugins:f.plugins,logger:f.logger??$.logger,telemetry:f.telemetry??TF($.telemetry),initialMessages:f.initialMessages,completionPolicy:$.completionPolicy,maxIterations:$.maxIterations,toolExecution:Q,toolPolicies:$.toolPolicies,toolContextMetadata:f.toolContextMetadata,requestToolApproval:$.requestToolApproval}}function UF(f){let $={};if(f.thinking!==void 0)$.thinking=f.thinking;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;if(f.maxTokensPerTurn!==void 0)$.maxTokensPerTurn=f.maxTokensPerTurn;if(f.apiTimeoutMs!==void 0)$.apiTimeoutMs=f.apiTimeoutMs;return Object.keys($).length>0?$:void 0}function GF(f){let $=f.providerConfig?.family;return{id:f.modelId,provider:f.providerId,family:$}}function hF(f){if(f===void 0)return;return f>=2?"parallel":"sequential"}function TF(f){if(!f)return;return{capture:($,J)=>{f.capture({event:$,properties:J})}}}function DF(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function MF(f){f.lastToolName="",f.lastToolSignature="",f.consecutiveIdenticalCount=0}function BW(f){if(f==null||typeof f!=="object")return f;if(Array.isArray(f))return f.map(BW);let $={};for(let J of Object.keys(f).sort())$[J]=BW(f[J]);return $}function _F(f){if(f==null)return"null";if(typeof f==="string")return f;if(typeof f!=="object")return String(f);try{return JSON.stringify(BW(f))}catch{return String(f)}}function LF(f,$,J,H){if($===f.lastToolName&&J===f.lastToolSignature)f.consecutiveIdenticalCount++;else f.consecutiveIdenticalCount=1;return f.lastToolName=$,f.lastToolSignature=J,{softWarning:f.consecutiveIdenticalCount===H.softThreshold,hardEscalation:f.consecutiveIdenticalCount>=H.hardThreshold}}var DQ={softThreshold:3,hardThreshold:5};class AW{config;state=DF();constructor(f){this.config={softThreshold:f?.softThreshold??DQ.softThreshold,hardThreshold:f?.hardThreshold??DQ.hardThreshold}}inspect(f){let $=_F(f.input),J=LF(this.state,f.name,$,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){MF(this.state)}}class RW{consecutiveMistakes=0;options;constructor(f){this.options=f}async record(f){let $=this.options.maxConsecutiveMistakes,J=f.forceAtLimit&&$?$:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let H=f.details?.trim()||`consecutive mistake (${f.reason})`;if(this.options.emit({type:"error",error:Error(H),recoverable:!0,iteration:f.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:f.iteration,reason:f.reason,details:f.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!$||J<$)return{action:"continue"};let W=await OF({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details},this.options.onLimitReached);if(W.action==="continue"){let Q=W.guidance?.trim();if(Q)this.options.appendRecoveryNotice(Q,f.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:Q}}return{action:"stop",reason:W.reason?.trim()||void 0,message:zF({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details,stopReason:W.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function zF(f){let $=[`Stopped after ${f.consecutiveMistakes}/${f.maxConsecutiveMistakes} consecutive mistakes (${f.reason}) at iteration ${f.iteration}.`],J=f.details?.trim();if(J)$.push(`Error: ${J}`);let H=f.stopReason?.trim();if(H)$.push(`Decision: ${H}`);return $.push("Session state was preserved. Send a new prompt to resume from the latest state."),$.join(" ")}async function OF(f,$){if(!$)return{action:"stop",reason:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`};try{return await $(f)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`}}}function NF(f){let $=f.content.filter((J)=>J.type==="text");if($.length===0)return;return $.map((J)=>J.text).join("")}function qF(f){let $=f.content.filter((J)=>J.type==="reasoning");if($.length===0)return;return{reasoning:$.map((J)=>J.text).join(""),redacted:$.some((J)=>J.redacted===!0)}}function bF(f){return f.content.find(($)=>$.type==="tool-result")}function wF(f){switch(f){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function CF(f){if(!f||f.isError!==!0)return;if(typeof f.output==="string")return f.output;if(f.output instanceof Error)return f.output.message;try{return JSON.stringify(f.output)}catch{return String(f.output)}}class FW{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate(f){switch(f.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:f.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:f.iteration,hadToolCalls:f.toolCallCount>0,toolCallCount:f.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:f.text,accumulated:f.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:f.text,redacted:f.redacted===!0}];case"assistant-message":return this.translateAssistantMessage(f.message);case"tool-started":return this.translateToolStarted(f);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,update:f.update}];case"tool-finished":return this.translateToolFinished(f);case"usage-updated":return this.translateUsage(f.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:f.message,reason:f.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:f.metadata}];case"run-finished":return this.translateRunFinished(f.result);case"run-failed":return[{type:"error",error:f.error,recoverable:!1,iteration:f.snapshot.iteration}];default:return f}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage(f){let $=[],J=NF(f);if(J!==void 0)$.push({type:"content_end",contentType:"text",text:J});let H=qF(f);if(H!==void 0)$.push({type:"content_end",contentType:"reasoning",reasoning:H.reasoning});return $}translateToolStarted(f){return this.toolStartedAt.set(f.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,input:f.toolCall.input}]}translateToolFinished(f){let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=$===void 0?void 0:Date.now()-$;this.toolStartedAt.delete(f.toolCall.toolCallId);let H=bF(f.message),W=H?.output,Q=CF(H);return[{type:"content_end",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,output:W,error:Q,durationMs:J}]}translateUsage(f){let $=f.inputTokens-this.lastUsage.inputTokens,J=f.outputTokens-this.lastUsage.outputTokens,H=f.cacheReadTokens-this.lastUsage.cacheReadTokens,W=f.cacheWriteTokens-this.lastUsage.cacheWriteTokens,Q=this.lastUsage.totalCost??0,j=(f.totalCost??0)-Q;return this.lastUsage={inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,totalCost:f.totalCost},[{type:"usage",inputTokens:Math.max(0,$),outputTokens:Math.max(0,J),cacheReadTokens:H===0?void 0:Math.max(0,H),cacheWriteTokens:W===0?void 0:Math.max(0,W),cost:j===0?void 0:j,totalInputTokens:f.inputTokens,totalOutputTokens:f.outputTokens,totalCacheReadTokens:f.cacheReadTokens===0?void 0:f.cacheReadTokens,totalCacheWriteTokens:f.cacheWriteTokens===0?void 0:f.cacheWriteTokens,totalCost:f.totalCost}]}translateRunFinished(f){let $={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens===0?void 0:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens===0?void 0:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost};return[{type:"done",reason:wF(f.status),text:f.outputText,iterations:f.iterations,usage:$}]}}function vF(f){if(typeof f==="string")return f;if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}}async function uF(f){let J=(typeof f.content==="function"?await f.content():f.content).trim();return J.length>0?J:void 0}function cF(f,$){let J=f.trim(),H=$.map((W)=>W.trim()).filter(Boolean).join(`
403
+ `;class BW{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor(f=OF,$=NF,J=zF){this.maxToolResultChars=f;this.targetToolNames=$;this.maxTotalTextBytes=J}buildForApi(f){this.reindex(f);let J=this.addMissingToolResults(f).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let Z=h7(W.content);if(Z!==W.content)return{...W,content:Z}}return W}let H=!1,Q=W.content.map((Z)=>{let j=this.transformBlock(Z,W.role);if(j!==Z)H=!0;return j});return H?{...W,content:Q}:W});return this.truncateToTotalTextBudget(J)}transformBlock(f,$){if($==="user"&&f.type==="text"&&typeof f.text==="string"){let H=h7(f.text);if(H!==f.text)return{...f,text:H};return f}if(f.type==="file"){let H=this.truncateMiddle(f.content);return H===f.content?f:{...f,content:H}}if(f.type!=="tool_result")return f;let J=this.toolNameByIdCache.get(f.tool_use_id),W=f.content;if(this.isReadTool(J)&&f.is_error!==!0){let H=this.getReadLocators(f);if(H.length>0){let Q=H.filter((Z)=>this.isOutdatedReadLocator(Z,f.tool_use_id));if(Q.length>0)W=this.replaceOutdatedReadContent(W,Q)}}if(this.shouldTruncateTool(J))W=this.truncateToolResultContent(W);return W===f.content?f:{...f,content:W}}reindex(f){let $=this.indexedMessageCount===0||f.length>=this.indexedMessageCount&&f[this.indexedMessageCount-1]===this.indexedTailRef;if(f.length<this.indexedMessageCount||!$)this.resetIndexes();for(let J=this.indexedMessageCount;J<f.length;J++){let W=f[J];if(!Array.isArray(W.content))continue;for(let H=0;H<W.content.length;H++){let Q=W.content[H];if(Q.type==="file")this.latestFullContentOwnerByPathCache.set(Q.path,`file:${J}:${H}`);else if(Q.type==="tool_use"){let Z=Q.name.toLowerCase();if(this.toolNameByIdCache.set(Q.id,Z),this.isReadTool(Z)){let j=this.extractLocatorsFromReadToolInput(Q.input);if(j.length>0)this.readLocatorsByToolUseIdCache.set(Q.id,j)}}else if(Q.type==="tool_result"){let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.isReadTool(Z)||Q.is_error===!0)continue;let j=this.getReadLocators(Q);for(let X of j)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(X),Q.tool_use_id),this.isFullFileRead(X))this.latestFullContentOwnerByPathCache.set(X.path,Q.tool_use_id)}}}this.indexedMessageCount=f.length,this.indexedTailRef=f.length>0?f[f.length-1]:void 0}addMissingToolResults(f){let $=this.collectToolResultIds(f),J=[],W=new Map,H=!1,Q=()=>{if(W.size===0)return;Z(this.createMissingToolResultMessage(W)),W.clear(),H=!0},Z=(j)=>{let X=J.at(-1);if(this.shouldMergeUserAfterToolResults(X,j)){J[J.length-1]={...X,content:[...X.content,...this.contentBlocksForUserMerge(j.content)]},H=!0;return}J.push(j)};for(let j of f){if(this.isToolResultOnlyMessage(j)){if(Z(this.appendMissingToolResults(j,W)),W.size>0)W.clear(),H=!0;continue}if(Array.isArray(j.content)){let X=j.content.filter((P)=>P.type==="tool_result"),A=j.content.filter((P)=>P.type!=="tool_result");if(X.length>0){let P=this.appendMissingToolResults({...j,role:"user",content:X},W);if(Z(P),W.size>0)W.clear();H=!0}if(A.length>0||X.length===0){if(X.length===0)Q();let P=X.length>0?{...j,content:A}:j;if(Z(P),P.role==="assistant")this.trackMissingToolCalls(P,$,W)}continue}Q(),Z(j)}return Q(),H?J:f}appendMissingToolResults(f,$){if($.size===0||!Array.isArray(f.content))return f;return{...f,role:"user",content:[...f.content,...this.createMissingToolResultBlocks($)]}}shouldMergeUserAfterToolResults(f,$){return f?.role==="user"&&$.role==="user"&&this.isToolResultOnlyMessage(f)&&this.contentBlocksForUserMerge($.content).length>0}contentBlocksForUserMerge(f){return typeof f==="string"?f.length>0?[{type:"text",text:f}]:[]:f}collectToolResultIds(f){let $=new Set;for(let J of f){if(!Array.isArray(J.content))continue;for(let W of J.content)if(W.type==="tool_result")$.add(W.tool_use_id)}return $}isToolResultOnlyMessage(f){return f.role==="user"&&Array.isArray(f.content)&&f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}trackMissingToolCalls(f,$,J){if(!Array.isArray(f.content))return;for(let W of f.content){if(W.type!=="tool_use"||$.has(W.id))continue;J.set(W.id,W.name)}}createMissingToolResultMessage(f){return{role:"user",content:this.createMissingToolResultBlocks(f)}}createMissingToolResultBlocks(f){return Array.from(f,([$,J])=>({type:"tool_result",tool_use_id:$,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText(f){return f?`${z7} Tool: ${f}.`:z7}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators(f){let $=f,J=this.readResultLocatorCache.get($);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent(f.content),this.readResultLocatorCache.set($,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get(f.tool_use_id)??[]}extractLocatorsFromReadToolInput(f){if(!f||typeof f!=="object")return[];let $=f,J=[],W=this.extractLocatorFromReadRequest($);if(W)J.push(W);if(Array.isArray($.files))for(let H of $.files){let Q=this.extractLocatorFromReadRequest(H);if(Q)J.push(Q)}if(Array.isArray($.file_paths)){for(let H of $.file_paths)if(typeof H==="string"&&H.length>0)J.push({path:H,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent(f){if(typeof f==="string")return this.tryParseReadLocators(f);for(let $ of f){if($.type!=="text")continue;let J=this.tryParseReadLocators($.text);if(J.length>0)return J}return[]}tryParseReadLocators(f){try{return this.extractLocatorsFromParsedReadResult(JSON.parse(f))}catch{return[]}}extractLocatorsFromParsedReadResult(f){if(Array.isArray(f)){let J=[];for(let W of f){let H=this.extractLocatorFromResultEntry(W);if(H)J.push(H)}return this.dedupeReadLocators(J)}let $=this.extractLocatorFromResultEntry(f);return $?[$]:[]}extractLocatorFromReadRequest(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(!J)return;return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)}}extractLocatorFromResultEntry(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(J)return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)};if(typeof $.query==="string"&&$.query.length>0)return this.parseReadQuery($.query);return}extractPath(f){let $=[f.path,f.file_path,f.filePath];for(let J of $)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber(f){return typeof f==="number"&&Number.isInteger(f)?f:null}parseReadQuery(f){let $=/^(.*):(\d+)-(EOF|\d+)$/.exec(f);if(!$)return{path:f,startLine:null,endLine:null};return{path:$[1],startLine:Number($[2]),endLine:$[3]==="EOF"?null:Number($[3])}}dedupeReadLocators(f){let $=new Map;for(let J of f)$.set(this.toReadLocatorKey(J),J);return Array.from($.values())}toReadLocatorKey(f){if(this.isFullFileRead(f))return f.path;return`${f.path}:${f.startLine??1}-${f.endLine??"EOF"}`}isFullFileRead(f){return f.startLine==null&&f.endLine==null}isOutdatedReadLocator(f,$){let J=this.latestFullContentOwnerByPathCache.get(f.path);if(J&&J!==$)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey(f))!==$}replaceOutdatedReadContent(f,$){let J=new Set($.map((Q)=>this.toReadLocatorKey(Q))),W=new Set($.map((Q)=>Q.path));if(typeof f==="string")return this.replaceOutdatedInString(f,J)??O$;let H=0;for(let Q of f)if(Q.type==="text")H+=this.countOutdatedImageEntries(Q.text,J);return f.map((Q)=>{if(Q.type==="file"){if(!W.has(Q.path))return Q;return{...Q,content:O$}}if(Q.type==="image"){if(H===0)return Q;return H-=1,{type:"text",text:O$}}if(Q.type!=="text")return Q;let Z=this.replaceOutdatedInString(Q.text,J);if(Z===null)return{...Q,text:O$};return Z===Q.text?Q:{...Q,text:Z}})}countOutdatedImageEntries(f,$){let J;try{J=JSON.parse(f)}catch{return 0}let W=Array.isArray(J)?J:[J],H=0;for(let Q of W){if(!Q||typeof Q!=="object")continue;let Z=Q,j=this.extractLocatorFromResultEntry(Z);if(!j)continue;if(!$.has(this.toReadLocatorKey(j)))continue;if(Z.result==="Successfully read image"||Z.content==="Successfully read image")H+=1}return H}replaceOutdatedInString(f,$){let J;try{J=JSON.parse(f)}catch{return null}let W=Array.isArray(J)?J.map((H)=>this.replaceOutdatedReadEntry(H,$)):this.replaceOutdatedReadEntry(J,$);return JSON.stringify(W)}replaceOutdatedReadEntry(f,$){if(!f||typeof f!=="object")return f;let J=this.extractLocatorFromResultEntry(f);if(!J||!$.has(this.toReadLocatorKey(J)))return f;let W={...f};if(typeof W.result==="string")W.result=O$;else if(typeof W.content==="string")W.content=O$;else W.result=O$;return W}isReadTool(f){return!!f&&qF.has(f)}shouldTruncateTool(f){return!!f&&this.targetToolNames.has(f)}truncateToolResultContent(f){if(typeof f==="string")return this.truncateMiddle(f);return f.map(($)=>{if($.type==="file"){let W=this.truncateMiddle($.content);return W===$.content?$:{...$,content:W}}if($.type!=="text")return $;let J=this.truncateMiddle($.text);return J===$.text?$:{...$,text:J}})}truncateMiddle(f){return PW(f,this.maxToolResultChars,wF)}truncateToTotalTextBudget(f){if(this.maxTotalTextBytes<=0)return f;let $=this.countMessageTextBytes(f);if($<=this.maxTotalTextBytes)return f;let J=f.map((H)=>{if(!Array.isArray(H.content))return H;return{...H,content:H.content.map((Q)=>EF(Q))}}),W=this.collectTruncationCandidates(J);for(let H of W){if($<=this.maxTotalTextBytes)break;let Q=H.byteLength;if(Q<=O7)continue;let Z=$-this.maxTotalTextBytes,j=Math.max(O7,Q-Z),X=CF(H.get(),j,bF);H.set(X),$-=Q-Mf(X)}return J}countMessageTextBytes(f){let $=0;for(let J of f){if(typeof J.content==="string"){$+=Mf(J.content);continue}for(let W of J.content)if(W.type==="text")$+=Mf(W.text);else if(W.type==="thinking")$+=Mf(W.thinking);else if(W.type==="file")$+=Mf(W.content);else if(W.type==="tool_result"){if(typeof W.content==="string")$+=Mf(W.content);else for(let H of W.content)if(H.type==="text")$+=Mf(H.text);else if(H.type==="file")$+=Mf(H.content)}}return $}collectTruncationCandidates(f){let $=[];for(let J of f){if(!Array.isArray(J.content))continue;for(let W of J.content){if(W.type!=="tool_result")continue;let H=this.toolNameByIdCache.get(W.tool_use_id);if(!this.shouldTruncateTool(H))continue;if(typeof W.content==="string"){$.push({byteLength:Mf(W.content),get:()=>W.content,set:(Q)=>{W.content=Q}});continue}for(let Q of W.content)if(Q.type==="text")$.push({byteLength:Mf(Q.text),get:()=>Q.text,set:(Z)=>{Q.text=Z}});else if(Q.type==="file")$.push({byteLength:Mf(Q.content),get:()=>Q.content,set:(Z)=>{Q.content=Z}})}}return $.sort((J,W)=>W.byteLength-J.byteLength)}}function Mf(f){return Buffer.byteLength(f,"utf8")}function PW(f,$,J){if(f.length<=$)return f;let W=J(f.length-$),H=Math.max(0,Math.floor(($-W.length)/2)),Q=Math.max(0,f.length-H*2),Z=J(Q),j=Math.max(0,Math.floor(($-Z.length)/2)),X=f.slice(0,j),A=j>0?f.slice(-j):"";return`${X}${Z}${A}`}function CF(f,$,J){if(Mf(f)<=$)return f;let W=0,H=f.length,Q=PW(f,0,J);while(W<=H){let Z=W+H>>>1,j=PW(f,Z,J);if(Mf(j)<=$)Q=j,W=Z+1;else H=Z-1}return Q}function EF(f){if(f.type!=="tool_result"||typeof f.content==="string")return{...f};return{...f,content:f.content.map(($)=>({...$}))}}function YW(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class VW{messages=[];conversationId=YW();sessionStarted=!1;constructor(f){if((f?.length??0)>0)this.restore(f??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage(f){this.messages.push(f)}appendMessages(f){if(f.length===0)return;this.messages.push(...f)}replaceMessages(f){this.messages=[...f]}resetForRun(){this.messages=[],this.conversationId=YW(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=YW(),this.sessionStarted=!1}restore(f){this.messages=[...f],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function SF(f){let $=IF(f.content),J=[],W=f.id??gF(),H=0,Q=[],Z=()=>{if(Q.length===0)return;let j=H===0?W:`${W}_part_${H}`;H+=1,J.push({id:j,role:f.role,content:Q.map(mF),createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:N7(f.metrics)}),Q=[]};if($.length===0)return J.push({id:W,role:f.role,content:[],createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:N7(f.metrics)}),J;for(let j of $){if(j.type!=="tool_result"){Q.push(j);continue}Z(),J.push({id:`${W}_tool_${j.tool_use_id}`,role:"tool",content:[b7(j)],createdAt:f.ts??Date.now(),metadata:f.metadata})}return Z(),J}function T6(f){return f.flatMap(SF)}function kF(f){let $=f.content.map(C7).filter((J)=>J!==void 0);return{id:f.id,role:f.role==="tool"?"user":f.role,content:$,ts:f.createdAt,metadata:f.metadata,modelInfo:f.modelInfo,metrics:xF(f.metrics)}}function D1(f){return f.map(kF)}function w7(f){let $=[];for(let J of f){let W=J.content.map(C7).filter((Z)=>Z!==void 0),H=J.role==="tool"?"user":J.role,Q=$[$.length-1];if(H==="user"&&W.length>0&&W.every((Z)=>Z.type==="tool_result")&&Q?.role==="user"&&Array.isArray(Q.content)&&Q.content.every((Z)=>Z.type==="tool_result")){Q.content.push(...W);continue}$.push({role:H,content:W})}return $}function IF(f){if(typeof f==="string")return f.length>0?[{type:"text",text:f}]:[];return[...f]}function mF(f){switch(f.type){case"text":return{type:"text",text:f.text};case"thinking":return{type:"reasoning",text:f.thinking,metadata:f.signature?{signature:f.signature,details:f.details}:f.details?{details:f.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:f.data}};case"image":return{type:"image",image:f.data,mediaType:f.mediaType};case"file":return{type:"file",path:f.path,content:f.content};case"tool_use":return{type:"tool-call",toolCallId:f.id,toolName:f.name,input:f.input,metadata:f.signature?{signature:f.signature}:void 0};case"tool_result":return b7(f)}}function b7(f){return{type:"tool-result",toolCallId:f.tool_use_id,toolName:"",output:f.content,isError:f.is_error}}function C7(f){switch(f.type){case"text":return{type:"text",text:f.text};case"reasoning":{if(f.redacted===!0)return{type:"redacted_thinking",data:f.metadata?.data??""};let $=f.metadata;return{type:"thinking",thinking:f.text,signature:$?.signature,details:$?.details}}case"image":return typeof f.image==="string"?{type:"image",data:f.image,mediaType:f.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:f.path,content:f.content};case"tool-call":return{type:"tool_use",id:f.toolCallId,name:f.toolName,input:f.input??{},signature:f.metadata?.signature};case"tool-result":{let $=f.output,J=typeof $==="string"?$:Array.isArray($)?$:JSON.stringify($);return{type:"tool_result",tool_use_id:f.toolCallId,content:J,is_error:f.isError}}}}function N7(f){if(!f)return;return{inputTokens:f.inputTokens??0,outputTokens:f.outputTokens??0,cacheReadTokens:f.cacheReadTokens??0,cacheWriteTokens:f.cacheWriteTokens??0,cost:f.cost}}function xF(f){if(!f)return;return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,cost:f.cost}}var q7=0;function gF(){return q7+=1,`msg_${Date.now().toString(36)}_${q7.toString(36)}`}function E7(f){let{agentConfig:$}=f,J=vF($),W=uF($),H=f.hooks,Q=cF($.maxParallelToolCalls);return{sessionId:f.sessionId??$.sessionId,agentId:f.agentId,conversationId:f.conversationId,parentAgentId:f.parentAgentId,agentRole:f.agentRole,systemPrompt:f.systemPrompt??$.systemPrompt,messageModelInfo:W,model:f.model,modelOptions:J,tools:f.tools,hooks:H,prepareTurn:f.prepareTurn,consumePendingUserMessage:$.consumePendingUserMessage,plugins:f.plugins,logger:f.logger??$.logger,telemetry:f.telemetry??dF($.telemetry),initialMessages:f.initialMessages,completionPolicy:$.completionPolicy,maxIterations:$.maxIterations,toolExecution:Q,toolPolicies:$.toolPolicies,toolContextMetadata:f.toolContextMetadata,requestToolApproval:$.requestToolApproval}}function vF(f){let $={};if(f.thinking!==void 0)$.thinking=f.thinking;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;if(f.maxTokensPerTurn!==void 0)$.maxTokensPerTurn=f.maxTokensPerTurn;if(f.apiTimeoutMs!==void 0)$.apiTimeoutMs=f.apiTimeoutMs;return Object.keys($).length>0?$:void 0}function uF(f){let $=f.providerConfig?.family;return{id:f.modelId,provider:f.providerId,family:$}}function cF(f){if(f===void 0)return;return f>=2?"parallel":"sequential"}function dF(f){if(!f)return;return{capture:($,J)=>{f.capture({event:$,properties:J})}}}function rF(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function lF(f){f.lastToolName="",f.lastToolSignature="",f.consecutiveIdenticalCount=0}function RW(f){if(f==null||typeof f!=="object")return f;if(Array.isArray(f))return f.map(RW);let $={};for(let J of Object.keys(f).sort())$[J]=RW(f[J]);return $}function pF(f){if(f==null)return"null";if(typeof f==="string")return f;if(typeof f!=="object")return String(f);try{return JSON.stringify(RW(f))}catch{return String(f)}}function iF(f,$,J,W){if($===f.lastToolName&&J===f.lastToolSignature)f.consecutiveIdenticalCount++;else f.consecutiveIdenticalCount=1;return f.lastToolName=$,f.lastToolSignature=J,{softWarning:f.consecutiveIdenticalCount===W.softThreshold,hardEscalation:f.consecutiveIdenticalCount>=W.hardThreshold}}var S7={softThreshold:3,hardThreshold:5};class FW{config;state=rF();constructor(f){this.config={softThreshold:f?.softThreshold??S7.softThreshold,hardThreshold:f?.hardThreshold??S7.hardThreshold}}inspect(f){let $=pF(f.input),J=iF(this.state,f.name,$,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){lF(this.state)}}class KW{consecutiveMistakes=0;options;constructor(f){this.options=f}async record(f){let $=this.options.maxConsecutiveMistakes,J=f.forceAtLimit&&$?$:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let W=f.details?.trim()||`consecutive mistake (${f.reason})`;if(this.options.emit({type:"error",error:Error(W),recoverable:!0,iteration:f.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:f.iteration,reason:f.reason,details:f.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!$||J<$)return{action:"continue"};let H=await aF({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details},this.options.onLimitReached);if(H.action==="continue"){let Q=H.guidance?.trim();if(Q)this.options.appendRecoveryNotice(Q,f.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:Q}}return{action:"stop",reason:H.reason?.trim()||void 0,message:nF({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details,stopReason:H.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function nF(f){let $=[`Stopped after ${f.consecutiveMistakes}/${f.maxConsecutiveMistakes} consecutive mistakes (${f.reason}) at iteration ${f.iteration}.`],J=f.details?.trim();if(J)$.push(`Error: ${J}`);let W=f.stopReason?.trim();if(W)$.push(`Decision: ${W}`);return $.push("Session state was preserved. Send a new prompt to resume from the latest state."),$.join(" ")}async function aF(f,$){if(!$)return{action:"stop",reason:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`};try{return await $(f)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`}}}function tF(f){let $=f.content.filter((J)=>J.type==="text");if($.length===0)return;return $.map((J)=>J.text).join("")}function sF(f){let $=f.content.filter((J)=>J.type==="reasoning");if($.length===0)return;return{reasoning:$.map((J)=>J.text).join(""),redacted:$.some((J)=>J.redacted===!0)}}function oF(f){return f.content.find(($)=>$.type==="tool-result")}function eF(f){switch(f){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function fK(f){if(!f||f.isError!==!0)return;if(typeof f.output==="string")return f.output;if(f.output instanceof Error)return f.output.message;try{return JSON.stringify(f.output)}catch{return String(f.output)}}class yW{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate(f){switch(f.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:f.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:f.iteration,hadToolCalls:f.toolCallCount>0,toolCallCount:f.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:f.text,accumulated:f.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:f.text,redacted:f.redacted===!0}];case"assistant-message":return this.translateAssistantMessage(f.message);case"tool-started":return this.translateToolStarted(f);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,update:f.update}];case"tool-finished":return this.translateToolFinished(f);case"usage-updated":return this.translateUsage(f.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:f.message,reason:f.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:f.metadata}];case"run-finished":return this.translateRunFinished(f.result);case"run-failed":return[{type:"error",error:f.error,recoverable:!1,iteration:f.snapshot.iteration}];default:return f}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage(f){let $=[],J=tF(f);if(J!==void 0)$.push({type:"content_end",contentType:"text",text:J});let W=sF(f);if(W!==void 0)$.push({type:"content_end",contentType:"reasoning",reasoning:W.reasoning});return $}translateToolStarted(f){return this.toolStartedAt.set(f.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,input:f.toolCall.input}]}translateToolFinished(f){let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=$===void 0?void 0:Date.now()-$;this.toolStartedAt.delete(f.toolCall.toolCallId);let W=oF(f.message),H=W?.output,Q=fK(W);return[{type:"content_end",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,output:H,error:Q,durationMs:J}]}translateUsage(f){let $=f.inputTokens-this.lastUsage.inputTokens,J=f.outputTokens-this.lastUsage.outputTokens,W=f.cacheReadTokens-this.lastUsage.cacheReadTokens,H=f.cacheWriteTokens-this.lastUsage.cacheWriteTokens,Q=this.lastUsage.totalCost??0,j=(f.totalCost??0)-Q;return this.lastUsage={inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,totalCost:f.totalCost},[{type:"usage",inputTokens:Math.max(0,$),outputTokens:Math.max(0,J),cacheReadTokens:W===0?void 0:Math.max(0,W),cacheWriteTokens:H===0?void 0:Math.max(0,H),cost:j===0?void 0:j,totalInputTokens:f.inputTokens,totalOutputTokens:f.outputTokens,totalCacheReadTokens:f.cacheReadTokens===0?void 0:f.cacheReadTokens,totalCacheWriteTokens:f.cacheWriteTokens===0?void 0:f.cacheWriteTokens,totalCost:f.totalCost}]}translateRunFinished(f){let $={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens===0?void 0:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens===0?void 0:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost};return[{type:"done",reason:eF(f.status),text:f.outputText,iterations:f.iterations,usage:$}]}}function XK(f){if(typeof f==="string")return f;if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}}async function AK(f){let J=(typeof f.content==="function"?await f.content():f.content).trim();return J.length>0?J:void 0}function PK(f,$){let J=f.trim(),W=$.map((H)=>H.trim()).filter(Boolean).join(`
404
404
 
405
- `);if(J&&H)return`${J}
405
+ `);if(J&&W)return`${J}
406
406
 
407
- ${H}`;return J||H}function dF(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return{};return{beforeRun:async(J)=>{for(let H of $){let W=await H.beforeRun?.(J);if(W?.stop)return W}return},afterRun:async(J)=>{for(let H of $)await H.afterRun?.(J)},beforeModel:async(J)=>{let H=J.request,W;for(let Q of $){let Z=await Q.beforeModel?.({...J,request:H});if(!Z)continue;if(Z.stop)return Z;W={...W,...Z,options:{...W?.options??{},...Z.options??{}}},H={...H,...Z.messages?{messages:Z.messages}:{},...Z.tools?{tools:Z.tools}:{},...Z.options?{options:{...H.options??{},...Z.options}}:{}}}return W},afterModel:async(J)=>{for(let H of $){let W=await H.afterModel?.(J);if(W?.stop)return W}return},beforeTool:async(J)=>{let H=J.input,W;for(let Q of $){let Z=await Q.beforeTool?.({...J,input:H});if(!Z)continue;if(Z.stop||Z.skip)return Z;if(W={...W,...Z},Object.hasOwn(Z,"input"))H=Z.input}return W},afterTool:async(J)=>{let H=J.result,W;for(let Q of $){let Z=await Q.afterTool?.({...J,result:H});if(!Z)continue;if(Z.stop)return Z;if(W={...W,...Z},Z.result)H=Z.result}return W},onEvent:async(J)=>{for(let H of $)await H.onEvent?.(J)}}}class d0{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 FW;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor(f,$={}){this.config=f,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=f.parentAgentId,this.logger=$.logger??f.logger,this.telemetry=$.telemetry??f.telemetry,this.createAgentRuntimeImpl=$.createAgentRuntimeImpl??xF,this.conversation=new YW(f.initialMessages),this.messageBuilder=new XW,this.contributionRegistry=gF({extensions:f.extensions?[...f.extensions]:[],setupContext:{session:f.extensionContext?.session,client:f.extensionContext?.client,user:f.extensionContext?.user,workspaceInfo:f.extensionContext?.workspace,automation:f.extensionContext?.automation,logger:f.extensionContext?.logger??this.logger,telemetry:f.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=f.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new RW({maxConsecutiveMistakes:J,onLimitReached:f.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,Z,j)=>rF(this.logger,Q,Z,j),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(Q,Z)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q}]})}});let H=f.execution?.loopDetection;this.loopDetectionDisabled=H===!1;let W=H===!1||H===void 0?void 0:H;this.loopTracker=new AW(W)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools(f){if(f.length===0)return;let $=new Set(this.config.tools.map((H)=>H.name)),J=[...this.config.tools];for(let H of f)if(!$.has(H.name))J.push(H),$.add(H.name);this.config={...this.config,tools:J}}updateConnection(f){let $={...this.config};if(f.providerId!==void 0)$.providerId=f.providerId;if(f.modelId!==void 0)$.modelId=f.modelId;if(f.apiKey!==void 0)$.apiKey=f.apiKey;if(f.baseUrl!==void 0)$.baseUrl=f.baseUrl;if(f.headers!==void 0)$.headers=f.headers;if(f.providerConfig!==void 0)$.providerConfig=f.providerConfig;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinking!==void 0)$.thinking=f.thinking;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;this.config=$}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore(f){this.conversation.restore(f),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}abort(f){let $=typeof f==="string"?f:f instanceof Error?f.message:f===void 0?void 0:String(f);if(this.abortRequested=!0,this.abortReason=$,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort($)}async shutdown(f,$){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run(f,$,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!1})}continue(f,$,J){return this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let f=[];for(let $ of this.contributionRegistry.getRegisteredRules()){let J=await uF($);if(J)f.push(J)}return cF(this.config.systemPrompt,f)}executeRun(f){let $;return $=this.executeRunInternal(f).finally(()=>{if(this.activeRunPromise===$)this.activeRunPromise=null}),this.activeRunPromise=$,$}async executeRunInternal(f){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let $=new Date,J=f.userMessage;if(J!==void 0){let F=await pF(J,f.userImages,f.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let H=await this.composeSystemPrompt(),W=BQ(this.config,this.logger),Q=this.contributionRegistry.getRegisteredTools(),Z=new Map;for(let F of Q)Z.set(F.name,F);for(let F of this.config.tools)Z.set(F.name,F);let j=this.conversation.getConversationId(),P=_Q(this.config),X=Array.from(Z.values()),V=R6(this.conversation.getMessages()),Y=TQ({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:j,parentAgentId:this.parentAgentId,model:W,logger:this.logger,tools:X,toolContextMetadata:{modelSupportsImages:P?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(P,X),initialMessages:V,systemPrompt:H}),B=this.createAgentRuntimeImpl(Y);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let A=B.subscribe((F)=>{this.handleRuntimeEvent(F)}),R,U;try{if(f.isContinue)R=await B.continue(void 0);else R=await B.run("")}catch(F){U=F instanceof Error?F:Error(String(F))}finally{A();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(R&&R.messages.length>0){let F=G1(R.messages);this.conversation.replaceMessages(F)}let y=new Date;try{return this.buildLegacyResult({runResult:R,thrownError:U,startedAt:$,endedAt:y})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch(f){if(this.config.hookErrorMode==="throw")throw f;this.emitLegacyEvent({type:"error",error:f instanceof Error?f:Error(String(f)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let f=dF([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map(($)=>$.hooks)]);return{...f,beforeModel:async($)=>{let J=await f.beforeModel?.($);if(J?.stop)return J;let H=J?.messages??$.request.messages,W=await this.prepareMessagesForModelRequest(H);return{...J,messages:W}}}}createRuntimePrepareTurn(f,$){let J=this.config.prepareTurn;if(!J)return;return async(H)=>{let W=G1(H.messages),Q=await this.prepareProviderMessagesForApi(W),Z=await J({agentId:H.agentId,conversationId:H.conversationId??this.conversation.getConversationId(),parentAgentId:H.parentAgentId??null,iteration:H.iteration,messages:W,apiMessages:Q,abortSignal:H.signal??new AbortController().signal,systemPrompt:H.systemPrompt??"",tools:$,model:{id:this.config.modelId,provider:this.config.providerId,info:f},emitStatusNotice:H.emitStatusNotice});if(!Z)return;return{...Z.messages?{messages:R6(Z.messages)}:{},...Z.systemPrompt!==void 0?{systemPrompt:Z.systemPrompt}:{}}}}async prepareMessagesForModelRequest(f){let $=await this.prepareProviderMessagesForApi(UQ(f));return R6($)}async prepareProviderMessagesForApi(f){let $=f,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let H of J)$=await H.build($);return this.messageBuilder.buildForApi($)}handleRuntimeEvent(f){switch(f.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage(f.snapshot.messages,[f.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set(f.toolCall.toolCallId,new Date),this.toolInputs.set(f.toolCall.toolCallId,f.toolCall.input),this.inspectLoopForToolCall(f.toolCall.toolName,f.toolCall.input,f.iteration);break}case"tool-finished":{let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=new Date,H=this.toolInputs.get(f.toolCall.toolCallId);this.toolStartedAt.delete(f.toolCall.toolCallId),this.toolInputs.delete(f.toolCall.toolCallId);let W=f.message.content.find((P)=>P.type==="tool-result"),Q=W?.type==="tool-result"&&W.isError===!0,Z=Q?vF(W?.type==="tool-result"?W.output:void 0):void 0,j={id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:H,output:W?.type==="tool-result"?W.output:void 0,error:Z,durationMs:$===void 0?0:J.getTime()-$.getTime(),startedAt:$??J,endedAt:J};if(this.currentRunToolCalls.push(j),Q){if(this.currentTurnFailedTools+=1,Z)this.currentTurnFailureDetails.push(`[${f.toolCall.toolName}] ${Z}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let $=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if($>0&&J===0){let H=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:f.iteration,reason:"tool_execution_failed",details:`${$} tool call(s) failed${H?`: ${H}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost};break}default:break}for(let $ of this.eventAdapter.translate(f))this.emitLegacyEvent($)}syncConversationFromRuntimeMessage(f,$){if(f.length>0){this.conversation.replaceMessages(G1(f));return}if($.length===0)return;let J=new Set(this.conversation.getMessages().map((W)=>W.id).filter((W)=>typeof W==="string")),H=G1($).filter((W)=>!W.id||!J.has(W.id));if(H.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...H])}emitLegacyEvent(f){for(let $ of this.listeners)try{$(f)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall(f,$,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let H=this.loopTracker.inspect({name:f,input:$});if(H.kind==="ok")return;if(H.kind==="soft"){if(H.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:H.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:H.message??`Detected repeated tool calls to \`${f}\`; stopping to avoid a loop.`})}enqueueMistakeRecord(f){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let $=await this.mistakeTracker.record(f);if($.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:$.message}]}),this.activeRuntime?.abort($.reason??$.message)})}buildLegacyResult(f){let{runResult:$,thrownError:J,startedAt:H,endedAt:W}=f,Q=W.getTime()-H.getTime(),Z=J?"error":lF($),j=$?.outputText||($?.status==="failed"?$.error?.message:void 0)||"",P=$?{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost}:this.currentRunUsage,X=$?G1($.messages):this.conversation.getMessages(),V=_Q(this.config);if(J)throw J;return{text:j,usage:P,messages:X,toolCalls:this.currentRunToolCalls,iterations:$?.iterations??0,finishReason:Z,model:{id:this.config.modelId,provider:this.config.providerId,info:V},startedAt:H,endedAt:W,durationMs:Q}}}function rF(f,$,J,H){if(!f)return;if($==="debug"){f.debug(J,H);return}if($==="error"&&f.error){f.error(J,H);return}let W=$==="warn"?"warn":$==="error"?"error":"info";f.log(J,{...H,severity:W})}function lF(f){if(!f)return"error";switch(f.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function pF(f,$,J,H){let{buildInitialUserContent:W}=await Promise.resolve().then(() => MQ);return W(f,$,J,H)}function _Q(f){if(f.knownModels?.[f.modelId])return f.knownModels[f.modelId];let $=jW(f);if($?.[f.modelId])return $[f.modelId];return}import{buildClineSystemPrompt as LQ}from"@cline/shared";function zQ(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return LQ({ide:$.clineIdeName?.trim()||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,rules:`# Team Teammate Role
408
- ${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function OQ(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return LQ({ide:$.clineIdeName||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,overridePrompt:J,metadata:$.workspaceMetadata,platform:$.clinePlatform})}function h1(f){let $={...f};return{getRuntimeConfig:()=>$,getConnectionConfig:()=>({providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking}),updateConnectionDefaults:(J)=>{$={...$,...J}}}}function _$(f){let $=f.configProvider.getRuntimeConfig(),J=f.kind==="teammate"?zQ(f.prompt,$):OQ(f.prompt,$);return{...f.configProvider.getConnectionConfig(),systemPrompt:J,tools:f.tools,maxIterations:f.maxIterations??$.maxIterations,parentAgentId:f.parentAgentId,abortSignal:f.abortSignal,onEvent:f.onEvent,hooks:$.hooks,extensions:$.extensions,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval,logger:$.logger,role:f.role}}function T1(f){let $=_$(f),J=new d0($);if($.onEvent)J.subscribeEvents($.onEvent);return J}var aF=yW.object({systemPrompt:yW.string().describe("System prompt defining the sub-agent's behavior"),task:yW.string().describe("Task for the sub-agent to complete")});function r0(f){return iF({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:nF(aF),execute:async($,J)=>{let H=f.createSubAgentTools?await f.createSubAgentTools($,J):f.subAgentTools??[],W=T1({kind:"subagent",prompt:$.systemPrompt,configProvider:f.configProvider,tools:H,maxIterations:f.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:f.onSubAgentEvent,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval}),Q=W.getAgentId(),Z=W.getConversationId(),j=J.agentId;if(f.onSubAgentStart)try{await f.onSubAgentStart({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$})}catch{}try{let P=await W.run($.task),X={text:P.text,iterations:P.iterations,finishReason:P.finishReason,usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens}};if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$,result:X})}catch{}return X}catch(P){if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$,error:P instanceof Error?P:Error(String(P))})}catch{}throw P}},timeoutMs:300000,retryable:!1})}import{createTool as Hf,TEAM_AWAIT_TIMEOUT_MS as tF,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as sF,TEAM_RUN_TEXT_PREVIEW_LIMIT as oF,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as eF,TeamAttachOutcomeFragmentInputSchema as NQ,TeamAwaitRunsInputSchema as qQ,TeamBroadcastInputSchema as bQ,TeamBroadcastToolResultSchema as fy,TeamCancelRunInputSchema as wQ,TeamCancelRunToolResultSchema as $y,TeamCleanupInputSchema as CQ,TeamCleanupToolResultSchema as Jy,TeamCreateOutcomeInputSchema as EQ,TeamCreateOutcomeToolResultSchema as Hy,TeamFinalizeOutcomeInputSchema as SQ,TeamFinalizeOutcomeToolResultSchema as Wy,TeamListOutcomesInputSchema as kQ,TeamListRunsInputSchema as mQ,TeamMailboxMessageToolResultSchema as Qy,TeamMissionLogInputSchema as IQ,TeamMissionLogToolResultSchema as Zy,TeamOutcomeFragmentToolResultSchema as xQ,TeamOutcomeToolResultSchema as jy,TeamReadMailboxInputSchema as gQ,TeamReviewOutcomeFragmentInputSchema as vQ,TeamRunTaskInputSchema as uQ,TeamRunTaskToolResultSchema as KW,TeamRunToolSummarySchema as UW,TeamSendMessageInputSchema as cQ,TeamSendMessageToolResultSchema as Py,TeamShutdownTeammateInputSchema as dQ,TeamSimpleAgentStatusToolResultSchema as rQ,TeamSpawnTeammateInputSchema as lQ,TeamStatusInputSchema as pQ,TeamStatusToolResultSchema as Xy,TeamTaskInputSchema as iQ,TeamTaskToolResultSchema as Q8,validateWithZod as b,zodToJsonSchema as Wf}from"@cline/shared";function nQ(f,$){let J=f.replace(/\s+/g," ").trim();if(J.length<=$)return J;return`${J.slice(0,Math.max(0,$-3)).trimEnd()}...`}function L$(f,$){if(f===void 0)throw Error(`Missing required field: ${$}`);return f}function Vy(f){let $=f.result;if(!$)return;return{textPreview:nQ($.text,oF),iterations:$.iterations,finishReason:$.finishReason,durationMs:$.durationMs,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost}}}function F6(f){return f?.toISOString()}function GW(f){return{id:f.id,agentId:f.agentId,taskId:f.taskId,status:f.status,messagePreview:nQ(f.message,sF),priority:f.priority,retryCount:f.retryCount,maxRetries:f.maxRetries,nextAttemptAt:F6(f.nextAttemptAt),continueConversation:f.continueConversation,startedAt:f.startedAt.toISOString(),endedAt:F6(f.endedAt),leaseOwner:f.leaseOwner,heartbeatAt:F6(f.heartbeatAt),lastProgressAt:F6(f.lastProgressAt),lastProgressMessage:f.lastProgressMessage,currentActivity:f.currentActivity,error:f.error,resultSummary:Vy(f)}}function Yy(f){if(f.status==="failed")throw Error(`Run "${f.id}" failed${f.error?`: ${f.error}`:""}`);if(f.status==="cancelled")throw Error(`Run "${f.id}" was cancelled${f.error?`: ${f.error}`:""}`);if(f.status==="interrupted")throw Error(`Run "${f.id}" was interrupted${f.error?`: ${f.error}`:""}`)}var D1=["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 aQ(f){let $=[];if(f.createBaseTools)$.push(...f.createBaseTools());$.push(...z$({runtime:f.runtime,requesterId:f.spec.agentId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!1})),f.runtime.spawnTeammate({agentId:f.spec.agentId,config:_$({kind:"teammate",prompt:f.spec.rolePrompt,role:f.spec.rolePrompt,configProvider:f.teammateConfigProvider,tools:$,maxIterations:f.spec.maxIterations,cwd:f.teammateConfigProvider.getRuntimeConfig().cwd})})}function M1(f){let $=f.leadAgentId??"lead",J=f.restoredFromPersistence===!0,H=z$({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!0,includeSpawnTool:f.includeLeadSpawnTool,includeManagementTools:f.includeLeadManagementTools,onLeadToolsUnlocked:f.onLeadToolsUnlocked}),W=[];for(let Q of f.restoredTeammates??[]){if(f.runtime.isTeammateActive(Q.agentId))continue;aQ({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:Q}),W.push(Q.agentId)}return{tools:H,restoredFromPersistence:J,restoredTeammates:W}}function z$(f){let $=f.allowSpawn??!0,J=f.includeSpawnTool??!0,H=f.includeManagementTools??!0,W=[];if(J)W.push(Hf({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:Wf(lQ),execute:async(Z)=>{let j=b(lQ,Z);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!$)throw Error("Spawning teammates is disabled in this context.");let P={agentId:j.agentId,rolePrompt:j.rolePrompt};if(aQ({runtime:f.runtime,requesterId:f.requesterId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:P}),!H)f.onLeadToolsUnlocked?.(z$({...f,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return b(rQ,{agentId:j.agentId,status:"spawned"})}}));if(!H)return W;W.push(Hf({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:Wf(dQ),execute:async(Z)=>{let j=b(dQ,Z);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return f.runtime.shutdownTeammate(j.agentId,j.reason),b(rQ,{agentId:j.agentId,status:"stopped"})}})),W.push(Hf({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:Wf(pQ),execute:async(Z)=>{return b(pQ,Z),b(Xy,f.runtime.getSnapshot())}})),W.push(Hf({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:Wf(iQ),execute:async(Z)=>{let j=b(iQ,Z);switch(j.action){case"create":{let P=new Set(eF.create??[]),X=Object.entries(Z).filter(([Y,B])=>P.has(Y)&&B!=null).map(([Y])=>Y),V=f.runtime.createTask({title:L$(j.title,"title"),description:L$(j.description,"description"),dependsOn:j.dependsOn,assignee:j.assignee,createdBy:f.requesterId});return b(Q8,{action:"create",taskId:V.id,status:V.status,...X.length>0?{ignoredFields:X,note:`Ignored fields for action=create: ${X.join(", ")}`}:{}})}case"list":return b(Q8,{action:"list",tasks:f.runtime.listTaskItems({status:j.status,assignee:j.assignee})});case"claim":{let P=f.runtime.claimTask(L$(j.taskId,"taskId"),f.requesterId);return b(Q8,{action:"claim",taskId:P.id,status:P.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 P=f.runtime.completeTask(L$(j.taskId,"taskId"),f.requesterId,L$(j.summary,"summary"));return b(Q8,{action:"complete",taskId:P.id,status:P.status})}case"block":{let P=f.runtime.blockTask(L$(j.taskId,"taskId"),f.requesterId,L$(j.reason,"reason"));return b(Q8,{action:"block",taskId:P.id,status:P.status})}}}}));let Q=new Map;return W.push(Hf({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:Wf(uQ),execute:async(Z)=>{let j=b(uQ,Z);if(j.runMode==="async"){let V=f.runtime.startTeammateRun(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:f.requesterId,continueConversation:j.continueConversation||void 0});return b(KW,{agentId:j.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${j.agentId} and queued as ${V.id}.`,runId:V.id})}let P=Q.get(j.agentId);if(P){let V=await P;return b(KW,{...V,status:"joined",deduped:!0,message:`Task for ${j.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let X=f.runtime.routeToTeammate(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:f.requesterId,continueConversation:j.continueConversation||void 0}).then((V)=>b(KW,{agentId:j.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${j.agentId} and completed in sync mode.`,text:V.text,iterations:V.iterations})).finally(()=>{Q.delete(j.agentId)});return Q.set(j.agentId,X),await X}})),W.push(Hf({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:Wf(wQ),execute:async(Z)=>{let j=b(wQ,Z),P=f.runtime.cancelRun(j.runId,j.reason);return b($y,{runId:P.id,status:P.status})}})),W.push(Hf({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:Wf(mQ),execute:async(Z)=>b(UW.array(),f.runtime.listRuns(b(mQ,Z)).map(GW))})),W.push(Hf({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:Wf(qQ),timeoutMs:tF,execute:async(Z)=>{let j=b(qQ,Z);if(j.runId){let V=await f.runtime.awaitRun(j.runId);return Yy(V),b(UW,GW(V))}let P=await f.runtime.awaitAllRuns(),X=P.filter((V)=>["failed","cancelled","interrupted"].includes(V.status));if(X.length>0){let V=X.map((Y)=>`${Y.id}:${Y.status}${Y.error?`(${Y.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${V}`)}return b(UW.array(),P.map(GW))}})),W.push(Hf({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:Wf(cQ),execute:async(Z)=>{let j=b(cQ,Z),P=f.runtime.sendMessage(f.requesterId,j.toAgentId,j.subject,j.body,j.taskId??void 0);return b(Py,{id:P.id,toAgentId:P.toAgentId})}})),W.push(Hf({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:Wf(bQ),execute:async(Z)=>{let j=b(bQ,Z),P=f.runtime.broadcast(f.requesterId,j.subject,j.body,{taskId:j.taskId??void 0});return b(fy,{delivered:P.length})}})),W.push(Hf({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:Wf(gQ),execute:async(Z)=>{let j=b(gQ,Z);return b(Qy.array(),f.runtime.listMailbox(f.requesterId,{unreadOnly:j.unreadOnly,markRead:!0}))}})),W.push(Hf({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:Wf(IQ),execute:async(Z)=>{let j=b(IQ,Z),P=f.runtime.appendMissionLog({agentId:f.requesterId,taskId:j.taskId||void 0,kind:j.kind,summary:j.summary,evidence:j.evidence?.length?j.evidence:void 0,nextAction:j.nextAction||void 0});return b(Zy,{id:P.id})}})),W.push(Hf({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:Wf(CQ),execute:async(Z)=>{if(b(CQ,Z),f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return f.runtime.cleanup(),b(Jy,{status:"cleaned"})}})),W.push(Hf({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:Wf(EQ),execute:async(Z)=>{let j=b(EQ,Z),P=f.runtime.createOutcome({title:j.title,requiredSections:j.requiredSections,createdBy:f.requesterId});return b(Hy,{outcomeId:P.id,status:P.status,requiredSections:P.requiredSections})}})),W.push(Hf({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:Wf(NQ),execute:async(Z)=>{let j=b(NQ,Z),P=f.runtime.attachOutcomeFragment({outcomeId:j.outcomeId,section:j.section,sourceAgentId:f.requesterId,sourceRunId:j.sourceRunId||void 0,content:j.content});return b(xQ,{fragmentId:P.id,status:P.status})}})),W.push(Hf({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:Wf(vQ),execute:async(Z)=>{let j=b(vQ,Z),P=f.runtime.reviewOutcomeFragment({fragmentId:j.fragmentId,reviewedBy:f.requesterId,approved:j.approved});return b(xQ,{fragmentId:P.id,status:P.status})}})),W.push(Hf({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:Wf(SQ),execute:async(Z)=>{let j=b(SQ,Z),P=f.runtime.finalizeOutcome(j.outcomeId);return b(Wy,{outcomeId:P.id,status:P.status})}})),W.push(Hf({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:Wf(kQ),execute:async(Z)=>{return b(kQ,Z),b(jy.array(),f.runtime.listOutcomes())}})),W}function y6(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}function K6(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var By=[{id:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:r0({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...D1]}],Ay={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function Ry(f){return f==="plan"||f==="yolo"?f:"act"}function sQ(f){let $=Ry(f.mode),J=bf[G0({mode:$})],H=U1(f.providerId??"",f.modelId??"",$,K1);return{mode:$,flags:{...J,...H,...typeof f.enableSpawnAgent==="boolean"?{enableSpawnAgent:f.enableSpawnAgent}:{},...typeof f.enableAgentTeams==="boolean"?{enableAgentTeams:f.enableAgentTeams}:{}}}}function tQ(f,$){if($.disabledToolIds?.has(f))return!1;let{flags:J}=sQ($);if(f==="spawn_agent")return J.enableSpawnAgent===!0;if(f==="teams")return J.enableAgentTeams===!0;if(f==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let H=Ay[f];return H?J[H]===!0:!1}function Fy(f,$){if(f.id==="editor"){let{flags:J}=sQ($),H=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...f,defaultEnabled:tQ(f.id,$),headlessToolNames:[H?"apply_patch":"editor"]}}return{...f,defaultEnabled:tQ(f.id,$)}}function O$(f={}){return By.map(($)=>Fy($,f))}function U6(f={}){return O$(f).filter(($)=>$.defaultEnabled).map(($)=>$.id)}function G6(f){if(!f.enabled)return new Set;let $=O$(f.availabilityContext),J=new Set($.map((H)=>H.id));if(!f.allowlist||f.allowlist.length===0)return new Set($.filter((H)=>H.defaultEnabled).map((H)=>H.id));for(let H of f.allowlist)if(!J.has(H))throw Error(`Unknown tool "${H}". Available tools: ${$.map((W)=>W.id).join(", ")}`);return new Set(f.allowlist)}function Z8(f,$={}){return O$($).filter((J)=>f.has(J.id)).flatMap((J)=>J.headlessToolNames)}function h6(f,$={}){return Z8(f,$)}function N$(f={}){let{executorOptions:$={},executors:J,...H}=f,W={...y1($),...J??{}};return u0({...H,executors:W})}import{mkdirSync as Ty,writeFileSync as Dy}from"node:fs";import{dirname as My}from"node:path";import{normalizeUserInput as _y}from"@cline/shared";import{nanoid as Ly}from"nanoid";var eQ={};N(eQ,{sanitizeSessionToken:()=>q$,parseTeamTaskSubSessionId:()=>L1,parseSubSessionId:()=>P8,makeTeamTaskSubSessionId:()=>j8,makeSubSessionId:()=>_1,deriveSubsessionStatus:()=>X8});import{nanoid as Uy}from"nanoid";function q$(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function _1(f,$){let J=q$(f),H=q$($),W=`${J}__${H}`;return W.length>180?W.slice(0,180):W}function j8(f,$){let J=q$(f),H=q$($);return`${J}__teamtask__${H}__${Uy(6)}`}function L1(f){let J=f.indexOf("__teamtask__");if(J<=0)return null;let H=f.slice(0,J),W=f.slice(J+12),Q=W.lastIndexOf("__");if(Q<=0)return null;let Z=W.slice(0,Q),j=W.slice(Q+2);if(!H||!Z||!j)return null;return{rootSessionId:H,agentId:Z,teamTaskId:j}}function P8(f){if(L1(f))return null;let $="__",J=f.indexOf($);if(J<=0)return null;let H=f.slice(0,J),W=f.slice(J+$.length);if(!H||!W)return null;return{rootSessionId:H,agentId:W}}function X8(f){switch(f.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let $=String(f.reason??"").toLowerCase();if($.includes("cancel")||$.includes("abort")||$.includes("interrupt"))return"cancelled";if($.includes("fail")||$.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as n}from"zod";var fZ={};N(fZ,{SessionSource:()=>Vf,SESSION_STATUSES:()=>V8});import{SESSION_STATUS_VALUES as Gy}from"@cline/shared";var V8=Gy,Vf={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 hy=n.enum(V8),Gf=n.object({version:n.literal(1),session_id:n.string().min(1),source:n.string().min(1),pid:n.number().int(),started_at:n.string().min(1),ended_at:n.string().min(1).optional(),exit_code:n.number().int().nullable().optional(),status:hy,interactive:n.boolean(),provider:n.string().min(1),model:n.string().min(1),cwd:n.string().min(1),workspace_root:n.string().min(1),team_name:n.string().min(1).optional(),enable_tools:n.boolean(),enable_spawn:n.boolean(),enable_teams:n.boolean(),prompt:n.string().optional(),metadata:n.record(n.string(),n.unknown()).optional(),messages_path:n.string().min(1).optional()});function $Z(f){if(!f)return!1;return Object.values(f).some(($)=>typeof $==="function")}function TW(f,$){let J=[...f??[],...$??[]];if(J.length===0)return;let H=[],W=new Set;for(let Q of J){if(W.has(Q.name))continue;W.add(Q.name),H.push(Q)}return H}function JZ(f){return JSON.stringify(f,($,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function h0(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function hW(f,$){let J={...f};J.id=h0(J.id)??Ly();let H=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,W={id:h0(H?.id)??h0(J.modelId)??h0($?.id),provider:h0(H?.provider)??h0(J.providerId)??h0($?.provider),family:h0(H?.family)??h0($?.family)};if(delete J.providerId,delete J.modelId,W.id&&W.provider)J.modelInfo={id:W.id,provider:W.provider,...W.family?{family:W.family}:{}};else delete J.modelInfo;return J}function T6(f){return f.map(($)=>hW($))}function D6(f,$,J=[]){let H=f.map((j,P)=>{let X=J[P],Y=X?.role===j.role&&JSON.stringify(X.content)===JSON.stringify(j.content)?{...X,...j}:{...j};return hW(Y)}),W=J.length,Q=[];for(let j=W;j<H.length;j+=1)if(H[j]?.role==="assistant")Q.push(j);if(Q.length===0){let j=[...H].reverse().findIndex((P)=>P.role==="assistant");if(j===-1)return H;Q.push(H.length-1-j)}let Z=Q[Q.length-1];for(let j of Q){let P=H[j],X=P.metrics;if(!X&&j===Z){let V=$.usage;X={inputTokens:V.inputTokens,outputTokens:V.outputTokens,cacheReadTokens:V.cacheReadTokens??0,cacheWriteTokens:V.cacheWriteTokens??0,cost:V.totalCost}}H[j]={...hW(P,{id:$.model.id,provider:$.model.provider,family:$.model.info?.family}),...X?{metrics:X}:{},ts:P.ts??$.endedAt.getTime()}}return H}function Y8(f){return{sessionId:f.sessionId,source:f.source,pid:f.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??void 0,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:f.parentSessionId??void 0,parentAgentId:f.parentAgentId??void 0,agentId:f.agentId??void 0,conversationId:f.conversationId??void 0,isSubagent:f.isSubagent,prompt:f.prompt??void 0,metadata:f.metadata??void 0,messagesPath:f.messagesPath??void 0,updatedAt:f.updatedAt}}var zy=120;function b$(f){let $=f?.trim();return $?$.slice(0,zy):void 0}function DW(f){let $=_y(f??"").trim();if(!$)return;return b$($.split(`
409
- `)[0]?.trim())}function l0(f){if(!f)return;let $={...f},J=b$(typeof $.title==="string"?$.title:void 0);if(J)$.title=J;else delete $.title;return Object.keys($).length>0?$:void 0}function B8(f){let $=l0(f.metadata)??{},J=f.title!==void 0?b$(f.title):DW(f.prompt);if(J)$.title=J;return Object.keys($).length>0?$:void 0}function MW(f){let $=L1(f);if($)return{agent:"teammate",sessionId:$.rootSessionId,taskType:"team"};let J=P8(f);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:f}}function _W(f){return{version:1,updated_at:f.updatedAt,agent:f.context.agent,sessionId:f.context.sessionId,...f.context.taskType?{taskType:f.context.taskType}:{},messages:T6(f.messages),...f.systemPrompt?{system_prompt:f.systemPrompt}:{}}}function HZ(f,$,J){Ty(My(f),{recursive:!0}),Dy(f,`${JSON.stringify(_W({updatedAt:$,context:J,messages:[]}),null,2)}
410
- `,"utf8")}function WZ(f,$){return Gf.parse({version:1,session_id:f.sessionId,source:f.source,pid:f.pid,started_at:f.startedAt,ended_at:$?.endedAt??f.endedAt??void 0,exit_code:$?.exitCode??f.exitCode??void 0,status:$?.status??f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName??void 0,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt??void 0,metadata:$?.metadata??f.metadata??void 0,messages_path:f.messagesPath??void 0})}async function QZ(f,$,J){let H=0;while(!0){let W=await f();if(W===void 0)return{updated:!1};let Q=await $(W);if(typeof Q==="object"&&Q!==null&&"updated"in Q&&Q.updated===!1){if(H+=1,H>=J)return Q;continue}return Q}}Kf();var ZZ={};N(ZZ,{summarizeUsageFromMessages:()=>A8,getCurrentContextSize:()=>LW,createInitialAccumulatedUsage:()=>p0,accumulateUsageTotals:()=>i0});function p0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function i0(f,$){return{inputTokens:f.inputTokens+Math.max(0,$.inputTokens??0),outputTokens:f.outputTokens+Math.max(0,$.outputTokens??0),cacheReadTokens:f.cacheReadTokens+Math.max(0,$.cacheReadTokens??0),cacheWriteTokens:f.cacheWriteTokens+Math.max(0,$.cacheWriteTokens??0),totalCost:f.totalCost+Math.max(0,$.totalCost??0)}}function z1(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function A8(f){let $=p0();for(let J of f){let H=J.metrics;if(!H)continue;$=i0($,{inputTokens:z1(H.inputTokens),outputTokens:z1(H.outputTokens),cacheReadTokens:z1(H.cacheReadTokens),cacheWriteTokens:z1(H.cacheWriteTokens),totalCost:z1(H.cost)})}return $}function LW(f){for(let $=f.length-1;$>=0;$-=1){let J=f[$];if(J?.role!=="assistant")continue;let H=z1(J.metrics?.inputTokens);return H>0?H:void 0}return}function Oy(f){if(!f||typeof f!=="object")return;let $=f,J=$.skill??$.skill_name??$.skillName;if(typeof J!=="string")return;let H=J.trim();return H.length>0?H:void 0}function zW(f){if(!f||typeof f!=="object")return{};let $=f;return{agentId:typeof $.agentId==="string"?$.agentId:void 0,conversationId:typeof $.conversationId==="string"?$.conversationId:void 0,parentAgentId:typeof $.parentAgentId==="string"?$.parentAgentId:void 0}}function T0(f){let $=f.agentId?.trim();if(!$)return;let J=f.parentAgentId?.trim()||void 0,H=f.teamRole,W="root";if(H==="teammate")W="team_teammate";else if(H==="lead")W="team_lead";else if(J)W="subagent";return{agentId:$,agentKind:W,conversationId:f.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:f.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:f.teamId?.trim()||void 0,teamName:f.teamName?.trim()||void 0,teamRole:H,teamAgentId:f.teamAgentId?.trim()||void 0}}function OW(f,$,J){let{sessionId:H,config:W,liveSession:Q,emit:Z}=f,j=W.telemetry,P=Q?.runtime.teamRuntime,X=J?.isPrimaryAgentEvent??!0,V=zW($),Y=T0({agentId:J?.agentId??V.agentId,conversationId:J?.conversationId??V.conversationId,parentAgentId:J?.parentAgentId??V.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??P?.getTeamId(),teamName:J?.teamName??P?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if($.type==="content_start"&&$.contentType==="tool"&&$.toolName==="skills"){let B=Oy($.input);if(B)v4(j,{ulid:H,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:W.providerId,modelId:W.modelId,...Y})}if($.type==="content_end"&&$.contentType==="tool"){let B=$.toolName??"unknown",A=!$.error;if(g4(j,{ulid:H,tool:B,autoApproved:void 0,success:A,modelId:W.modelId,provider:W.providerId,...Y}),!A&&(B==="editor"||B==="apply_patch"))u4(j,{ulid:H,modelId:W.modelId,provider:W.providerId,errorType:$.error,...Y})}if($.type==="notice"&&$.reason==="api_error")L2(j,{ulid:H,model:W.modelId,provider:W.providerId,errorMessage:$.message,...Y});if($.type==="error")L2(j,{ulid:H,model:W.modelId,provider:W.providerId,errorMessage:$.error?.message??"unknown error",...Y});if($.type==="usage"&&X&&Q?.turnUsageBaseline)f.usageBySession.set(H,i0(Q.turnUsageBaseline,{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost})),Z1(j,{ulid:H,provider:W.providerId,model:W.modelId,source:"assistant",mode:W.mode,...Y}),I4(j,{ulid:H,tokensIn:$.inputTokens,tokensOut:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost,model:W.modelId,...Y});if($.type==="iteration_end"&&X)f.persistMessages(H,Q?.agent.getMessages()??[],Q?.config.systemPrompt);Z({type:"agent_event",payload:{sessionId:H,event:$,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(X?"lead":void 0):void 0}}),Z({type:"chunk",payload:{sessionId:H,stream:"agent",chunk:JZ($),ts:Date.now()}})}function n0(f){return f.workspaceRoot??f.cwd}import{hasRuntimeConfigExtension as wU}from"@cline/shared";function jZ(f){let $="";for(let J=0;J<f.length;J+=1)$+=String.fromCharCode(f[J]??0);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function Ny(f){let J=new TextEncoder().encode(f),H=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(H)}function qy(f=32){let $=new Uint8Array(f);return crypto.getRandomValues($),jZ($)}async function M6(){let f=qy(),$=jZ(await Ny(f));return{verifier:f,challenge:$}}function _6(f){return f.endsWith("/")?f.slice(0,-1):f}function w$(f,$){return new URL($,`${_6(f)}/`).toString()}function O1(f,$={}){let J=f.trim();if(!J)return{};try{let H=new URL(J);return{code:H.searchParams.get("code")??void 0,state:H.searchParams.get("state")??void 0,provider:$.includeProvider?H.searchParams.get("provider")??void 0:void 0}}catch{}if($.allowHashCodeState&&J.includes("#")){let[H,W]=J.split("#",2);return{code:H||void 0,state:W||void 0}}if(J.includes("code=")){let H=new URLSearchParams(J);return{code:H.get("code")??void 0,state:H.get("state")??void 0,provider:$.includeProvider?H.get("provider")??void 0:void 0}}return{code:J}}function by(f){if(typeof atob==="function")try{return atob(f)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from(f,"base64").toString("utf8")}catch{return null}return null}function Ff(f){if(!f)return null;try{let $=f.split(".");if($.length!==3)return null;let J=$[1];if(!J)return null;let H=J.replace(/-/g,"+").replace(/_/g,"/"),W=H.padEnd(H.length+(4-H.length%4)%4,"="),Q=by(W);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function N1(f){try{let $=JSON.parse(f),J=$.error,H=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,W=typeof $.error_description==="string"?$.error_description:typeof $.message==="string"?$.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:H,message:W}}catch{return{}}}function C$(f,$){return Date.now()>=f.expires-$}async function q1(f){if(!f.onManualCodeInput){let Q=await f.waitForCallback();return{code:Q?.code,state:Q?.state,provider:Q?.provider,error:Q?.error}}let $,J,H=f.onManualCodeInput().then((Q)=>{$=Q,f.cancelWait()}).catch((Q)=>{J=Q instanceof Error?Q:Error(String(Q)),f.cancelWait()}),W=await f.waitForCallback();if(J)throw J;if(W?.code||W?.error)return{code:W.code,state:W.state,provider:W.provider,error:W.error};if($)return O1($,f.parseOptions);if(await H,J)throw J;if($)return O1($,f.parseOptions);return{}}F0();import{existsSync as PK}from"node:fs";import{discoverPluginModulePaths as XK,resolveConfiguredPluginModulePaths as VK,resolvePluginConfigSearchPaths as YK}from"@cline/shared/storage";import{resolve as cy}from"node:path";import{normalizePluginManifest as dy}from"@cline/shared";import{existsSync as a0,readFileSync as bW}from"node:fs";import{builtinModules as wy,createRequire as PZ}from"node:module";import{dirname as z6,extname as XZ,isAbsolute as Cy,resolve as yf}from"node:path";import{fileURLToPath as VZ}from"node:url";import{PLUGIN_FILE_EXTENSIONS as Ey}from"@cline/shared";var Sy=z6(VZ(import.meta.url)),YZ=PZ(import.meta.url),ky=yf(Sy,"..","..","..","..",".."),NW=my(ky),wW=new Set(wy.flatMap((f)=>[f,f.replace(/^node:/,"")])),L6=new Set(Ey);function my(f){let $={},J={"@cline/agents":yf(f,"packages/agents/src/index.ts"),"@cline/core":yf(f,"packages/core/src/index.ts"),"@cline/llms":yf(f,"packages/llms/src/index.ts"),"@cline/shared":yf(f,"packages/shared/src/index.ts"),"@cline/shared/storage":yf(f,"packages/shared/src/storage/index.ts"),"@cline/shared/db":yf(f,"packages/shared/src/db/index.ts")};for(let[H,W]of Object.entries(J))if(a0(W))$[H]=W;return $}function BZ(f){return!(f.startsWith(".")||f.startsWith("/")||f.startsWith("file:")||f.startsWith("data:")||f.startsWith("http:")||f.startsWith("https:"))}function qW(f){if(f.startsWith("@")){let[$,J]=f.split("/",3);return J?`${$}/${J}`:f}return f.split("/",1)[0]??f}function AZ(f,$){let J=qW($),H=z6(f);while(!0){let W=yf(H,"node_modules",J);if(a0(W)||a0(yf(W,"package.json")))return!0;let Q=yf(H,"..");if(Q===H)return!1;H=Q}}function Iy(f){try{return YZ.resolve(f),!0}catch{return!1}}function xy(f){try{return YZ.resolve(f)}catch{return null}}function gy(f){let J=z6(f);for(let H=0;H<4;H++){let W=yf(J,"package.json");if(a0(W))try{let Z=JSON.parse(bW(W,"utf8"));return Z!=null&&typeof Z==="object"&&"cline"in Z}catch{return!1}let Q=yf(J,"..");if(Q===J)return!1;J=Q}return!1}function vy(f,$){let J=$.startsWith("file:")?VZ($):Cy($)?$:yf(z6(f),$);if(a0(J)&&L6.has(XZ(J)))return J;for(let H of L6){let W=`${J}${H}`;if(a0(W))return W}for(let H of L6){let W=yf(J,`index${H}`);if(a0(W))return W}return null}function RZ(f){let $=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let H of J)for(let W of f.matchAll(H)){let Q=W[1];if(Q)$.add(Q)}return[...$]}function FZ(f,$,J=new Set){if(J.has(f)||!a0(f))return;if(J.add(f),!L6.has(XZ(f)))return;let H=bW(f,"utf8");for(let W of RZ(H)){if(W.startsWith("node:")||wW.has(W))continue;if(BZ(W)){if(Object.hasOwn(NW,W)||Object.hasOwn(NW,qW(W))||AZ(f,W)||$&&Iy(W))continue;throw Error(`Cannot find module '${qW(W)}'`)}let Q=vy(f,W);if(Q)FZ(Q,$,J)}}function uy(f,$){let J=PZ(f),H={};for(let[W,Q]of Object.entries(NW)){try{J.resolve(W);continue}catch{}H[W]=Q}if($){let W=bW(f,"utf8");for(let Q of RZ(W)){if(!BZ(Q)||Q.startsWith("node:")||wW.has(Q)||Object.hasOwn(H,Q)||AZ(f,Q))continue;let Z=xy(Q);if(Z)H[Q]=Z}}return H}async function yZ(f,$={}){let J=!gy(f);FZ(f,J);let H=uy(f,J),W=await import("jiti"),Q=typeof W==="function"?W:typeof W.default==="function"?W.default:void 0;if(!Q)throw Error("Unable to load jiti");return await Q(f,{alias:H,cache:$.useCache,requireCache:$.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...wW],transformModules:Object.keys(H)}).import(f,{})}function KZ(f,$){if(!f)return!0;if(f.providerIds?.length){if(!$?.providerId||!f.providerIds.includes($.providerId))return!1}if(f.modelIds?.length){if(!$?.modelId||!f.modelIds.includes($.modelId))return!1}return!0}function UZ(f){return typeof f==="object"&&f!==null}function CW(f){return Array.isArray(f)&&f.every(($)=>typeof $==="string")}function ry(f,$){if(!UZ(f.manifest))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);if(!CW(f.manifest.capabilities))throw Error(`Invalid plugin module at ${$}: manifest.capabilities must be a string array`);if(f.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${$}: manifest.capabilities cannot be empty`);if(Object.hasOwn(f.manifest,"providerIds")&&!CW(f.manifest.providerIds))throw Error(`Invalid plugin module at ${$}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn(f.manifest,"modelIds")&&!CW(f.manifest.modelIds))throw Error(`Invalid plugin module at ${$}: manifest.modelIds must be a string array when provided`)}function ly(f,$){if(!UZ(f))throw Error(`Invalid plugin module at ${$}: expected object export`);if(typeof f.name!=="string"||f.name.length===0)throw Error(`Invalid plugin module at ${$}: expected non-empty "name"`);if(!Object.hasOwn(f,"manifest"))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);ry(f,$)}async function R8(f,$={}){let J=cy($.cwd??process.cwd(),f),H=await yZ(J,{useCache:$.useCache}),W=$.exportName??"plugin",Q=H.default??H[W];ly(Q,J);let Z=Q,j=Z.setup,P=j?(X,V)=>{let Y={...$.session,...V.session},B={...V,session:Object.keys(Y).length>0?Y:void 0,client:$.client??V.client,user:$.user??V.user,workspaceInfo:$.workspaceInfo??V.workspaceInfo,automation:$.automation??V.automation,logger:$.logger??V.logger,telemetry:$.telemetry??V.telemetry};return j(X,B)}:void 0;return{...Z,manifest:dy(Z.manifest),setup:P}}async function O6(f,$={}){return(await D0(f,$)).plugins}async function D0(f,$={}){let J=[],H=[],W=new Map,Q=0;for(let Z of f)try{let j=await R8(Z,$);if(!KZ(j.manifest,$))continue;let P=W.get(j.name);if(P)H.push({type:"duplicate_plugin_override",pluginName:j.name,pluginPath:Z,overriddenPluginPath:P.pluginPath,message:`Plugin "${j.name}" from ${Z} overrides ${P.pluginPath}`});W.set(j.name,{plugin:j,pluginPath:Z,order:Q++})}catch(j){let P=j instanceof Error?j.message:String(j);J.push({pluginPath:Z,phase:"load",message:P,stack:j instanceof Error?j.stack:void 0})}return{plugins:[...W.values()].sort((Z,j)=>Z.order-j.order).map((Z)=>Z.plugin),failures:J,warnings:H}}import{existsSync as ty}from"node:fs";import{createRequire as sy}from"node:module";import{dirname as oy,join as N6}from"node:path";import{fileURLToPath as ey}from"node:url";var MZ={};N(MZ,{resolveSubprocessRuntimeExecutable:()=>EW,buildSubprocessSandboxCommand:()=>DZ,SubprocessSandbox:()=>b1,CLINE_JS_RUNTIME_PATH_ENV:()=>TZ});import{spawn as py}from"node:child_process";import{basename as iy}from"node:path";import{augmentNodeCommandForDebug as ny,withResolvedClineBuildEnv as ay}from"@cline/shared";function GZ(f){if(f instanceof Error)return f;return Error(String(f))}var TZ="CLINE_JS_RUNTIME_PATH";function hZ(f){let $=f?.trim();if(!$)return!1;let J=iy($).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function EW(f={}){let $=f.env??process.env,J=f.runtimeExecutable?.trim()||$[TZ]?.trim();if(J)return J;let H=f.execPath?.trim()||process.execPath;if(hZ(H))return H;for(let W of[$.BUN_EXEC_PATH,$.npm_node_execpath,$.NODE]){let Q=W?.trim();if(Q&&hZ(Q))return Q}return"node"}function DZ(f,$={}){let J=EW({env:$.env,execPath:$.execPath,runtimeExecutable:$.runtimeExecutable});return ny([J,...f],{env:$.env,execArgv:$.execArgv,debugRole:$.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class b1{options;process=null;requestCounter=0;pending=new Map;constructor(f){this.options=f}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest(f){let $=this.pending.get(f);if(!$)return;if(this.pending.delete(f),$.timeout)clearTimeout($.timeout);return $}start(){if(this.process&&this.process.exitCode===null)return;let f=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],$=DZ(f,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=py($[0]??EW(this.options),$.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:ay(process.env)});this.process=J;let H="",W=(Q)=>{let Z=H+Q;H=Z.length>4000?Z.slice(-4000):Z};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(Q)=>{W(Q)}),J.on("message",(Q)=>{this.onMessage(Q)}),J.on("error",(Q)=>{this.failPending(Error(`${this.processLabel} process error: ${GZ(Q).message}`))}),J.on("exit",(Q,Z)=>{this.process=null;let j=H.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Q)}, signal=${String(Z)})${j?`: ${j}`:""}`))})}async call(f,$,J={}){this.start();let H=this.process;if(!H||H.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let W=`req_${++this.requestCounter}`,Q={type:"call",id:W,method:f,args:$};return await new Promise((Z,j)=>{let P={resolve:(X)=>Z(X),reject:j};if((J.timeoutMs??0)>0)P.timeout=setTimeout(()=>{this.clearPendingRequest(W),this.shutdown().catch(()=>{}),j(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${f}`))},J.timeoutMs);this.pending.set(W,P),H.send(Q,(X)=>{if(!X)return;let V=this.clearPendingRequest(W);if(!V)return;V.reject(Error(`${this.processLabel} failed to send call "${f}": ${GZ(X).message}`))})})}async shutdown(){let f=this.process;if(this.process=null,!f||f.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise(($)=>{let J=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}$()},300);f.once("exit",()=>{clearTimeout(J),$()});try{f.kill("SIGTERM")}catch{clearTimeout(J),$()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage(f){if(!f)return;if(f.type==="event"){if(typeof f.name==="string"&&f.name.length>0)this.options.onEvent?.({name:f.name,payload:f.payload});return}if(f.type!=="response"||!f.id)return;let $=this.clearPendingRequest(f.id);if(!$)return;if(f.ok){$.resolve(f.result);return}$.reject(Error(f.error?.message||`${this.processLabel} call failed`))}failPending(f){for(let[$,J]of this.pending.entries()){if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);J.reject(f)}}}function fK(f){return{...f,contributions:{tools:f.contributions?.tools??[],commands:f.contributions?.commands??[],messageBuilders:f.contributions?.messageBuilders??[],providers:f.contributions?.providers??[],automationEventTypes:f.contributions?.automationEventTypes??[],shortcuts:f.contributions?.shortcuts??[],flags:f.contributions?.flags??[]}}}function q6(f){return(f instanceof Error?f.message:String(f)).includes("Unknown sandbox plugin id:")}function $K(){let f=oy(ey(import.meta.url)),$=sy(import.meta.url),J=[N6(f,"plugin-sandbox-bootstrap.js"),N6(f,"extensions","plugin-sandbox-bootstrap.js"),N6(f,"agents","plugin-sandbox-bootstrap.js")];for(let Q of J)if(ty(Q))return{file:Q};let H=N6(f,"plugin-sandbox-bootstrap.ts"),W="jiti";try{W=$.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(W)});`,`const jiti = createJiti(${JSON.stringify(H)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(H)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
411
- `)}}var SW=$K();function kW(f,$){return typeof f==="number"&&f>0?f:$}async function LZ(f){let $=new b1({name:"plugin-sandbox",..."file"in SW?{bootstrapFile:SW.file}:{bootstrapScript:SW.script},onEvent:f.onEvent}),J=kW(f.importTimeoutMs,4000),H=kW(f.hookTimeoutMs,3000),W=kW(f.contributionTimeoutMs,60000),Q={pluginPaths:f.pluginPaths,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,loggerEnabled:Boolean(f.logger)},Z,j=()=>{return Z??=$.call("initialize",Q,{timeoutMs:J}).finally(()=>{Z=void 0}),Z},P;try{P=await $.call("initialize",Q,{timeoutMs:J})}catch(Y){throw await $.shutdown().catch(()=>{}),Y}return{extensions:P.plugins.map(fK).map((Y)=>{let B={name:Y.name,manifest:Y.manifest,setup:(A)=>{JK(A,$,Y,W,j),HK(A,$,Y,W,j),QK(A,$,Y,W,j),WK(A,Y)}};return B.hooks=jK($,Y,H,j),B}),failures:P.failures,shutdown:async()=>{await $.shutdown()},warnings:P.warnings}}function JK(f,$,J,H,W){for(let Q of J.contributions?.tools??[]){let Z={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema??{type:"object",properties:{}},timeoutMs:Q.timeoutMs,retryable:Q.retryable,execute:async(j,P)=>{try{return await $.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:j,context:P},{timeoutMs:H})}catch(X){if(!q6(X))throw X;return await W(),await $.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:j,context:P},{timeoutMs:H})}}};f.registerTool(Z)}}function HK(f,$,J,H,W){for(let Q of J.contributions?.commands??[])f.registerCommand({name:Q.name,description:Q.description,handler:async(Z)=>{try{return await $.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:Z},{timeoutMs:H})}catch(j){if(!q6(j))throw j;return await W(),await $.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:Z},{timeoutMs:H})}}})}function WK(f,$){for(let J of $.contributions?.providers??[])f.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of $.contributions?.automationEventTypes??[])f.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function QK(f,$,J,H,W){for(let Q of J.contributions?.messageBuilders??[])f.registerMessageBuilder({name:Q.name,async build(Z){try{let j=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:Z},{timeoutMs:H});return _Z(j)?j:Z}catch(j){if(!q6(j))throw j;await W();let P=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:Z},{timeoutMs:H});return _Z(P)?P:Z}}})}function _Z(f){return Array.isArray(f)&&f.every(($)=>typeof $==="object"&&$!==null&&("role"in $)&&("content"in $))}function ZK(f,$,J,H,W){return async(Q)=>{try{return await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:H})}catch(Z){if(!q6(Z))throw Z;return await W(),await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:H})}}}function jK(f,$,J,H){let W={};for(let Q of $.hooks??[])W[Q]=ZK(f,$.pluginId,Q,J,H);return Object.keys(W).length>0?W:void 0}function F8(f){return YK(f)}function y8(f){return XK(f)}function E$(f={}){let $=f.cwd??process.cwd(),J=F8(f.workspacePath).flatMap((Z)=>y8(Z)).filter((Z)=>PK(Z)),H=VK(f.pluginPaths??[],$),W=[],Q=new Set;for(let Z of[...H,...J]){if(Q.has(Z))continue;Q.add(Z),W.push(Z)}return a4(W)}async function w1(f={}){let $=E$(f);if($.length===0)return{extensions:[],failures:[],warnings:[]};if(f.mode==="in_process"){let H=await D0($,{cwd:f.cwd,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,automation:f.automation,logger:f.logger,telemetry:f.telemetry});return{extensions:H.plugins,failures:H.failures,warnings:H.warnings}}let J=await LZ({pluginPaths:$,exportName:f.exportName,importTimeoutMs:f.importTimeoutMs,hookTimeoutMs:f.hookTimeoutMs,contributionTimeoutMs:f.contributionTimeoutMs,onEvent:f.onEvent,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,logger:f.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,warnings:J.warnings}}import{execFile as BK}from"node:child_process";import{promisify as AK}from"node:util";var RK=AK(BK);function mW(f,$){f?.log($,{severity:"warn"})}function FK(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!J.latest||!Array.isArray(J.history))return;let H=J.latest,W=J.history.filter((Q)=>!!Q&&typeof Q==="object"&&typeof Q.ref==="string"&&typeof Q.createdAt==="number"&&typeof Q.runCount==="number");if(typeof H.ref!=="string"||typeof H.createdAt!=="number"||typeof H.runCount!=="number")return;return{latest:H,history:W}}async function S$(f,$){let J=await RK("git",["-C",f,...$],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function IW(f,$){if(!f)return;let J=`refs/cline/checkpoints/${$}/`;try{let{stdout:H}=await S$(f,["for-each-ref","--format=%(refname)",J]),W=H.trim().split(`
412
- `).filter(Boolean);await Promise.allSettled(W.map((Q)=>S$(f,["update-ref","-d",Q])))}catch{}}async function zZ(f,$,J){if(!f||J.length===0)return;await Promise.allSettled(J.map((H)=>S$(f,["update-ref",`refs/cline/checkpoints/${$}/${H.runCount}`,H.ref])))}function yK(f,$){let J=f.findIndex((H)=>H.runCount===$.runCount);if(J<0)return[...f,$];return f.map((H,W)=>W===J?$:H)}function OZ(f){let $=f.initialRunCount??0,J,H=async()=>{if(J!==void 0)return J;try{J=(await S$(f.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},W=async()=>{if(f.createCheckpoint)return await f.createCheckpoint({cwd:f.cwd,sessionId:f.sessionId,runCount:$});if(!await H())return;let Q=async(X)=>{try{let Y=(await S$(f.cwd,["rev-parse","HEAD"])).stdout.trim();if(!Y)return;return{ref:Y,createdAt:Date.now(),runCount:$,kind:"commit"}}catch(V){mW(f.logger,`${X}: ${V instanceof Error?V.message:String(V)}`);return}},Z=`cline checkpoint session=${f.sessionId} run=${$}`,j="";try{j=(await S$(f.cwd,["stash","create",Z])).stdout.trim()}catch(X){return mW(f.logger,`Checkpoint snapshot failed: ${X instanceof Error?X.message:String(X)}`),Q("Checkpoint HEAD fallback failed")}if(!j)return Q("Checkpoint HEAD fallback failed");let P=`refs/cline/checkpoints/${f.sessionId}/${$}`;try{await S$(f.cwd,["update-ref",P,j])}catch(X){mW(f.logger,`Checkpoint store failed: ${X instanceof Error?X.message:String(X)}`);return}return{ref:j,createdAt:Date.now(),runCount:$,kind:"stash"}};return{beforeRun:async({snapshot:Q})=>{if(Q.parentAgentId!=null)return;$+=1;return},beforeModel:async({snapshot:Q})=>{if(Q.parentAgentId!=null||Q.iteration!==1||$<1)return;let Z=await W();if(!Z)return;let j=await f.readSessionMetadata(),P=FK(j);if(P?.latest.ref===Z.ref)return;let X=yK(P?.history??[],Z);await f.writeSessionMetadata({...j??{},checkpoint:{latest:Z,history:X}});return}}}import{spawn as LK}from"node:child_process";import{appendFileSync as zK,readFileSync as OK}from"node:fs";import{join as NK}from"node:path";import{augmentNodeCommandForDebug as bZ,withResolvedClineBuildEnv as vW}from"@cline/shared";import{ensureHookLogDir as NZ}from"@cline/shared/storage";function C1(f,$){if(!$)return;return{name:f,manifest:{capabilities:["hooks"]},hooks:$}}import{existsSync as KK,readdirSync as UK}from"node:fs";import{basename as GK,extname as hK,join as TK}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as b6,resolveHooksConfigSearchPaths as DK}from"@cline/shared/storage";function K8(f){return DK(f)}var E1;((V)=>{V.TaskStart="TaskStart";V.TaskResume="TaskResume";V.TaskCancel="TaskCancel";V.TaskComplete="TaskComplete";V.TaskError="TaskError";V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.UserPromptSubmit="UserPromptSubmit";V.PreCompact="PreCompact";V.SessionShutdown="SessionShutdown"})(E1||={});var U8={["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"},MK=new Map(Object.values(E1).map((f)=>[f.toLowerCase(),f])),_K=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function G8(f){let $=hK(f).toLowerCase();if(!_K.has($))return;let J=GK(f,$).trim().toLowerCase();return MK.get(J)}function t0(f){let $=[],J=new Set,H=K8(f).filter((W)=>KK(W));for(let W of H)try{for(let Q of UK(W,{withFileTypes:!0})){if(!Q.isFile())continue;let Z=G8(Q.name);if(!Z)continue;let j=TK(W,Q.name);if(J.has(j))continue;J.add(j),$.push({fileName:Z,hookEventName:U8[Z],path:j})}}catch{}return $.sort((W,Q)=>W.path.localeCompare(Q.path))}function C6(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,H]of Object.entries(f))$[J]=typeof H==="string"?H:JSON.stringify(H);return $}function w6(f,$,J){let H=J instanceof Error?`: ${J.message}`:"",W=`${$}${H}`;if(f){try{f.log(W,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(W)}function qK(f,$){if(!$)return f;if(!f)return{...$};let J=[f.context,$.context].filter((W)=>typeof W==="string"&&W.length>0).join(`
413
- `),H=[...f.appendMessages??[],...$.appendMessages??[]];return{cancel:f.cancel===!0||$.cancel===!0?!0:void 0,review:f.review===!0||$.review===!0?!0:void 0,context:J||void 0,overrideInput:$.overrideInput!==void 0?$.overrideInput:f.overrideInput,systemPrompt:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,appendMessages:H.length>0?H:void 0}}function bK(f){if(!f||typeof f!=="object")return;let $=f,J=typeof $.context==="string"?$.context:typeof $.contextModification==="string"?$.contextModification:typeof $.errorMessage==="string"?$.errorMessage:void 0;return{cancel:typeof $.cancel==="boolean"?$.cancel:void 0,review:typeof $.review==="boolean"?$.review:void 0,context:J,overrideInput:Object.hasOwn($,"overrideInput")?$.overrideInput:void 0}}function xW(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function Yf(f,$){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",H={rootSessionId:$.rootSessionId||f.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:H,workspaceRoots:$.workspacePath?[$.workspacePath]:[],workspaceInfo:$.workspaceInfo,userId:J,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function wK(f){let $=f.trim();if(!$)return{};let H=$.split(`
414
- `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),W=H.length>0?H[H.length-1]:$;try{return{parsedJson:JSON.parse(W)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse hook stdout JSON"}}}async function CK(f,$){let J=f.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((H,W)=>{let Q=!1,Z=()=>{J.off("error",P),J.off("finish",X),f.off("close",V)},j=(Y)=>{if(Q)return;if(Q=!0,Z(),Y){let B=Y.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){H();return}W(Y);return}H()},P=(Y)=>j(Y),X=()=>j(),V=()=>j();J.on("error",P),J.once("finish",X),f.once("close",V);try{J.end($)}catch(Y){j(Y)}})}async function wZ(f,$){if($.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await qZ(f,$)}catch(J){let H=kK($.command,process.platform,J);if(!H)throw J;return await qZ(f,{...$,command:H})}}async function qZ(f,$){let J=bZ($.command,{env:$.env,debugRole:"hook"}),H=LK(J[0],J.slice(1),{cwd:$.cwd,env:vW($.env),stdio:$.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:$.detached}),W=new Promise((B)=>{H.once("spawn",()=>B())}),Q=new Promise((B,A)=>{H.once("error",(R)=>A(R))}),Z=JSON.stringify(f);if(await Promise.race([W,Q]),await CK(H,Z),$.detached){H.unref();return}if(!H.stdout||!H.stderr)throw Error("hook command failed to create stdout/stderr");let j="",P="",X=!1,V;H.stdout.on("data",(B)=>{j+=B.toString()}),H.stderr.on("data",(B)=>{P+=B.toString()});let Y=new Promise((B)=>{if(($.timeoutMs??0)>0)V=setTimeout(()=>{X=!0,H.kill("SIGKILL")},$.timeoutMs);H.once("close",(A)=>{if(V)clearTimeout(V);let{parsedJson:R,parseError:U}=wK(j);B({exitCode:A,stdout:j,stderr:P,parsedJson:R,parseError:U,timedOut:X})})});return await Promise.race([Y,Q])}function EK(f){try{let J=OK(f,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let H=J.slice(2).trim();if(!H)return;let W=H.split(/\s+/).filter(Boolean);return W.length>0?W:void 0}catch{return}}function SK(f){return!!(f&&typeof f==="object"&&("code"in f)&&f.code==="ENOENT")}function kK(f,$=process.platform,J){if($!=="win32"||!SK(J))return;if(f[0]!=="py"||f[1]!=="-3")return;return["python",...f.slice(2)]}function CZ(f){if(f.length===0)return;let[$,...J]=f,H=$.replace(/\\/g,"/").toLowerCase(),W=H.split("/").at(-1)??H;if(W==="env")return CZ(J);if(W==="bash"||W==="sh"||W==="zsh")return[W,...J];if(W==="python3"||W==="python")return process.platform==="win32"?["py","-3",...J]:[W,...J];return f}function mK(f){let $=EK(f);if($&&$.length>0)return[...CZ($)??$,f];let J=f.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",f];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return bZ(["node",f],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",f];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",f]:["python3",f];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",f];return["bash",f]}function IK(f){let $={};for(let J of t0(f)){if(!J.hookEventName)continue;let H=J.hookEventName,W=$[H]??[];W.push(mK(J.path)),$[H]=W}return $}async function xK(f){let $;for(let J of f.commands){let H=J.join(" ");try{let W=await wZ(f.payload,{command:J,cwd:f.cwd,env:vW(process.env),detached:!1,timeoutMs:f.timeoutMs});if(W?.timedOut){w6(f.logger,`hook command timed out: ${H}`);continue}if(W?.parseError){w6(f.logger,`hook command returned invalid JSON control output: ${H} (${W.parseError})`);continue}$=qK($,bK(W?.parsedJson))}catch(W){w6(f.logger,`hook command failed: ${H}`,W)}}return $}function k$(f){for(let $ of f.commands){let J=$.join(" ");wZ(f.payload,{command:$,cwd:f.cwd,env:vW(process.env),detached:!0}).catch((H)=>{w6(f.logger,`hook command failed: ${J}`,H)})}}function s0(f){return{agentId:f.agentId,conversationId:f.conversationId??f.runId??f.agentId,parentAgentId:f.parentAgentId??null}}function gW(f,$){return{...s0(f.snapshot),userMessage:$}}function EZ(f){return{...s0(f.snapshot),iteration:f.snapshot.iteration,call:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input}}}function SZ(f){return{...s0(f.snapshot),iteration:f.snapshot.iteration,record:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}}function kZ(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function gK(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}function S1(f){let $={cwd:f.workspacePath,workspacePath:f.workspacePath,rootSessionId:f.rootSessionId,workspaceInfo:f.workspaceInfo},J=(H)=>{let W=`${JSON.stringify({ts:new Date().toISOString(),...H})}
415
- `,Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??NK(NZ(),"hooks.jsonl");NZ(Z),zK(Z,W,"utf8")};return{beforeRun:async(H)=>{let W=gW(H,"");J({...Yf(W,$),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(H)=>{let W=EZ(H);J({...Yf(W,$),hookName:"tool_call",iteration:W.iteration,tool_call:{id:W.call.id,name:W.call.name,input:W.call.input},preToolUse:{toolName:W.call.name,parameters:C6(W.call.input)}});return},afterTool:async(H)=>{let W=SZ(H);J({...Yf(W,$),hookName:"tool_result",iteration:W.iteration,tool_result:W.record,postToolUse:{toolName:W.record.name,parameters:C6(W.record.input),result:typeof W.record.output==="string"?W.record.output:JSON.stringify(W.record.output),success:!W.record.error,executionTimeMs:W.record.durationMs}});return},afterRun:async({snapshot:H,result:W})=>{let Q=s0(H);if(W.status==="completed"){J({...Yf(Q,$),hookName:"agent_end",iteration:W.iterations,turn:{outputText:W.outputText,status:W.status},taskComplete:{taskMetadata:{}}});return}if(W.status==="aborted"||xW(W.error?.message)){J({...Yf(Q,$),hookName:"agent_abort",reason:W.error?.message,taskCancel:{taskMetadata:{}}});return}if(W.error)J({...Yf(Q,$),hookName:"agent_error",iteration:W.iterations,error:{name:W.error.name,message:W.error.message,stack:W.error.stack}})},onEvent:async(H)=>{if(H.type!=="message-added"||H.message.role!=="user")return;let W=gW({snapshot:H.snapshot},kZ(H.message.content));J({...Yf(W,$),hookName:"prompt_submit",userPromptSubmit:{prompt:W.userMessage,attachments:[]}})}}}function h8(f){let $=IK(f.workspacePath);if(!Object.values($).some((Y)=>Y.length>0))return;let H=async(Y,B)=>{let A=$[B]??[];if(A.length===0)return;k$({commands:A,cwd:f.cwd,logger:f.logger,payload:B==="agent_resume"?{...Yf(Y,f),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...Yf(Y,f),hookName:B,taskStart:{taskMetadata:{}}}})},W=async(Y)=>{let B=$.prompt_submit??[];if(B.length>0)k$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Yf(Y,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Y.userMessage,attachments:[]}}})},Q=async(Y)=>{let B=$.tool_call??[];if(B.length===0)return;return xK({commands:B,cwd:f.cwd,logger:f.logger,timeoutMs:f.toolCallTimeoutMs??120000,payload:{...Yf(Y,f),hookName:"tool_call",iteration:Y.iteration,tool_call:{id:Y.call.id,name:Y.call.name,input:Y.call.input},preToolUse:{toolName:Y.call.name,parameters:C6(Y.call.input)}}})},Z=async(Y)=>{let B=$.tool_result??[];if(B.length===0)return;k$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Yf(Y,f),hookName:"tool_result",iteration:Y.iteration,tool_result:Y.record,postToolUse:{toolName:Y.record.name,parameters:C6(Y.record.input),result:typeof Y.record.output==="string"?Y.record.output:JSON.stringify(Y.record.output),success:!Y.record.error,executionTimeMs:Y.record.durationMs}}})},j=async(Y)=>{let B=$.agent_end??[];if(B.length===0)return;k$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Yf(Y,f),hookName:"agent_end",iteration:Y.iteration,turn:Y.turn,taskComplete:{taskMetadata:{}}}})},P=async(Y)=>{let B=$.agent_error??[];if(B.length===0)return;k$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Yf(Y,f),hookName:"agent_error",iteration:Y.iteration,error:{name:Y.error.name,message:Y.error.message,stack:Y.error.stack}}})},X=async(Y)=>{if(xW(Y.reason)){let A=$.agent_abort??[];if(A.length>0)k$({commands:A,cwd:f.cwd,logger:f.logger,payload:{...Yf(Y,f),hookName:"agent_abort",reason:Y.reason,taskCancel:{taskMetadata:{}}}})}let B=$.session_shutdown??[];if(B.length===0)return;k$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Yf(Y,f),hookName:"session_shutdown",reason:Y.reason}})},V={};if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0||($.prompt_submit?.length??0)>0){if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0)V.beforeRun=async(Y)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await H(s0(Y.snapshot),B);return};if(($.prompt_submit?.length??0)>0)V.onEvent=async(Y)=>{if(Y.type!=="message-added"||Y.message.role!=="user")return;await W(gW({snapshot:Y.snapshot},kZ(Y.message.content)))}}if(($.tool_call?.length??0)>0)V.beforeTool=async(Y)=>{let B=await Q(EZ(Y));return gK(B)};if(($.tool_result?.length??0)>0)V.afterTool=async(Y)=>{await Z(SZ(Y));return};if(($.agent_end?.length??0)>0)V.afterRun=async({snapshot:Y,result:B})=>{if(B.status!=="completed")return;await j({...s0(Y),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if(($.agent_error?.length??0)>0||($.agent_abort?.length??0)>0||($.session_shutdown?.length??0)>0){let Y=V.afterRun;V.afterRun=async(B)=>{await Y?.(B);let{snapshot:A,result:R}=B;if(R.status==="aborted"||xW(R.error?.message)){await X({...s0(A),reason:R.error?.message});return}if(R.error)await P({...s0(A),iteration:R.iterations,error:R.error})}}return V}function k1(f){return C1("core.hook_config_files",h8(f))}function m$(f,$){let J=f.map((H)=>H[$]).filter((H)=>typeof H==="function");if(J.length===0)return;return async(H)=>{let W;for(let Q of J){let Z=await Q(H);if(!Z||typeof Z!=="object")continue;let j=Z;W={...W??{},...j,stop:W?.stop===!0||j.stop===!0?!0:j.stop,options:W?.options||j.options?{...W?.options??{},...j.options??{}}:void 0}}return W}}function I$(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return;return{beforeRun:m$($,"beforeRun"),afterRun:m$($,"afterRun"),beforeModel:m$($,"beforeModel"),afterModel:m$($,"afterModel"),beforeTool:m$($,"beforeTool"),afterTool:m$($,"afterTool"),onEvent:m$($,"onEvent")}}var mZ={};N(mZ,{normalizeRuntimeCapabilities:()=>Bf});function Bf(...f){let $,J;for(let W of f){if(!W)continue;if(W.toolExecutors)$={...$??{},...W.toolExecutors};if(W.requestToolApproval)J=W.requestToolApproval}let H=$&&Object.keys($).length>0;if(!H&&!J)return;return{...H?{toolExecutors:$}:{},...J?{requestToolApproval:J}:{}}}var eZ={};N(eZ,{toProviderConfig:()=>Cf,emptyStoredProviderSettings:()=>$$,StoredProviderSettingsSchema:()=>u1,StoredProviderSettingsEntrySchema:()=>PJ,ProviderSettingsSchemaTyped:()=>q8});import{z as f$}from"zod";var oZ={};N(oZ,{toProviderConfig:()=>Cf,safeParseSettings:()=>jJ,safeCreateProviderConfig:()=>H5,parseSettings:()=>ZJ,normalizeProviderId:()=>v1,isBuiltInProviderId:()=>$5,createProviderConfig:()=>J5,SapSettingsSchema:()=>HJ,ReasoningSettingsSchema:()=>e6,ProviderSettingsSchema:()=>e0,ProviderProtocolSchema:()=>t6,ProviderIdSchema:()=>N8,ProviderClientSchema:()=>s6,OcaSettingsSchema:()=>WJ,ModelCatalogSettingsSchema:()=>QJ,GcpSettingsSchema:()=>$J,BUILT_IN_PROVIDER_IDS:()=>f5,BUILT_IN_PROVIDER:()=>O8,AzureSettingsSchema:()=>JJ,AwsSettingsSchema:()=>fJ,AuthSettingsSchema:()=>o6});import*as wf from"@cline/llms";import{z as _}from"zod";Kf();var lZ={};N(lZ,{refreshOcaToken:()=>D8,loginOcaOAuth:()=>x1,getValidOcaCredentials:()=>M8,generateOcaOpcRequestId:()=>u6,createOcaRequestHeaders:()=>rW,createOcaOAuthProvider:()=>dW,OCI_HEADER_OPC_REQUEST_ID:()=>g6,DEFAULT_INTERNAL_OCA_BASE_URL:()=>m1,DEFAULT_INTERNAL_IDCS_URL:()=>S6,DEFAULT_INTERNAL_IDCS_SCOPES:()=>k6,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>E6,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>I1,DEFAULT_EXTERNAL_IDCS_URL:()=>I6,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>x6,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>m6});import{nanoid as xZ}from"nanoid";class uW{ttlMs;maxEntries;entries=new Map;constructor(f,$){this.ttlMs=f;this.maxEntries=$}get(f,$=Date.now()){this.pruneExpired($);let J=this.entries.get(f);if(!J)return;return this.entries.delete(f),this.entries.set(f,J),J.value}set(f,$,J=Date.now(),H=this.ttlMs){this.pruneExpired(J),this.entries.delete(f);while(this.entries.size>=this.maxEntries){let W=this.entries.keys().next().value;if(W===void 0)break;this.entries.delete(W)}this.entries.set(f,{value:$,expiresAt:J+H})}pruneExpired(f){for(let[$,J]of this.entries)if(J.expiresAt<=f)this.entries.delete($)}}var IZ={};N(IZ,{startLocalOAuthServer:()=>M0});function vK(){let f;return{promise:new Promise((J)=>{f=J}),resolve:f}}async function M0(f){let $=await import("node:http"),J=f.host??"127.0.0.1",H=f.timeoutMs??300000,W=f.successHtml??uK,Q=vK(),Z=!1,j=null,P=null,X=null,V=(A)=>{if(Z)return;Z=!0,Q.resolve(A)},Y=()=>{if(j)clearTimeout(j),j=null;let A=X;if(X=null,P)P.close(),P=null;if(A!==null&&f.onClose)Promise.resolve(f.onClose({host:J,port:A})).catch(()=>{})},B=async()=>{return j=setTimeout(()=>{Y(),V(null)},H),Q.promise};for(let A of f.ports){let R=$.createServer((y,F)=>{try{let K=new URL(y.url||"",`http://${J}:${A}`);if(K.pathname!==f.callbackPath){F.statusCode=404,F.end("Not found");return}let M={url:K,code:K.searchParams.get("code")??void 0,state:K.searchParams.get("state")??void 0,provider:K.searchParams.get("provider")??void 0,error:K.searchParams.get("error")??void 0};if(M.error){F.statusCode=400,F.end(`Authentication failed: ${M.error}`),Y(),V(M);return}if(!M.code){F.statusCode=400,F.end("Missing authorization code");return}if(f.expectedState&&M.state!==f.expectedState){F.statusCode=400,F.end("State mismatch");return}F.statusCode=200,F.setHeader("Content-Type","text/html; charset=utf-8"),F.end(W),Y(),V(M)}catch{F.statusCode=500,F.end("Internal error")}}),U=await new Promise((y)=>{let F=(K)=>{R.off("error",F),y({bound:!1,error:K})};R.once("error",F),R.listen(A,J,()=>{R.off("error",F),P=R,y({bound:!0})})});if(U.error){if(U.error.code==="EADDRINUSE")continue;throw Y(),U.error}if(U.bound){X=A;let y=`http://${J}:${A}${f.callbackPath}`;if(f.onListening)await Promise.resolve(f.onListening({host:J,port:A,callbackUrl:y})).catch(()=>{});return{callbackUrl:y,waitForCallback:B,cancelWait:()=>{Y(),V(null)},close:()=>{Y(),V(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var uK=`<!DOCTYPE html>
407
+ ${W}`;return J||W}function BK(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return{};return{beforeRun:async(J)=>{for(let W of $){let H=await W.beforeRun?.(J);if(H?.stop)return H}return},afterRun:async(J)=>{for(let W of $)await W.afterRun?.(J)},beforeModel:async(J)=>{let W=J.request,H;for(let Q of $){let Z=await Q.beforeModel?.({...J,request:W});if(!Z)continue;if(Z.stop)return Z;H={...H,...Z,options:{...H?.options??{},...Z.options??{}}},W={...W,...Z.messages?{messages:Z.messages}:{},...Z.tools?{tools:Z.tools}:{},...Z.options?{options:{...W.options??{},...Z.options}}:{}}}return H},afterModel:async(J)=>{for(let W of $){let H=await W.afterModel?.(J);if(H?.stop)return H}return},beforeTool:async(J)=>{let W=J.input,H;for(let Q of $){let Z=await Q.beforeTool?.({...J,input:W});if(!Z)continue;if(Z.stop||Z.skip)return Z;if(H={...H,...Z},Object.hasOwn(Z,"input"))W=Z.input}return H},afterTool:async(J)=>{let W=J.result,H;for(let Q of $){let Z=await Q.afterTool?.({...J,result:W});if(!Z)continue;if(Z.stop)return Z;if(H={...H,...Z},Z.result)W=Z.result}return H},onEvent:async(J)=>{for(let W of $)await W.onEvent?.(J)}}}class a0{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 yW;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor(f,$={}){this.config=f,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=f.parentAgentId,this.logger=$.logger??f.logger,this.telemetry=$.telemetry??f.telemetry,this.createAgentRuntimeImpl=$.createAgentRuntimeImpl??ZK,this.conversation=new VW(f.initialMessages),this.messageBuilder=new BW,this.contributionRegistry=jK({extensions:f.extensions?[...f.extensions]:[],setupContext:{session:f.extensionContext?.session,client:f.extensionContext?.client,user:f.extensionContext?.user,workspaceInfo:f.extensionContext?.workspace,automation:f.extensionContext?.automation,logger:f.extensionContext?.logger??this.logger,telemetry:f.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=f.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new KW({maxConsecutiveMistakes:J,onLimitReached:f.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,Z,j)=>YK(this.logger,Q,Z,j),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(Q,Z)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q}]})}});let W=f.execution?.loopDetection;this.loopDetectionDisabled=W===!1;let H=W===!1||W===void 0?void 0:W;this.loopTracker=new FW(H)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools(f){if(f.length===0)return;let $=new Set(this.config.tools.map((W)=>W.name)),J=[...this.config.tools];for(let W of f)if(!$.has(W.name))J.push(W),$.add(W.name);this.config={...this.config,tools:J}}updateConnection(f){let $={...this.config};if(f.providerId!==void 0)$.providerId=f.providerId;if(f.modelId!==void 0)$.modelId=f.modelId;if(f.apiKey!==void 0)$.apiKey=f.apiKey;if(f.baseUrl!==void 0)$.baseUrl=f.baseUrl;if(f.headers!==void 0)$.headers=f.headers;if(f.providerConfig!==void 0)$.providerConfig=f.providerConfig;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinking!==void 0)$.thinking=f.thinking;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;this.config=$}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore(f){this.conversation.restore(f),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}abort(f){let $=typeof f==="string"?f:f instanceof Error?f.message:f===void 0?void 0:String(f);if(this.abortRequested=!0,this.abortReason=$,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort($)}async shutdown(f,$){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run(f,$,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!1})}continue(f,$,J){return this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let f=[];for(let $ of this.contributionRegistry.getRegisteredRules()){let J=await AK($);if(J)f.push(J)}return PK(this.config.systemPrompt,f)}executeRun(f){let $;return $=this.executeRunInternal(f).finally(()=>{if(this.activeRunPromise===$)this.activeRunPromise=null}),this.activeRunPromise=$,$}async executeRunInternal(f){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let $=new Date,J=f.userMessage;if(J!==void 0){let F=await RK(J,f.userImages,f.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let W=await this.composeSystemPrompt(),H=L7(this.config,this.logger),Q=this.contributionRegistry.getRegisteredTools(),Z=new Map;for(let F of Q)Z.set(F.name,F);for(let F of this.config.tools)Z.set(F.name,F);let j=this.conversation.getConversationId(),X=I7(this.config),A=Array.from(Z.values()),P=T6(this.conversation.getMessages()),B=E7({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:j,parentAgentId:this.parentAgentId,model:H,logger:this.logger,tools:A,toolContextMetadata:{modelSupportsImages:X?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(X,A),initialMessages:P,systemPrompt:W}),Y=this.createAgentRuntimeImpl(B);if(this.activeRuntime=Y,this.abortRequested)Y.abort(this.abortReason);let V=Y.subscribe((F)=>{this.handleRuntimeEvent(F)}),R,U;try{if(f.isContinue)R=await Y.continue(void 0);else R=await Y.run("")}catch(F){U=F instanceof Error?F:Error(String(F))}finally{V();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(R&&R.messages.length>0){let F=D1(R.messages);this.conversation.replaceMessages(F)}let K=new Date;try{return this.buildLegacyResult({runResult:R,thrownError:U,startedAt:$,endedAt:K})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch(f){if(this.config.hookErrorMode==="throw")throw f;this.emitLegacyEvent({type:"error",error:f instanceof Error?f:Error(String(f)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let f=BK([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map(($)=>$.hooks)]);return{...f,beforeModel:async($)=>{let J=await f.beforeModel?.($);if(J?.stop)return J;let W=J?.messages??$.request.messages,H=await this.prepareMessagesForModelRequest(W);return{...J,messages:H}}}}createRuntimePrepareTurn(f,$){let J=this.config.prepareTurn;if(!J)return;return async(W)=>{let H=D1(W.messages),Q=await this.prepareProviderMessagesForApi(H),Z=await J({agentId:W.agentId,conversationId:W.conversationId??this.conversation.getConversationId(),parentAgentId:W.parentAgentId??null,iteration:W.iteration,messages:H,apiMessages:Q,abortSignal:W.signal??new AbortController().signal,systemPrompt:W.systemPrompt??"",tools:$,model:{id:this.config.modelId,provider:this.config.providerId,info:f},emitStatusNotice:W.emitStatusNotice});if(!Z)return;return{...Z.messages?{messages:T6(Z.messages)}:{},...Z.systemPrompt!==void 0?{systemPrompt:Z.systemPrompt}:{}}}}async prepareMessagesForModelRequest(f){let $=await this.prepareProviderMessagesForApi(w7(f));return T6($)}async prepareProviderMessagesForApi(f){let $=f,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let W of J)$=await W.build($);return this.messageBuilder.buildForApi($)}handleRuntimeEvent(f){switch(f.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage(f.snapshot.messages,[f.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set(f.toolCall.toolCallId,new Date),this.toolInputs.set(f.toolCall.toolCallId,f.toolCall.input),this.inspectLoopForToolCall(f.toolCall.toolName,f.toolCall.input,f.iteration);break}case"tool-finished":{let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=new Date,W=this.toolInputs.get(f.toolCall.toolCallId);this.toolStartedAt.delete(f.toolCall.toolCallId),this.toolInputs.delete(f.toolCall.toolCallId);let H=f.message.content.find((X)=>X.type==="tool-result"),Q=H?.type==="tool-result"&&H.isError===!0,Z=Q?XK(H?.type==="tool-result"?H.output:void 0):void 0,j={id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:W,output:H?.type==="tool-result"?H.output:void 0,error:Z,durationMs:$===void 0?0:J.getTime()-$.getTime(),startedAt:$??J,endedAt:J};if(this.currentRunToolCalls.push(j),Q){if(this.currentTurnFailedTools+=1,Z)this.currentTurnFailureDetails.push(`[${f.toolCall.toolName}] ${Z}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let $=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if($>0&&J===0){let W=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:f.iteration,reason:"tool_execution_failed",details:`${$} tool call(s) failed${W?`: ${W}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost};break}default:break}for(let $ of this.eventAdapter.translate(f))this.emitLegacyEvent($)}syncConversationFromRuntimeMessage(f,$){if(f.length>0){this.conversation.replaceMessages(D1(f));return}if($.length===0)return;let J=new Set(this.conversation.getMessages().map((H)=>H.id).filter((H)=>typeof H==="string")),W=D1($).filter((H)=>!H.id||!J.has(H.id));if(W.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...W])}emitLegacyEvent(f){for(let $ of this.listeners)try{$(f)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall(f,$,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let W=this.loopTracker.inspect({name:f,input:$});if(W.kind==="ok")return;if(W.kind==="soft"){if(W.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:W.message??`Detected repeated tool calls to \`${f}\`; stopping to avoid a loop.`})}enqueueMistakeRecord(f){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let $=await this.mistakeTracker.record(f);if($.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:$.message}]}),this.activeRuntime?.abort($.reason??$.message)})}buildLegacyResult(f){let{runResult:$,thrownError:J,startedAt:W,endedAt:H}=f,Q=H.getTime()-W.getTime(),Z=J?"error":VK($),j=$?.outputText||($?.status==="failed"?$.error?.message:void 0)||"",X=$?{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost}:this.currentRunUsage,A=$?D1($.messages):this.conversation.getMessages(),P=I7(this.config);if(J)throw J;return{text:j,usage:X,messages:A,toolCalls:this.currentRunToolCalls,iterations:$?.iterations??0,finishReason:Z,model:{id:this.config.modelId,provider:this.config.providerId,info:P},startedAt:W,endedAt:H,durationMs:Q}}}function YK(f,$,J,W){if(!f)return;if($==="debug"){f.debug(J,W);return}if($==="error"&&f.error){f.error(J,W);return}let H=$==="warn"?"warn":$==="error"?"error":"info";f.log(J,{...W,severity:H})}function VK(f){if(!f)return"error";switch(f.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function RK(f,$,J,W){let{buildInitialUserContent:H}=await Promise.resolve().then(() => k7);return H(f,$,J,W)}function I7(f){if(f.knownModels?.[f.modelId])return f.knownModels[f.modelId];let $=AW(f);if($?.[f.modelId])return $[f.modelId];return}import{buildClineSystemPrompt as m7}from"@cline/shared";function x7(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return m7({ide:$.clineIdeName?.trim()||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,rules:`# Team Teammate Role
408
+ ${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function g7(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return m7({ide:$.clineIdeName||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,overridePrompt:J,metadata:$.workspaceMetadata,platform:$.clinePlatform})}function _1(f){let $={...f};return{getRuntimeConfig:()=>$,getConnectionConfig:()=>({providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking}),updateConnectionDefaults:(J)=>{$={...$,...J}}}}function z$(f){let $=f.configProvider.getRuntimeConfig(),J=f.kind==="teammate"?x7(f.prompt,$):g7(f.prompt,$);return{...f.configProvider.getConnectionConfig(),systemPrompt:J,tools:f.tools,maxIterations:f.maxIterations??$.maxIterations,parentAgentId:f.parentAgentId,abortSignal:f.abortSignal,onEvent:f.onEvent,hooks:$.hooks,extensions:$.extensions,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval,logger:$.logger,role:f.role}}function M1(f){let $=z$(f),J=new a0($);if($.onEvent)J.subscribeEvents($.onEvent);return J}var yK=UW.object({systemPrompt:UW.string().describe("System prompt defining the sub-agent's behavior"),task:UW.string().describe("Task for the sub-agent to complete")});function t0(f){return FK({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:KK(yK),execute:async($,J)=>{let W=f.createSubAgentTools?await f.createSubAgentTools($,J):f.subAgentTools??[],H=M1({kind:"subagent",prompt:$.systemPrompt,configProvider:f.configProvider,tools:W,maxIterations:f.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:f.onSubAgentEvent,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval}),Q=H.getAgentId(),Z=H.getConversationId(),j=J.agentId;if(f.onSubAgentStart)try{await f.onSubAgentStart({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$})}catch{}try{let X=await H.run($.task),A={text:X.text,iterations:X.iterations,finishReason:X.finishReason,usage:{inputTokens:X.usage.inputTokens,outputTokens:X.usage.outputTokens}};if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$,result:A,agentResult:X})}catch{}return A}catch(X){if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$,error:X instanceof Error?X:Error(String(X))})}catch{}throw X}},timeoutMs:300000,retryable:!1})}import{createTool as Zf,TEAM_AWAIT_TIMEOUT_MS as UK,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as GK,TEAM_RUN_TEXT_PREVIEW_LIMIT as TK,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as DK,TeamAttachOutcomeFragmentInputSchema as v7,TeamAwaitRunsInputSchema as u7,TeamBroadcastInputSchema as c7,TeamBroadcastToolResultSchema as _K,TeamCancelRunInputSchema as d7,TeamCancelRunToolResultSchema as MK,TeamCleanupInputSchema as r7,TeamCleanupToolResultSchema as LK,TeamCreateOutcomeInputSchema as l7,TeamCreateOutcomeToolResultSchema as hK,TeamFinalizeOutcomeInputSchema as p7,TeamFinalizeOutcomeToolResultSchema as OK,TeamListOutcomesInputSchema as i7,TeamListRunsInputSchema as n7,TeamMailboxMessageToolResultSchema as zK,TeamMissionLogInputSchema as a7,TeamMissionLogToolResultSchema as NK,TeamOutcomeFragmentToolResultSchema as t7,TeamOutcomeToolResultSchema as qK,TeamReadMailboxInputSchema as s7,TeamReviewOutcomeFragmentInputSchema as o7,TeamRunTaskInputSchema as e7,TeamRunTaskToolResultSchema as GW,TeamRunToolSummarySchema as TW,TeamSendMessageInputSchema as fZ,TeamSendMessageToolResultSchema as wK,TeamShutdownTeammateInputSchema as $Z,TeamSimpleAgentStatusToolResultSchema as JZ,TeamSpawnTeammateInputSchema as WZ,TeamStatusInputSchema as HZ,TeamStatusToolResultSchema as bK,TeamTaskInputSchema as QZ,TeamTaskToolResultSchema as j8,validateWithZod as b,zodToJsonSchema as jf}from"@cline/shared";function ZZ(f,$){let J=f.replace(/\s+/g," ").trim();if(J.length<=$)return J;return`${J.slice(0,Math.max(0,$-3)).trimEnd()}...`}function N$(f,$){if(f===void 0)throw Error(`Missing required field: ${$}`);return f}function CK(f){let $=f.result;if(!$)return;return{textPreview:ZZ($.text,TK),iterations:$.iterations,finishReason:$.finishReason,durationMs:$.durationMs,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost}}}function D6(f){return f?.toISOString()}function DW(f){return{id:f.id,agentId:f.agentId,taskId:f.taskId,status:f.status,messagePreview:ZZ(f.message,GK),priority:f.priority,retryCount:f.retryCount,maxRetries:f.maxRetries,nextAttemptAt:D6(f.nextAttemptAt),continueConversation:f.continueConversation,startedAt:f.startedAt.toISOString(),endedAt:D6(f.endedAt),leaseOwner:f.leaseOwner,heartbeatAt:D6(f.heartbeatAt),lastProgressAt:D6(f.lastProgressAt),lastProgressMessage:f.lastProgressMessage,currentActivity:f.currentActivity,error:f.error,resultSummary:CK(f)}}function EK(f){if(f.status==="failed")throw Error(`Run "${f.id}" failed${f.error?`: ${f.error}`:""}`);if(f.status==="cancelled")throw Error(`Run "${f.id}" was cancelled${f.error?`: ${f.error}`:""}`);if(f.status==="interrupted")throw Error(`Run "${f.id}" was interrupted${f.error?`: ${f.error}`:""}`)}var L1=["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 jZ(f){let $=[];if(f.createBaseTools)$.push(...f.createBaseTools());$.push(...q$({runtime:f.runtime,requesterId:f.spec.agentId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!1})),f.runtime.spawnTeammate({agentId:f.spec.agentId,config:z$({kind:"teammate",prompt:f.spec.rolePrompt,role:f.spec.rolePrompt,configProvider:f.teammateConfigProvider,tools:$,maxIterations:f.spec.maxIterations,cwd:f.teammateConfigProvider.getRuntimeConfig().cwd})})}function h1(f){let $=f.leadAgentId??"lead",J=f.restoredFromPersistence===!0,W=q$({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!0,includeSpawnTool:f.includeLeadSpawnTool,includeManagementTools:f.includeLeadManagementTools,onLeadToolsUnlocked:f.onLeadToolsUnlocked}),H=[];for(let Q of f.restoredTeammates??[]){if(f.runtime.isTeammateActive(Q.agentId))continue;jZ({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:Q}),H.push(Q.agentId)}return{tools:W,restoredFromPersistence:J,restoredTeammates:H}}function q$(f){let $=f.allowSpawn??!0,J=f.includeSpawnTool??!0,W=f.includeManagementTools??!0,H=[];if(J)H.push(Zf({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:jf(WZ),execute:async(Z)=>{let j=b(WZ,Z);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!$)throw Error("Spawning teammates is disabled in this context.");let X={agentId:j.agentId,rolePrompt:j.rolePrompt};if(jZ({runtime:f.runtime,requesterId:f.requesterId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:X}),!W)f.onLeadToolsUnlocked?.(q$({...f,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return b(JZ,{agentId:j.agentId,status:"spawned"})}}));if(!W)return H;H.push(Zf({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:jf($Z),execute:async(Z)=>{let j=b($Z,Z);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return f.runtime.shutdownTeammate(j.agentId,j.reason),b(JZ,{agentId:j.agentId,status:"stopped"})}})),H.push(Zf({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:jf(HZ),execute:async(Z)=>{return b(HZ,Z),b(bK,f.runtime.getSnapshot())}})),H.push(Zf({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:jf(QZ),execute:async(Z)=>{let j=b(QZ,Z);switch(j.action){case"create":{let X=new Set(DK.create??[]),A=Object.entries(Z).filter(([B,Y])=>X.has(B)&&Y!=null).map(([B])=>B),P=f.runtime.createTask({title:N$(j.title,"title"),description:N$(j.description,"description"),dependsOn:j.dependsOn,assignee:j.assignee,createdBy:f.requesterId});return b(j8,{action:"create",taskId:P.id,status:P.status,...A.length>0?{ignoredFields:A,note:`Ignored fields for action=create: ${A.join(", ")}`}:{}})}case"list":return b(j8,{action:"list",tasks:f.runtime.listTaskItems({status:j.status,assignee:j.assignee})});case"claim":{let X=f.runtime.claimTask(N$(j.taskId,"taskId"),f.requesterId);return b(j8,{action:"claim",taskId:X.id,status:X.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let X=f.runtime.completeTask(N$(j.taskId,"taskId"),f.requesterId,N$(j.summary,"summary"));return b(j8,{action:"complete",taskId:X.id,status:X.status})}case"block":{let X=f.runtime.blockTask(N$(j.taskId,"taskId"),f.requesterId,N$(j.reason,"reason"));return b(j8,{action:"block",taskId:X.id,status:X.status})}}}}));let Q=new Map;return H.push(Zf({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:jf(e7),execute:async(Z)=>{let j=b(e7,Z);if(j.runMode==="async"){let P=f.runtime.startTeammateRun(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:f.requesterId,continueConversation:j.continueConversation||void 0});return b(GW,{agentId:j.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${j.agentId} and queued as ${P.id}.`,runId:P.id})}let X=Q.get(j.agentId);if(X){let P=await X;return b(GW,{...P,status:"joined",deduped:!0,message:`Task for ${j.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let A=f.runtime.routeToTeammate(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:f.requesterId,continueConversation:j.continueConversation||void 0}).then((P)=>b(GW,{agentId:j.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${j.agentId} and completed in sync mode.`,text:P.text,iterations:P.iterations})).finally(()=>{Q.delete(j.agentId)});return Q.set(j.agentId,A),await A}})),H.push(Zf({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:jf(d7),execute:async(Z)=>{let j=b(d7,Z),X=f.runtime.cancelRun(j.runId,j.reason);return b(MK,{runId:X.id,status:X.status})}})),H.push(Zf({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:jf(n7),execute:async(Z)=>b(TW.array(),f.runtime.listRuns(b(n7,Z)).map(DW))})),H.push(Zf({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:jf(u7),timeoutMs:UK,execute:async(Z)=>{let j=b(u7,Z);if(j.runId){let P=await f.runtime.awaitRun(j.runId);return EK(P),b(TW,DW(P))}let X=await f.runtime.awaitAllRuns(),A=X.filter((P)=>["failed","cancelled","interrupted"].includes(P.status));if(A.length>0){let P=A.map((B)=>`${B.id}:${B.status}${B.error?`(${B.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${P}`)}return b(TW.array(),X.map(DW))}})),H.push(Zf({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:jf(fZ),execute:async(Z)=>{let j=b(fZ,Z),X=f.runtime.sendMessage(f.requesterId,j.toAgentId,j.subject,j.body,j.taskId??void 0);return b(wK,{id:X.id,toAgentId:X.toAgentId})}})),H.push(Zf({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:jf(c7),execute:async(Z)=>{let j=b(c7,Z),X=f.runtime.broadcast(f.requesterId,j.subject,j.body,{taskId:j.taskId??void 0});return b(_K,{delivered:X.length})}})),H.push(Zf({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:jf(s7),execute:async(Z)=>{let j=b(s7,Z);return b(zK.array(),f.runtime.listMailbox(f.requesterId,{unreadOnly:j.unreadOnly,markRead:!0}))}})),H.push(Zf({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:jf(a7),execute:async(Z)=>{let j=b(a7,Z),X=f.runtime.appendMissionLog({agentId:f.requesterId,taskId:j.taskId||void 0,kind:j.kind,summary:j.summary,evidence:j.evidence?.length?j.evidence:void 0,nextAction:j.nextAction||void 0});return b(NK,{id:X.id})}})),H.push(Zf({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:jf(r7),execute:async(Z)=>{if(b(r7,Z),f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return f.runtime.cleanup(),b(LK,{status:"cleaned"})}})),H.push(Zf({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:jf(l7),execute:async(Z)=>{let j=b(l7,Z),X=f.runtime.createOutcome({title:j.title,requiredSections:j.requiredSections,createdBy:f.requesterId});return b(hK,{outcomeId:X.id,status:X.status,requiredSections:X.requiredSections})}})),H.push(Zf({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:jf(v7),execute:async(Z)=>{let j=b(v7,Z),X=f.runtime.attachOutcomeFragment({outcomeId:j.outcomeId,section:j.section,sourceAgentId:f.requesterId,sourceRunId:j.sourceRunId||void 0,content:j.content});return b(t7,{fragmentId:X.id,status:X.status})}})),H.push(Zf({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:jf(o7),execute:async(Z)=>{let j=b(o7,Z),X=f.runtime.reviewOutcomeFragment({fragmentId:j.fragmentId,reviewedBy:f.requesterId,approved:j.approved});return b(t7,{fragmentId:X.id,status:X.status})}})),H.push(Zf({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:jf(p7),execute:async(Z)=>{let j=b(p7,Z),X=f.runtime.finalizeOutcome(j.outcomeId);return b(OK,{outcomeId:X.id,status:X.status})}})),H.push(Zf({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:jf(i7),execute:async(Z)=>{return b(i7,Z),b(qK.array(),f.runtime.listOutcomes())}})),H}function _6(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}function XZ(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var SK=[{id:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:t0({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...L1]}],kK={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function IK(f){return f==="plan"||f==="yolo"?f:"act"}function PZ(f){let $=IK(f.mode),J=kf[L0({mode:$})],W=T1(f.providerId??"",f.modelId??"",$,G1);return{mode:$,flags:{...J,...W,...typeof f.enableSpawnAgent==="boolean"?{enableSpawnAgent:f.enableSpawnAgent}:{},...typeof f.enableAgentTeams==="boolean"?{enableAgentTeams:f.enableAgentTeams}:{}}}}function AZ(f,$){if($.disabledToolIds?.has(f))return!1;let{flags:J}=PZ($);if(f==="spawn_agent")return J.enableSpawnAgent===!0;if(f==="teams")return J.enableAgentTeams===!0;if(f==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let W=kK[f];return W?J[W]===!0:!1}function mK(f,$){if(f.id==="editor"){let{flags:J}=PZ($),W=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...f,defaultEnabled:AZ(f.id,$),headlessToolNames:[W?"apply_patch":"editor"]}}return{...f,defaultEnabled:AZ(f.id,$)}}function w$(f={}){return SK.map(($)=>mK($,f))}function M6(f={}){return w$(f).filter(($)=>$.defaultEnabled).map(($)=>$.id)}function L6(f){if(!f.enabled)return new Set;let $=w$(f.availabilityContext),J=new Set($.map((W)=>W.id));if(!f.allowlist||f.allowlist.length===0)return new Set($.filter((W)=>W.defaultEnabled).map((W)=>W.id));for(let W of f.allowlist)if(!J.has(W))throw Error(`Unknown tool "${W}". Available tools: ${$.map((H)=>H.id).join(", ")}`);return new Set(f.allowlist)}function X8(f,$={}){return w$($).filter((J)=>f.has(J.id)).flatMap((J)=>J.headlessToolNames)}function h6(f,$={}){return X8(f,$)}function b$(f={}){let{executorOptions:$={},executors:J,...W}=f,H={...U1($),...J??{}};return i0({...W,executors:H})}import{mkdirSync as dK,writeFileSync as rK}from"node:fs";import{dirname as lK}from"node:path";import{normalizeUserInput as pK}from"@cline/shared";import{nanoid as iK}from"nanoid";var YZ={};N(YZ,{sanitizeSessionToken:()=>C$,parseTeamTaskSubSessionId:()=>z1,parseSubSessionId:()=>P8,makeTeamTaskSubSessionId:()=>A8,makeSubSessionId:()=>O1,deriveSubsessionStatus:()=>B8});import{nanoid as vK}from"nanoid";function C$(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function O1(f,$){let J=C$(f),W=C$($),H=`${J}__${W}`;return H.length>180?H.slice(0,180):H}function A8(f,$){let J=C$(f),W=C$($);return`${J}__teamtask__${W}__${vK(6)}`}function z1(f){let J=f.indexOf("__teamtask__");if(J<=0)return null;let W=f.slice(0,J),H=f.slice(J+12),Q=H.lastIndexOf("__");if(Q<=0)return null;let Z=H.slice(0,Q),j=H.slice(Q+2);if(!W||!Z||!j)return null;return{rootSessionId:W,agentId:Z,teamTaskId:j}}function P8(f){if(z1(f))return null;let $="__",J=f.indexOf($);if(J<=0)return null;let W=f.slice(0,J),H=f.slice(J+$.length);if(!W||!H)return null;return{rootSessionId:W,agentId:H}}function B8(f){switch(f.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let $=String(f.reason??"").toLowerCase();if($.includes("cancel")||$.includes("abort")||$.includes("interrupt"))return"cancelled";if($.includes("fail")||$.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as t}from"zod";var VZ={};N(VZ,{SessionSource:()=>Ff,SESSION_STATUSES:()=>Y8});import{SESSION_STATUS_VALUES as uK}from"@cline/shared";var Y8=uK,Ff={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 cK=t.enum(Y8),Lf=t.object({version:t.literal(1),session_id:t.string().min(1),source:t.string().min(1),pid:t.number().int(),started_at:t.string().min(1),ended_at:t.string().min(1).optional(),exit_code:t.number().int().nullable().optional(),status:cK,interactive:t.boolean(),provider:t.string().min(1),model:t.string().min(1),cwd:t.string().min(1),workspace_root:t.string().min(1),team_name:t.string().min(1).optional(),enable_tools:t.boolean(),enable_spawn:t.boolean(),enable_teams:t.boolean(),prompt:t.string().optional(),metadata:t.record(t.string(),t.unknown()).optional(),messages_path:t.string().min(1).optional()});function RZ(f){if(!f)return!1;return Object.values(f).some(($)=>typeof $==="function")}function MW(f,$){let J=[...f??[],...$??[]];if(J.length===0)return;let W=[],H=new Set;for(let Q of J){if(H.has(Q.name))continue;H.add(Q.name),W.push(Q)}return W}function FZ(f){return JSON.stringify(f,($,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function h0(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function _W(f,$){let J={...f};J.id=h0(J.id)??iK();let W=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,H={id:h0(W?.id)??h0(J.modelId)??h0($?.id),provider:h0(W?.provider)??h0(J.providerId)??h0($?.provider),family:h0(W?.family)??h0($?.family)};if(delete J.providerId,delete J.modelId,H.id&&H.provider)J.modelInfo={id:H.id,provider:H.provider,...H.family?{family:H.family}:{}};else delete J.modelInfo;return J}function O6(f){return f.map(($)=>_W($))}function z6(f,$,J=[]){let W=f.map((j,X)=>{let A=J[X],B=A?.role===j.role&&JSON.stringify(A.content)===JSON.stringify(j.content)?{...A,...j}:{...j};return _W(B)}),H=J.length,Q=[];for(let j=H;j<W.length;j+=1)if(W[j]?.role==="assistant")Q.push(j);if(Q.length===0){let j=[...W].reverse().findIndex((X)=>X.role==="assistant");if(j===-1)return W;Q.push(W.length-1-j)}let Z=Q[Q.length-1];for(let j of Q){let X=W[j],A=X.metrics;if(!A&&j===Z){let P=$.usage;A={inputTokens:P.inputTokens,outputTokens:P.outputTokens,cacheReadTokens:P.cacheReadTokens??0,cacheWriteTokens:P.cacheWriteTokens??0,cost:P.totalCost}}W[j]={..._W(X,{id:$.model.id,provider:$.model.provider,family:$.model.info?.family}),...A?{metrics:A}:{},ts:X.ts??$.endedAt.getTime()}}return W}function V8(f){return{sessionId:f.sessionId,source:f.source,pid:f.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??void 0,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:f.parentSessionId??void 0,parentAgentId:f.parentAgentId??void 0,agentId:f.agentId??void 0,conversationId:f.conversationId??void 0,isSubagent:f.isSubagent,prompt:f.prompt??void 0,metadata:f.metadata??void 0,messagesPath:f.messagesPath??void 0,updatedAt:f.updatedAt}}var nK=120;function E$(f){let $=f?.trim();return $?$.slice(0,nK):void 0}function LW(f){let $=pK(f??"").trim();if(!$)return;return E$($.split(`
409
+ `)[0]?.trim())}function s0(f){if(!f)return;let $={...f},J=E$(typeof $.title==="string"?$.title:void 0);if(J)$.title=J;else delete $.title;return Object.keys($).length>0?$:void 0}function R8(f){let $=s0(f.metadata)??{},J=f.title!==void 0?E$(f.title):LW(f.prompt);if(J)$.title=J;return Object.keys($).length>0?$:void 0}function hW(f){let $=z1(f);if($)return{agent:"teammate",sessionId:$.rootSessionId,taskType:"team"};let J=P8(f);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:f}}function OW(f){return{version:1,updated_at:f.updatedAt,agent:f.context.agent,sessionId:f.context.sessionId,...f.context.taskType?{taskType:f.context.taskType}:{},messages:O6(f.messages),...f.systemPrompt?{system_prompt:f.systemPrompt}:{}}}function KZ(f,$,J){dK(lK(f),{recursive:!0}),rK(f,`${JSON.stringify(OW({updatedAt:$,context:J,messages:[]}),null,2)}
410
+ `,"utf8")}function yZ(f,$){return Lf.parse({version:1,session_id:f.sessionId,source:f.source,pid:f.pid,started_at:f.startedAt,ended_at:$?.endedAt??f.endedAt??void 0,exit_code:$?.exitCode??f.exitCode??void 0,status:$?.status??f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName??void 0,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt??void 0,metadata:$?.metadata??f.metadata??void 0,messages_path:f.messagesPath??void 0})}async function UZ(f,$,J){let W=0;while(!0){let H=await f();if(H===void 0)return{updated:!1};let Q=await $(H);if(typeof Q==="object"&&Q!==null&&"updated"in Q&&Q.updated===!1){if(W+=1,W>=J)return Q;continue}return Q}}_f();var GZ={};N(GZ,{summarizeUsageFromMessages:()=>q1,sumUsageTotals:()=>F8,getCurrentContextSize:()=>zW,createInitialAccumulatedUsage:()=>Pf,accumulateUsageTotals:()=>Xf});function Pf(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function Xf(f,$){return{inputTokens:f.inputTokens+Math.max(0,$.inputTokens??0),outputTokens:f.outputTokens+Math.max(0,$.outputTokens??0),cacheReadTokens:f.cacheReadTokens+Math.max(0,$.cacheReadTokens??0),cacheWriteTokens:f.cacheWriteTokens+Math.max(0,$.cacheWriteTokens??0),totalCost:f.totalCost+Math.max(0,$.totalCost??0)}}function F8(f){let $=Pf();for(let J of f)$=Xf($,J);return $}function N1(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function q1(f){let $=Pf();for(let J of f){let W=J.metrics;if(!W)continue;$=Xf($,{inputTokens:N1(W.inputTokens),outputTokens:N1(W.outputTokens),cacheReadTokens:N1(W.cacheReadTokens),cacheWriteTokens:N1(W.cacheWriteTokens),totalCost:N1(W.cost)})}return $}function zW(f){for(let $=f.length-1;$>=0;$-=1){let J=f[$];if(J?.role!=="assistant")continue;let W=N1(J.metrics?.inputTokens);return W>0?W:void 0}return}function aK(f){if(!f||typeof f!=="object")return;let $=f,J=$.skill??$.skill_name??$.skillName;if(typeof J!=="string")return;let W=J.trim();return W.length>0?W:void 0}function NW(f){if(!f||typeof f!=="object")return{};let $=f;return{agentId:typeof $.agentId==="string"?$.agentId:void 0,conversationId:typeof $.conversationId==="string"?$.conversationId:void 0,parentAgentId:typeof $.parentAgentId==="string"?$.parentAgentId:void 0}}function O0(f){let $=f.agentId?.trim();if(!$)return;let J=f.parentAgentId?.trim()||void 0,W=f.teamRole,H="root";if(W==="teammate")H="team_teammate";else if(W==="lead")H="team_lead";else if(J)H="subagent";return{agentId:$,agentKind:H,conversationId:f.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:f.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:f.teamId?.trim()||void 0,teamName:f.teamName?.trim()||void 0,teamRole:W,teamAgentId:f.teamAgentId?.trim()||void 0}}function tK(f){return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost}}function sK(f){let $=f.isPrimaryAgentEvent?[f.overrides?.agentId,f.eventMetadata.agentId,f.overrides?.teamAgentId]:[f.overrides?.teamAgentId,f.overrides?.agentId,f.eventMetadata.agentId,f.eventMetadata.conversationId];for(let J of $){let W=J?.trim();if(W)return W}return f.isPrimaryAgentEvent?"root":"unknown"}function qW(f,$,J){let{sessionId:W,config:H,liveSession:Q,emit:Z}=f,j=H.telemetry,X=Q?.runtime.teamRuntime,A=J?.isPrimaryAgentEvent??!0,P=NW($),B=O0({agentId:J?.agentId??P.agentId,conversationId:J?.conversationId??P.conversationId,parentAgentId:J?.parentAgentId??P.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??X?.getTeamId(),teamName:J?.teamName??X?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if($.type==="content_start"&&$.contentType==="tool"&&$.toolName==="skills"){let Y=aK($.input);if(Y)p4(j,{ulid:W,skillName:Y,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:H.providerId,modelId:H.modelId,...B})}if($.type==="content_end"&&$.contentType==="tool"){let Y=$.toolName??"unknown",V=!$.error;if(l4(j,{ulid:W,tool:Y,autoApproved:void 0,success:V,modelId:H.modelId,provider:H.providerId,...B}),!V&&(Y==="editor"||Y==="apply_patch"))i4(j,{ulid:W,modelId:H.modelId,provider:H.providerId,errorType:$.error,...B})}if($.type==="notice"&&$.reason==="api_error")z2(j,{ulid:W,model:H.modelId,provider:H.providerId,errorMessage:$.message,...B});if($.type==="error")z2(j,{ulid:W,model:H.modelId,provider:H.providerId,errorMessage:$.error?.message??"unknown error",...B});if($.type==="usage"&&Q?.turnUsageBaseline){let Y=tK($);if(A){Q.turnPrimaryUsage=Xf(Q.turnPrimaryUsage??Pf(),Y);let R=Xf(Q.turnUsageBaseline,Q.turnPrimaryUsage);f.usageBySession.set(W,R),X1(j,{ulid:W,provider:H.providerId,model:H.modelId,source:"assistant",mode:H.mode,...B}),d4(j,{ulid:W,tokensIn:$.inputTokens,tokensOut:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost,model:H.modelId,...B})}else{let R=sK({isPrimaryAgentEvent:A,overrides:J,eventMetadata:P}),U=Q.turnUsageByAgent??new Map;Q.turnUsageByAgent=U,U.set(R,Xf(U.get(R)??Pf(),Y))}let V=Xf(Q.turnPrimaryUsage??Pf(),F8(Q.turnUsageByAgent?.values()??[]));f.aggregateUsageBySession.set(W,Xf(Q.turnAggregateUsageBaseline??Q.turnUsageBaseline,V))}if($.type==="iteration_end"&&A)f.persistMessages(W,Q?.agent.getMessages()??[],Q?.config.systemPrompt);Z({type:"agent_event",payload:{sessionId:W,event:$,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(A?"lead":void 0):void 0}}),Z({type:"chunk",payload:{sessionId:W,stream:"agent",chunk:FZ($),ts:Date.now()}})}function o0(f){return f.workspaceRoot??f.cwd}import{hasRuntimeConfigExtension as XG}from"@cline/shared";function TZ(f){let $="";for(let J=0;J<f.length;J+=1)$+=String.fromCharCode(f[J]??0);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function oK(f){let J=new TextEncoder().encode(f),W=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(W)}function eK(f=32){let $=new Uint8Array(f);return crypto.getRandomValues($),TZ($)}async function N6(){let f=eK(),$=TZ(await oK(f));return{verifier:f,challenge:$}}function q6(f){return f.endsWith("/")?f.slice(0,-1):f}function S$(f,$){return new URL($,`${q6(f)}/`).toString()}function w1(f,$={}){let J=f.trim();if(!J)return{};try{let W=new URL(J);return{code:W.searchParams.get("code")??void 0,state:W.searchParams.get("state")??void 0,provider:$.includeProvider?W.searchParams.get("provider")??void 0:void 0}}catch{}if($.allowHashCodeState&&J.includes("#")){let[W,H]=J.split("#",2);return{code:W||void 0,state:H||void 0}}if(J.includes("code=")){let W=new URLSearchParams(J);return{code:W.get("code")??void 0,state:W.get("state")??void 0,provider:$.includeProvider?W.get("provider")??void 0:void 0}}return{code:J}}function fy(f){if(typeof atob==="function")try{return atob(f)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from(f,"base64").toString("utf8")}catch{return null}return null}function Kf(f){if(!f)return null;try{let $=f.split(".");if($.length!==3)return null;let J=$[1];if(!J)return null;let W=J.replace(/-/g,"+").replace(/_/g,"/"),H=W.padEnd(W.length+(4-W.length%4)%4,"="),Q=fy(H);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function b1(f){try{let $=JSON.parse(f),J=$.error,W=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,H=typeof $.error_description==="string"?$.error_description:typeof $.message==="string"?$.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:W,message:H}}catch{return{}}}function k$(f,$){return Date.now()>=f.expires-$}async function C1(f){if(!f.onManualCodeInput){let Q=await f.waitForCallback();return{code:Q?.code,state:Q?.state,provider:Q?.provider,error:Q?.error}}let $,J,W=f.onManualCodeInput().then((Q)=>{$=Q,f.cancelWait()}).catch((Q)=>{J=Q instanceof Error?Q:Error(String(Q)),f.cancelWait()}),H=await f.waitForCallback();if(J)throw J;if(H?.code||H?.error)return{code:H.code,state:H.state,provider:H.provider,error:H.error};if($)return w1($,f.parseOptions);if(await W,J)throw J;if($)return w1($,f.parseOptions);return{}}G0();import{existsSync as Iy}from"node:fs";import{discoverPluginModulePaths as my,resolveConfiguredPluginModulePaths as xy,resolvePluginConfigSearchPaths as gy}from"@cline/shared/storage";import{resolve as Ky}from"node:path";import{normalizePluginManifest as yy}from"@cline/shared";import{existsSync as Tf,readFileSync as S1}from"node:fs";import{builtinModules as $y,createRequire as _Z}from"node:module";import{dirname as y8,extname as EW,isAbsolute as Jy,resolve as d}from"node:path";import{fileURLToPath as MZ}from"node:url";import{PLUGIN_FILE_EXTENSIONS as Wy}from"@cline/shared";var LZ=y8(MZ(import.meta.url)),Hy=_Z(import.meta.url),Qy=d(LZ,"..","..","..","..",".."),wW=Xy(Qy),Zy=["@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"],SW=new Set($y.flatMap((f)=>[f,f.replace(/^node:/,"")])),K8=new Set(Wy),jy=["development","node","import","require","default"];function Xy(f){let $={},J={"@cline/agents":d(f,"packages/agents/src/index.ts"),"@cline/core":d(f,"packages/core/src/index.ts"),"@cline/llms":d(f,"packages/llms/src/index.ts"),"@cline/shared":d(f,"packages/shared/src/index.ts"),"@cline/shared/storage":d(f,"packages/shared/src/storage/index.ts"),"@cline/shared/db":d(f,"packages/shared/src/db/index.ts")};for(let[W,H]of Object.entries(J))if(Tf(H))$[W]=H;for(let W of["agents","core","llms","shared"]){let H=d(f,"packages",W),Q=d(H,"package.json");if(!Tf(Q))continue;try{let Z=JSON.parse(S1(Q,"utf8"));if(typeof Z.name!=="string"||!Z.exports)continue;if(typeof Z.exports==="string"){let j=d(H,Z.exports);if(Tf(j))$[Z.name]=j;continue}if(typeof Z.exports!=="object")continue;for(let[j,X]of Object.entries(Z.exports)){let A=Ay(H,X);if(!A)continue;let P=j==="."?Z.name:`${Z.name}/${j.replace(/^\.\//,"")}`;$[P]=A}}catch{}}return $}function Ay(f,$){let J=kW($);if(!J)return null;let W=hZ(f,J);for(let H of W)if(Tf(H))return H;return null}function kW(f,$=new Set){if(typeof f==="string")return f;if(!f||typeof f!=="object")return null;if($.has(f))return null;$.add(f);let J=f;for(let W of jy){let H=kW(J[W],$);if(H)return H}return null}function hZ(f,$){let J=$.replace(/^\.\//,""),W=[d(f,$)];if(J.startsWith("dist/")){let H=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[d(f,`${H}.ts`),d(f,`${H}.tsx`),d(f,`${H}.mts`),d(f,`${H}.cts`),...W]}return W}function Py(f){return Object.fromEntries(Object.entries(f).sort(([$],[J])=>J.length-$.length))}function w6(f){return!(f.startsWith(".")||f.startsWith("/")||f.startsWith("file:")||f.startsWith("data:")||f.startsWith("http:")||f.startsWith("https:"))}function E1(f){if(f.startsWith("@")){let[$,J]=f.split("/",3);return J?`${$}/${J}`:f}return f.split("/",1)[0]??f}function By(f){let $=E1(f);if(f===$)return".";return`.${f.slice($.length)}`}function OZ(f){return E1(f).startsWith("@cline/")}function bW(f,$){let J=E1($),W=y8(f);while(!0){let H=d(W,"node_modules",J);if(Tf(H)||Tf(d(H,"package.json")))return!0;let Q=d(W,"..");if(Q===W)return!1;W=Q}}function DZ(f){return CW(f)!==null}function CW(f){try{return Hy.resolve(f)}catch{}return Yy(f)}function Yy(f){let $=E1(f),J=Vy($);if(!J)return null;let W=d(J,"package.json");try{let H=JSON.parse(S1(W,"utf8")),Q=By(f),Z=Q==="."&&typeof H.exports==="string"?H.exports:H.exports&&typeof H.exports==="object"&&Object.hasOwn(H.exports,Q)?H.exports[Q]:void 0,j=kW(Z)??(Q==="."&&typeof H.main==="string"?H.main:null);if(!j)return null;let X=d(J,j),A=[X,...hZ(J,j).filter((P)=>P!==X)];for(let P of A)if(Tf(P))return P;return null}catch{return null}}function Vy(f){let $=LZ;while(!0){let J=d($,"package.json");if(Tf(J))try{if(JSON.parse(S1(J,"utf8")).name===f)return $}catch{}let W=d($,"node_modules",f,"package.json");if(Tf(W))return y8(W);let H=d($,"..");if(H===$)return null;$=H}}function Ry(f){let J=y8(f);for(let W=0;W<4;W++){let H=d(J,"package.json");if(Tf(H))try{let Z=JSON.parse(S1(H,"utf8"));return Z!=null&&typeof Z==="object"&&"cline"in Z}catch{return!1}let Q=d(J,"..");if(Q===J)return!1;J=Q}return!1}function zZ(f,$){let J=$.startsWith("file:")?MZ($):Jy($)?$:d(y8(f),$);if(Tf(J)&&K8.has(EW(J)))return J;for(let W of K8){let H=`${J}${W}`;if(Tf(H))return H}for(let W of K8){let H=d(J,`index${W}`);if(Tf(H))return H}return null}function NZ(f){let $=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let W of J)for(let H of f.matchAll(W)){let Q=H[1];if(Q)$.add(Q)}return[...$]}function qZ(f,$,J=new Set){if(J.has(f)||!Tf(f))return;if(J.add(f),!K8.has(EW(f)))return;let W=S1(f,"utf8");for(let H of NZ(W)){if(H.startsWith("node:")||SW.has(H))continue;if(w6(H)){if(Object.hasOwn(wW,H)||Object.hasOwn(wW,E1(H))||bW(f,H)||OZ(H)&&DZ(H)||$&&DZ(H))continue;throw Error(`Cannot find module '${E1(H)}'`)}let Q=zZ(f,H);if(Q)qZ(Q,$,J)}}function wZ(f,$=new Set,J=new Set){if($.has(f)||!Tf(f))return J;if($.add(f),!K8.has(EW(f)))return J;let W=S1(f,"utf8");for(let H of NZ(W)){if(J.add(H),w6(H))continue;let Q=zZ(f,H);if(Q)wZ(Q,$,J)}return J}function Fy(f,$){let J=_Z(f),W={},H=wZ(f),Q=new Set(Zy);for(let[Z,j]of Object.entries(wW)){try{J.resolve(Z);continue}catch{}W[Z]=j}for(let Z of H)if(w6(Z)&&(OZ(Z)||$))Q.add(Z);for(let Z of Q){if(Object.hasOwn(W,Z)||bW(f,Z))continue;let j=CW(Z);if(j)W[Z]=j}if(!$)return W;for(let Z of H){if(!w6(Z)||Object.hasOwn(W,Z)||bW(f,Z)||Z.startsWith("node:")||SW.has(Z))continue;let j=CW(Z);if(j)W[Z]=j}return W}async function bZ(f,$={}){let J=!Ry(f);qZ(f,J);let W=Fy(f,J),H=Py(W),Q=await import("jiti"),Z=typeof Q==="function"?Q:typeof Q.default==="function"?Q.default:void 0;if(!Z)throw Error("Unable to load jiti");return await Z(f,{alias:H,cache:$.useCache,requireCache:$.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...SW],transformModules:Object.keys(H)}).import(f,{})}function CZ(f,$){if(!f)return!0;if(f.providerIds?.length){if(!$?.providerId||!f.providerIds.includes($.providerId))return!1}if(f.modelIds?.length){if(!$?.modelId||!f.modelIds.includes($.modelId))return!1}return!0}function EZ(f){return typeof f==="object"&&f!==null}function IW(f){return Array.isArray(f)&&f.every(($)=>typeof $==="string")}function Uy(f,$){if(!EZ(f.manifest))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);if(!IW(f.manifest.capabilities))throw Error(`Invalid plugin module at ${$}: manifest.capabilities must be a string array`);if(f.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${$}: manifest.capabilities cannot be empty`);if(Object.hasOwn(f.manifest,"providerIds")&&!IW(f.manifest.providerIds))throw Error(`Invalid plugin module at ${$}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn(f.manifest,"modelIds")&&!IW(f.manifest.modelIds))throw Error(`Invalid plugin module at ${$}: manifest.modelIds must be a string array when provided`)}function Gy(f,$){if(!EZ(f))throw Error(`Invalid plugin module at ${$}: expected object export`);if(typeof f.name!=="string"||f.name.length===0)throw Error(`Invalid plugin module at ${$}: expected non-empty "name"`);if(!Object.hasOwn(f,"manifest"))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);Uy(f,$)}async function U8(f,$={}){let J=Ky($.cwd??process.cwd(),f),W=await bZ(J,{useCache:$.useCache}),H=$.exportName??"plugin",Q=W.default??W[H];Gy(Q,J);let Z=Q,j=Z.setup,X=j?(A,P)=>{let B={...$.session,...P.session},Y={...P,session:Object.keys(B).length>0?B:void 0,client:$.client??P.client,user:$.user??P.user,workspaceInfo:$.workspaceInfo??P.workspaceInfo,automation:$.automation??P.automation,logger:$.logger??P.logger,telemetry:$.telemetry??P.telemetry};return j(A,Y)}:void 0;return{...Z,manifest:yy(Z.manifest),setup:X}}async function b6(f,$={}){return(await z0(f,$)).plugins}async function z0(f,$={}){let J=[],W=[],H=new Map,Q=0;for(let Z of f)try{let j=await U8(Z,$);if(!CZ(j.manifest,$))continue;let X=H.get(j.name);if(X)W.push({type:"duplicate_plugin_override",pluginName:j.name,pluginPath:Z,overriddenPluginPath:X.pluginPath,message:`Plugin "${j.name}" from ${Z} overrides ${X.pluginPath}`});H.set(j.name,{plugin:j,pluginPath:Z,order:Q++})}catch(j){let X=j instanceof Error?j.message:String(j);J.push({pluginPath:Z,phase:"load",message:X,stack:j instanceof Error?j.stack:void 0})}return{plugins:[...H.values()].sort((Z,j)=>Z.order-j.order).map((Z)=>Z.plugin),failures:J,warnings:W}}import{existsSync as Ly}from"node:fs";import{createRequire as hy}from"node:module";import{dirname as Oy,join as C6}from"node:path";import{fileURLToPath as zy}from"node:url";var xZ={};N(xZ,{resolveSubprocessRuntimeExecutable:()=>mW,buildSubprocessSandboxCommand:()=>mZ,SubprocessSandbox:()=>k1,CLINE_JS_RUNTIME_PATH_ENV:()=>IZ});import{spawn as Ty}from"node:child_process";import{basename as Dy}from"node:path";import{augmentNodeCommandForDebug as _y,withResolvedClineBuildEnv as My}from"@cline/shared";function SZ(f){if(f instanceof Error)return f;return Error(String(f))}var IZ="CLINE_JS_RUNTIME_PATH";function kZ(f){let $=f?.trim();if(!$)return!1;let J=Dy($).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function mW(f={}){let $=f.env??process.env,J=f.runtimeExecutable?.trim()||$[IZ]?.trim();if(J)return J;let W=f.execPath?.trim()||process.execPath;if(kZ(W))return W;for(let H of[$.BUN_EXEC_PATH,$.npm_node_execpath,$.NODE]){let Q=H?.trim();if(Q&&kZ(Q))return Q}return"node"}function mZ(f,$={}){let J=mW({env:$.env,execPath:$.execPath,runtimeExecutable:$.runtimeExecutable});return _y([J,...f],{env:$.env,execArgv:$.execArgv,debugRole:$.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class k1{options;process=null;requestCounter=0;pending=new Map;constructor(f){this.options=f}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest(f){let $=this.pending.get(f);if(!$)return;if(this.pending.delete(f),$.timeout)clearTimeout($.timeout);return $}start(){if(this.process&&this.process.exitCode===null)return;let f=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],$=mZ(f,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=Ty($[0]??mW(this.options),$.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:My(process.env)});this.process=J;let W="",H=(Q)=>{let Z=W+Q;W=Z.length>4000?Z.slice(-4000):Z};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(Q)=>{H(Q)}),J.on("message",(Q)=>{this.onMessage(Q)}),J.on("error",(Q)=>{this.failPending(Error(`${this.processLabel} process error: ${SZ(Q).message}`))}),J.on("exit",(Q,Z)=>{this.process=null;let j=W.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Q)}, signal=${String(Z)})${j?`: ${j}`:""}`))})}async call(f,$,J={}){this.start();let W=this.process;if(!W||W.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let H=`req_${++this.requestCounter}`,Q={type:"call",id:H,method:f,args:$};return await new Promise((Z,j)=>{let X={resolve:(A)=>Z(A),reject:j};if((J.timeoutMs??0)>0)X.timeout=setTimeout(()=>{this.clearPendingRequest(H),this.shutdown().catch(()=>{}),j(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${f}`))},J.timeoutMs);this.pending.set(H,X),W.send(Q,(A)=>{if(!A)return;let P=this.clearPendingRequest(H);if(!P)return;P.reject(Error(`${this.processLabel} failed to send call "${f}": ${SZ(A).message}`))})})}async shutdown(){let f=this.process;if(this.process=null,!f||f.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise(($)=>{let J=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}$()},300);f.once("exit",()=>{clearTimeout(J),$()});try{f.kill("SIGTERM")}catch{clearTimeout(J),$()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage(f){if(!f)return;if(f.type==="event"){if(typeof f.name==="string"&&f.name.length>0)this.options.onEvent?.({name:f.name,payload:f.payload});return}if(f.type!=="response"||!f.id)return;let $=this.clearPendingRequest(f.id);if(!$)return;if(f.ok){$.resolve(f.result);return}$.reject(Error(f.error?.message||`${this.processLabel} call failed`))}failPending(f){for(let[$,J]of this.pending.entries()){if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);J.reject(f)}}}function Ny(f){return{...f,contributions:{tools:f.contributions?.tools??[],commands:f.contributions?.commands??[],messageBuilders:f.contributions?.messageBuilders??[],providers:f.contributions?.providers??[],automationEventTypes:f.contributions?.automationEventTypes??[],shortcuts:f.contributions?.shortcuts??[],flags:f.contributions?.flags??[]}}}function E6(f){return(f instanceof Error?f.message:String(f)).includes("Unknown sandbox plugin id:")}function qy(){let f=Oy(zy(import.meta.url)),$=hy(import.meta.url),J=[C6(f,"plugin-sandbox-bootstrap.js"),C6(f,"extensions","plugin-sandbox-bootstrap.js"),C6(f,"agents","plugin-sandbox-bootstrap.js")];for(let Q of J)if(Ly(Q))return{file:Q};let W=C6(f,"plugin-sandbox-bootstrap.ts"),H="jiti";try{H=$.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(H)});`,`const jiti = createJiti(${JSON.stringify(W)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(W)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
411
+ `)}}var xW=qy();function gW(f,$){return typeof f==="number"&&f>0?f:$}async function vZ(f){let $=new k1({name:"plugin-sandbox",..."file"in xW?{bootstrapFile:xW.file}:{bootstrapScript:xW.script},onEvent:f.onEvent}),J=gW(f.importTimeoutMs,4000),W=gW(f.hookTimeoutMs,3000),H=gW(f.contributionTimeoutMs,60000),Q={pluginPaths:f.pluginPaths,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,loggerEnabled:Boolean(f.logger)},Z,j=()=>{return Z??=$.call("initialize",Q,{timeoutMs:J}).finally(()=>{Z=void 0}),Z},X;try{X=await $.call("initialize",Q,{timeoutMs:J})}catch(B){throw await $.shutdown().catch(()=>{}),B}return{extensions:X.plugins.map(Ny).map((B)=>{let Y={name:B.name,manifest:B.manifest,setup:(V)=>{wy(V,$,B,H,j),by(V,$,B,H,j),Ey(V,$,B,H,j),Cy(V,B)}};return Y.hooks=ky($,B,W,j),Y}),failures:X.failures,shutdown:async()=>{await $.shutdown()},warnings:X.warnings}}function wy(f,$,J,W,H){for(let Q of J.contributions?.tools??[]){let Z={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema??{type:"object",properties:{}},timeoutMs:Q.timeoutMs,retryable:Q.retryable,execute:async(j,X)=>{try{return await $.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:j,context:X},{timeoutMs:W})}catch(A){if(!E6(A))throw A;return await H(),await $.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:j,context:X},{timeoutMs:W})}}};f.registerTool(Z)}}function by(f,$,J,W,H){for(let Q of J.contributions?.commands??[])f.registerCommand({name:Q.name,description:Q.description,handler:async(Z)=>{try{return await $.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:Z},{timeoutMs:W})}catch(j){if(!E6(j))throw j;return await H(),await $.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:Z},{timeoutMs:W})}}})}function Cy(f,$){for(let J of $.contributions?.providers??[])f.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of $.contributions?.automationEventTypes??[])f.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function Ey(f,$,J,W,H){for(let Q of J.contributions?.messageBuilders??[])f.registerMessageBuilder({name:Q.name,async build(Z){try{let j=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:Z},{timeoutMs:W});return gZ(j)?j:Z}catch(j){if(!E6(j))throw j;await H();let X=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:Z},{timeoutMs:W});return gZ(X)?X:Z}}})}function gZ(f){return Array.isArray(f)&&f.every(($)=>typeof $==="object"&&$!==null&&("role"in $)&&("content"in $))}function Sy(f,$,J,W,H){return async(Q)=>{try{return await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:W})}catch(Z){if(!E6(Z))throw Z;return await H(),await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:W})}}}function ky(f,$,J,W){let H={};for(let Q of $.hooks??[])H[Q]=Sy(f,$.pluginId,Q,J,W);return Object.keys(H).length>0?H:void 0}function G8(f){return gy(f)}function T8(f){return my(f)}function I$(f={}){let $=f.cwd??process.cwd(),J=G8(f.workspacePath).flatMap((Z)=>T8(Z)).filter((Z)=>Iy(Z)),W=xy(f.pluginPaths??[],$),H=[],Q=new Set;for(let Z of[...W,...J]){if(Q.has(Z))continue;Q.add(Z),H.push(Z)}return $6(H)}async function I1(f={}){let $=I$(f);if($.length===0)return{extensions:[],failures:[],warnings:[]};if(f.mode==="in_process"){let W=await z0($,{cwd:f.cwd,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,automation:f.automation,logger:f.logger,telemetry:f.telemetry});return{extensions:W.plugins,failures:W.failures,warnings:W.warnings}}let J=await vZ({pluginPaths:$,exportName:f.exportName,importTimeoutMs:f.importTimeoutMs,hookTimeoutMs:f.hookTimeoutMs,contributionTimeoutMs:f.contributionTimeoutMs,onEvent:f.onEvent,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,logger:f.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,warnings:J.warnings}}import{execFile as vy}from"node:child_process";import{promisify as uy}from"node:util";var cy=uy(vy);function vW(f,$){f?.log($,{severity:"warn"})}function dy(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!J.latest||!Array.isArray(J.history))return;let W=J.latest,H=J.history.filter((Q)=>!!Q&&typeof Q==="object"&&typeof Q.ref==="string"&&typeof Q.createdAt==="number"&&typeof Q.runCount==="number");if(typeof W.ref!=="string"||typeof W.createdAt!=="number"||typeof W.runCount!=="number")return;return{latest:W,history:H}}async function m$(f,$){let J=await cy("git",["-C",f,...$],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function uW(f,$){if(!f)return;let J=`refs/cline/checkpoints/${$}/`;try{let{stdout:W}=await m$(f,["for-each-ref","--format=%(refname)",J]),H=W.trim().split(`
412
+ `).filter(Boolean);await Promise.allSettled(H.map((Q)=>m$(f,["update-ref","-d",Q])))}catch{}}async function uZ(f,$,J){if(!f||J.length===0)return;await Promise.allSettled(J.map((W)=>m$(f,["update-ref",`refs/cline/checkpoints/${$}/${W.runCount}`,W.ref])))}function ry(f,$){let J=f.findIndex((W)=>W.runCount===$.runCount);if(J<0)return[...f,$];return f.map((W,H)=>H===J?$:W)}function cZ(f){let $=f.initialRunCount??0,J,W=async()=>{if(J!==void 0)return J;try{J=(await m$(f.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},H=async()=>{if(f.createCheckpoint)return await f.createCheckpoint({cwd:f.cwd,sessionId:f.sessionId,runCount:$});if(!await W())return;let Q=async(A)=>{try{let B=(await m$(f.cwd,["rev-parse","HEAD"])).stdout.trim();if(!B)return;return{ref:B,createdAt:Date.now(),runCount:$,kind:"commit"}}catch(P){vW(f.logger,`${A}: ${P instanceof Error?P.message:String(P)}`);return}},Z=`cline checkpoint session=${f.sessionId} run=${$}`,j="";try{j=(await m$(f.cwd,["stash","create",Z])).stdout.trim()}catch(A){return vW(f.logger,`Checkpoint snapshot failed: ${A instanceof Error?A.message:String(A)}`),Q("Checkpoint HEAD fallback failed")}if(!j)return Q("Checkpoint HEAD fallback failed");let X=`refs/cline/checkpoints/${f.sessionId}/${$}`;try{await m$(f.cwd,["update-ref",X,j])}catch(A){vW(f.logger,`Checkpoint store failed: ${A instanceof Error?A.message:String(A)}`);return}return{ref:j,createdAt:Date.now(),runCount:$,kind:"stash"}};return{beforeRun:async({snapshot:Q})=>{if(Q.parentAgentId!=null)return;$+=1;return},beforeModel:async({snapshot:Q})=>{if(Q.parentAgentId!=null||Q.iteration!==1||$<1)return;let Z=await H();if(!Z)return;let j=await f.readSessionMetadata(),X=dy(j);if(X?.latest.ref===Z.ref)return;let A=ry(X?.history??[],Z);await f.writeSessionMetadata({...j??{},checkpoint:{latest:Z,history:A}});return}}}import{spawn as ey}from"node:child_process";import{appendFileSync as fU,readFileSync as $U}from"node:fs";import{join as JU}from"node:path";import{augmentNodeCommandForDebug as lZ,withResolvedClineBuildEnv as rW}from"@cline/shared";import{ensureHookLogDir as dZ}from"@cline/shared/storage";function m1(f,$){if(!$)return;return{name:f,manifest:{capabilities:["hooks"]},hooks:$}}import{existsSync as ly,readdirSync as py}from"node:fs";import{basename as iy,extname as ny,join as ay}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as S6,resolveHooksConfigSearchPaths as ty}from"@cline/shared/storage";function D8(f){return ty(f)}var x1;((P)=>{P.TaskStart="TaskStart";P.TaskResume="TaskResume";P.TaskCancel="TaskCancel";P.TaskComplete="TaskComplete";P.TaskError="TaskError";P.PreToolUse="PreToolUse";P.PostToolUse="PostToolUse";P.UserPromptSubmit="UserPromptSubmit";P.PreCompact="PreCompact";P.SessionShutdown="SessionShutdown"})(x1||={});var _8={["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"},sy=new Map(Object.values(x1).map((f)=>[f.toLowerCase(),f])),oy=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function M8(f){let $=ny(f).toLowerCase();if(!oy.has($))return;let J=iy(f,$).trim().toLowerCase();return sy.get(J)}function e0(f){let $=[],J=new Set,W=D8(f).filter((H)=>ly(H));for(let H of W)try{for(let Q of py(H,{withFileTypes:!0})){if(!Q.isFile())continue;let Z=M8(Q.name);if(!Z)continue;let j=ay(H,Q.name);if(J.has(j))continue;J.add(j),$.push({fileName:Z,hookEventName:_8[Z],path:j})}}catch{}return $.sort((H,Q)=>H.path.localeCompare(Q.path))}function I6(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,W]of Object.entries(f))$[J]=typeof W==="string"?W:JSON.stringify(W);return $}function k6(f,$,J){let W=J instanceof Error?`: ${J.message}`:"",H=`${$}${W}`;if(f){try{f.log(H,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(H)}function WU(f,$){if(!$)return f;if(!f)return{...$};let J=[f.context,$.context].filter((H)=>typeof H==="string"&&H.length>0).join(`
413
+ `),W=[...f.appendMessages??[],...$.appendMessages??[]];return{cancel:f.cancel===!0||$.cancel===!0?!0:void 0,review:f.review===!0||$.review===!0?!0:void 0,context:J||void 0,overrideInput:$.overrideInput!==void 0?$.overrideInput:f.overrideInput,systemPrompt:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,appendMessages:W.length>0?W:void 0}}function HU(f){if(!f||typeof f!=="object")return;let $=f,J=typeof $.context==="string"?$.context:typeof $.contextModification==="string"?$.contextModification:typeof $.errorMessage==="string"?$.errorMessage:void 0;return{cancel:typeof $.cancel==="boolean"?$.cancel:void 0,review:typeof $.review==="boolean"?$.review:void 0,context:J,overrideInput:Object.hasOwn($,"overrideInput")?$.overrideInput:void 0}}function cW(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function yf(f,$){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",W={rootSessionId:$.rootSessionId||f.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:W,workspaceRoots:$.workspacePath?[$.workspacePath]:[],workspaceInfo:$.workspaceInfo,userId:J,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function QU(f){let $=f.trim();if(!$)return{};let W=$.split(`
414
+ `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),H=W.length>0?W[W.length-1]:$;try{return{parsedJson:JSON.parse(H)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse hook stdout JSON"}}}async function ZU(f,$){let J=f.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((W,H)=>{let Q=!1,Z=()=>{J.off("error",X),J.off("finish",A),f.off("close",P)},j=(B)=>{if(Q)return;if(Q=!0,Z(),B){let Y=B.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){W();return}H(B);return}W()},X=(B)=>j(B),A=()=>j(),P=()=>j();J.on("error",X),J.once("finish",A),f.once("close",P);try{J.end($)}catch(B){j(B)}})}async function pZ(f,$){if($.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await rZ(f,$)}catch(J){let W=AU($.command,process.platform,J);if(!W)throw J;return await rZ(f,{...$,command:W})}}async function rZ(f,$){let J=lZ($.command,{env:$.env,debugRole:"hook"}),W=ey(J[0],J.slice(1),{cwd:$.cwd,env:rW($.env),stdio:$.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:$.detached}),H=new Promise((Y)=>{W.once("spawn",()=>Y())}),Q=new Promise((Y,V)=>{W.once("error",(R)=>V(R))}),Z=JSON.stringify(f);if(await Promise.race([H,Q]),await ZU(W,Z),$.detached){W.unref();return}if(!W.stdout||!W.stderr)throw Error("hook command failed to create stdout/stderr");let j="",X="",A=!1,P;W.stdout.on("data",(Y)=>{j+=Y.toString()}),W.stderr.on("data",(Y)=>{X+=Y.toString()});let B=new Promise((Y)=>{if(($.timeoutMs??0)>0)P=setTimeout(()=>{A=!0,W.kill("SIGKILL")},$.timeoutMs);W.once("close",(V)=>{if(P)clearTimeout(P);let{parsedJson:R,parseError:U}=QU(j);Y({exitCode:V,stdout:j,stderr:X,parsedJson:R,parseError:U,timedOut:A})})});return await Promise.race([B,Q])}function jU(f){try{let J=$U(f,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let W=J.slice(2).trim();if(!W)return;let H=W.split(/\s+/).filter(Boolean);return H.length>0?H:void 0}catch{return}}function XU(f){return!!(f&&typeof f==="object"&&("code"in f)&&f.code==="ENOENT")}function AU(f,$=process.platform,J){if($!=="win32"||!XU(J))return;if(f[0]!=="py"||f[1]!=="-3")return;return["python",...f.slice(2)]}function iZ(f){if(f.length===0)return;let[$,...J]=f,W=$.replace(/\\/g,"/").toLowerCase(),H=W.split("/").at(-1)??W;if(H==="env")return iZ(J);if(H==="bash"||H==="sh"||H==="zsh")return[H,...J];if(H==="python3"||H==="python")return process.platform==="win32"?["py","-3",...J]:[H,...J];return f}function PU(f){let $=jU(f);if($&&$.length>0)return[...iZ($)??$,f];let J=f.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",f];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return lZ(["node",f],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",f];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",f]:["python3",f];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",f];return["bash",f]}function BU(f){let $={};for(let J of e0(f)){if(!J.hookEventName)continue;let W=J.hookEventName,H=$[W]??[];H.push(PU(J.path)),$[W]=H}return $}async function YU(f){let $;for(let J of f.commands){let W=J.join(" ");try{let H=await pZ(f.payload,{command:J,cwd:f.cwd,env:rW(process.env),detached:!1,timeoutMs:f.timeoutMs});if(H?.timedOut){k6(f.logger,`hook command timed out: ${W}`);continue}if(H?.parseError){k6(f.logger,`hook command returned invalid JSON control output: ${W} (${H.parseError})`);continue}$=WU($,HU(H?.parsedJson))}catch(H){k6(f.logger,`hook command failed: ${W}`,H)}}return $}function x$(f){for(let $ of f.commands){let J=$.join(" ");pZ(f.payload,{command:$,cwd:f.cwd,env:rW(process.env),detached:!0}).catch((W)=>{k6(f.logger,`hook command failed: ${J}`,W)})}}function f$(f){return{agentId:f.agentId,conversationId:f.conversationId??f.runId??f.agentId,parentAgentId:f.parentAgentId??null}}function dW(f,$){return{...f$(f.snapshot),userMessage:$}}function nZ(f){return{...f$(f.snapshot),iteration:f.snapshot.iteration,call:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input}}}function aZ(f){return{...f$(f.snapshot),iteration:f.snapshot.iteration,record:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}}function tZ(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function VU(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}function g1(f){let $={cwd:f.workspacePath,workspacePath:f.workspacePath,rootSessionId:f.rootSessionId,workspaceInfo:f.workspaceInfo},J=(W)=>{let H=`${JSON.stringify({ts:new Date().toISOString(),...W})}
415
+ `,Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??JU(dZ(),"hooks.jsonl");dZ(Z),fU(Z,H,"utf8")};return{beforeRun:async(W)=>{let H=dW(W,"");J({...yf(H,$),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(W)=>{let H=nZ(W);J({...yf(H,$),hookName:"tool_call",iteration:H.iteration,tool_call:{id:H.call.id,name:H.call.name,input:H.call.input},preToolUse:{toolName:H.call.name,parameters:I6(H.call.input)}});return},afterTool:async(W)=>{let H=aZ(W);J({...yf(H,$),hookName:"tool_result",iteration:H.iteration,tool_result:H.record,postToolUse:{toolName:H.record.name,parameters:I6(H.record.input),result:typeof H.record.output==="string"?H.record.output:JSON.stringify(H.record.output),success:!H.record.error,executionTimeMs:H.record.durationMs}});return},afterRun:async({snapshot:W,result:H})=>{let Q=f$(W);if(H.status==="completed"){J({...yf(Q,$),hookName:"agent_end",iteration:H.iterations,turn:{outputText:H.outputText,status:H.status},taskComplete:{taskMetadata:{}}});return}if(H.status==="aborted"||cW(H.error?.message)){J({...yf(Q,$),hookName:"agent_abort",reason:H.error?.message,taskCancel:{taskMetadata:{}}});return}if(H.error)J({...yf(Q,$),hookName:"agent_error",iteration:H.iterations,error:{name:H.error.name,message:H.error.message,stack:H.error.stack}})},onEvent:async(W)=>{if(W.type!=="message-added"||W.message.role!=="user")return;let H=dW({snapshot:W.snapshot},tZ(W.message.content));J({...yf(H,$),hookName:"prompt_submit",userPromptSubmit:{prompt:H.userMessage,attachments:[]}})}}}function L8(f){let $=BU(f.workspacePath);if(!Object.values($).some((B)=>B.length>0))return;let W=async(B,Y)=>{let V=$[Y]??[];if(V.length===0)return;x$({commands:V,cwd:f.cwd,logger:f.logger,payload:Y==="agent_resume"?{...yf(B,f),hookName:Y,taskResume:{taskMetadata:{},previousState:{}}}:{...yf(B,f),hookName:Y,taskStart:{taskMetadata:{}}}})},H=async(B)=>{let Y=$.prompt_submit??[];if(Y.length>0)x$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...yf(B,f),hookName:"prompt_submit",userPromptSubmit:{prompt:B.userMessage,attachments:[]}}})},Q=async(B)=>{let Y=$.tool_call??[];if(Y.length===0)return;return YU({commands:Y,cwd:f.cwd,logger:f.logger,timeoutMs:f.toolCallTimeoutMs??120000,payload:{...yf(B,f),hookName:"tool_call",iteration:B.iteration,tool_call:{id:B.call.id,name:B.call.name,input:B.call.input},preToolUse:{toolName:B.call.name,parameters:I6(B.call.input)}}})},Z=async(B)=>{let Y=$.tool_result??[];if(Y.length===0)return;x$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...yf(B,f),hookName:"tool_result",iteration:B.iteration,tool_result:B.record,postToolUse:{toolName:B.record.name,parameters:I6(B.record.input),result:typeof B.record.output==="string"?B.record.output:JSON.stringify(B.record.output),success:!B.record.error,executionTimeMs:B.record.durationMs}}})},j=async(B)=>{let Y=$.agent_end??[];if(Y.length===0)return;x$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...yf(B,f),hookName:"agent_end",iteration:B.iteration,turn:B.turn,taskComplete:{taskMetadata:{}}}})},X=async(B)=>{let Y=$.agent_error??[];if(Y.length===0)return;x$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...yf(B,f),hookName:"agent_error",iteration:B.iteration,error:{name:B.error.name,message:B.error.message,stack:B.error.stack}}})},A=async(B)=>{if(cW(B.reason)){let V=$.agent_abort??[];if(V.length>0)x$({commands:V,cwd:f.cwd,logger:f.logger,payload:{...yf(B,f),hookName:"agent_abort",reason:B.reason,taskCancel:{taskMetadata:{}}}})}let Y=$.session_shutdown??[];if(Y.length===0)return;x$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...yf(B,f),hookName:"session_shutdown",reason:B.reason}})},P={};if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0||($.prompt_submit?.length??0)>0){if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0)P.beforeRun=async(B)=>{let Y=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await W(f$(B.snapshot),Y);return};if(($.prompt_submit?.length??0)>0)P.onEvent=async(B)=>{if(B.type!=="message-added"||B.message.role!=="user")return;await H(dW({snapshot:B.snapshot},tZ(B.message.content)))}}if(($.tool_call?.length??0)>0)P.beforeTool=async(B)=>{let Y=await Q(nZ(B));return VU(Y)};if(($.tool_result?.length??0)>0)P.afterTool=async(B)=>{await Z(aZ(B));return};if(($.agent_end?.length??0)>0)P.afterRun=async({snapshot:B,result:Y})=>{if(Y.status!=="completed")return;await j({...f$(B),iteration:Y.iterations,turn:{outputText:Y.outputText,status:Y.status}})};if(($.agent_error?.length??0)>0||($.agent_abort?.length??0)>0||($.session_shutdown?.length??0)>0){let B=P.afterRun;P.afterRun=async(Y)=>{await B?.(Y);let{snapshot:V,result:R}=Y;if(R.status==="aborted"||cW(R.error?.message)){await A({...f$(V),reason:R.error?.message});return}if(R.error)await X({...f$(V),iteration:R.iterations,error:R.error})}}return P}function v1(f){return m1("core.hook_config_files",L8(f))}function g$(f,$){let J=f.map((W)=>W[$]).filter((W)=>typeof W==="function");if(J.length===0)return;return async(W)=>{let H;for(let Q of J){let Z=await Q(W);if(!Z||typeof Z!=="object")continue;let j=Z;H={...H??{},...j,stop:H?.stop===!0||j.stop===!0?!0:j.stop,options:H?.options||j.options?{...H?.options??{},...j.options??{}}:void 0}}return H}}function v$(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return;return{beforeRun:g$($,"beforeRun"),afterRun:g$($,"afterRun"),beforeModel:g$($,"beforeModel"),afterModel:g$($,"afterModel"),beforeTool:g$($,"beforeTool"),afterTool:g$($,"afterTool"),onEvent:g$($,"onEvent")}}var sZ={};N(sZ,{normalizeRuntimeCapabilities:()=>Uf});function Uf(...f){let $,J;for(let H of f){if(!H)continue;if(H.toolExecutors)$={...$??{},...H.toolExecutors};if(H.requestToolApproval)J=H.requestToolApproval}let W=$&&Object.keys($).length>0;if(!W&&!J)return;return{...W?{toolExecutors:$}:{},...J?{requestToolApproval:J}:{}}}var Dj={};N(Dj,{toProviderConfig:()=>mf,emptyStoredProviderSettings:()=>H$,StoredProviderSettingsSchema:()=>r1,StoredProviderSettingsEntrySchema:()=>ZJ,ProviderSettingsSchemaTyped:()=>S8});import{z as W$}from"zod";var Tj={};N(Tj,{toProviderConfig:()=>mf,safeParseSettings:()=>QJ,safeCreateProviderConfig:()=>jH,parseSettings:()=>HJ,normalizeProviderId:()=>d1,isBuiltInProviderId:()=>QH,createProviderConfig:()=>ZH,SapSettingsSchema:()=>$J,ReasoningSettingsSchema:()=>s6,ProviderSettingsSchema:()=>J$,ProviderProtocolSchema:()=>n6,ProviderIdSchema:()=>E8,ProviderClientSchema:()=>a6,OcaSettingsSchema:()=>JJ,ModelCatalogSettingsSchema:()=>WJ,GcpSettingsSchema:()=>e6,BUILT_IN_PROVIDER_IDS:()=>HH,BUILT_IN_PROVIDER:()=>C8,AzureSettingsSchema:()=>fJ,AwsSettingsSchema:()=>o6,AuthSettingsSchema:()=>t6});import*as If from"@cline/llms";import{z as h}from"zod";_f();var Vj={};N(Vj,{refreshOcaToken:()=>O8,loginOcaOAuth:()=>u1,getValidOcaCredentials:()=>z8,generateOcaOpcRequestId:()=>v6,createOcaRequestHeaders:()=>nW,createOcaOAuthProvider:()=>iW,OCI_HEADER_OPC_REQUEST_ID:()=>Zj,DEFAULT_INTERNAL_OCA_BASE_URL:()=>m6,DEFAULT_INTERNAL_IDCS_URL:()=>$j,DEFAULT_INTERNAL_IDCS_SCOPES:()=>Jj,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>fj,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>x6,DEFAULT_EXTERNAL_IDCS_URL:()=>Hj,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>Qj,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>Wj});import{nanoid as eZ}from"nanoid";class lW{ttlMs;maxEntries;entries=new Map;constructor(f,$){this.ttlMs=f;this.maxEntries=$}get(f,$=Date.now()){this.pruneExpired($);let J=this.entries.get(f);if(!J)return;return this.entries.delete(f),this.entries.set(f,J),J.value}set(f,$,J=Date.now(),W=this.ttlMs){this.pruneExpired(J),this.entries.delete(f);while(this.entries.size>=this.maxEntries){let H=this.entries.keys().next().value;if(H===void 0)break;this.entries.delete(H)}this.entries.set(f,{value:$,expiresAt:J+W})}pruneExpired(f){for(let[$,J]of this.entries)if(J.expiresAt<=f)this.entries.delete($)}}var oZ={};N(oZ,{startLocalOAuthServer:()=>N0});function RU(){let f;return{promise:new Promise((J)=>{f=J}),resolve:f}}async function N0(f){let $=await import("node:http"),J=f.host??"127.0.0.1",W=f.timeoutMs??300000,H=f.successHtml??FU,Q=RU(),Z=!1,j=null,X=null,A=null,P=(V)=>{if(Z)return;Z=!0,Q.resolve(V)},B=()=>{if(j)clearTimeout(j),j=null;let V=A;if(A=null,X)X.close(),X=null;if(V!==null&&f.onClose)Promise.resolve(f.onClose({host:J,port:V})).catch(()=>{})},Y=async()=>{return j=setTimeout(()=>{B(),P(null)},W),Q.promise};for(let V of f.ports){let R=$.createServer((K,F)=>{try{let y=new URL(K.url||"",`http://${J}:${V}`);if(y.pathname!==f.callbackPath){F.statusCode=404,F.end("Not found");return}let D={url:y,code:y.searchParams.get("code")??void 0,state:y.searchParams.get("state")??void 0,provider:y.searchParams.get("provider")??void 0,error:y.searchParams.get("error")??void 0};if(D.error){F.statusCode=400,F.end(`Authentication failed: ${D.error}`),B(),P(D);return}if(!D.code){F.statusCode=400,F.end("Missing authorization code");return}if(f.expectedState&&D.state!==f.expectedState){F.statusCode=400,F.end("State mismatch");return}F.statusCode=200,F.setHeader("Content-Type","text/html; charset=utf-8"),F.end(H),B(),P(D)}catch{F.statusCode=500,F.end("Internal error")}}),U=await new Promise((K)=>{let F=(y)=>{R.off("error",F),K({bound:!1,error:y})};R.once("error",F),R.listen(V,J,()=>{R.off("error",F),X=R,K({bound:!0})})});if(U.error){if(U.error.code==="EADDRINUSE")continue;throw B(),U.error}if(U.bound){A=V;let K=`http://${J}:${V}${f.callbackPath}`;if(f.onListening)await Promise.resolve(f.onListening({host:J,port:V,callbackUrl:K})).catch(()=>{});return{callbackUrl:K,waitForCallback:Y,cancelWait:()=>{B(),P(null)},close:()=>{B(),P(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var FU=`<!DOCTYPE html>
416
416
  <html lang="en">
417
417
  <head>
418
418
  <meta charset="utf-8">
@@ -453,54 +453,54 @@ ${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function OQ(f,$){l
453
453
  </div>
454
454
  <script>setTimeout(() => window.close(), 3000);</script>
455
455
  </body>
456
- </html>`;var E6="a8331954c0cf48ba99b5dd223a14c6ea",S6="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",k6="openid offline_access",m1="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",m6="c1aba3deed5740659981a752714eba33",I6="https://login-ext.identity.oraclecloud.com",x6="openid offline_access",I1="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",g6="opc-request-id",cK="/auth/oca",dK=Array.from({length:11},(f,$)=>48801+$),rK=300000,lK=30000,gZ=30000,pK=600000;class v6 extends Error{status;errorCode;constructor(f,$){super(f);this.name="OcaOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var o0={internal:{clientId:E6,idcsUrl:S6,scopes:k6,baseUrl:m1},external:{clientId:m6,idcsUrl:I6,scopes:x6,baseUrl:I1}},T8=new Map,iK=86400000,nK=300000,aK=32,cW=new uW(iK,aK);function vZ(f){if(typeof f==="function")return f();return f??"internal"}function uZ(f){return{internal:{clientId:f?.internal?.clientId??o0.internal.clientId,idcsUrl:f?.internal?.idcsUrl??o0.internal.idcsUrl,scopes:f?.internal?.scopes??o0.internal.scopes,baseUrl:f?.internal?.baseUrl??o0.internal.baseUrl},external:{clientId:f?.external?.clientId??o0.external.clientId,idcsUrl:f?.external?.idcsUrl??o0.external.idcsUrl,scopes:f?.external?.scopes??o0.external.scopes,baseUrl:f?.external?.baseUrl??o0.external.baseUrl}}}function tK(f=Date.now()){let $=f-pK;for(let[J,H]of T8.entries())if(H.createdAt<$)T8.delete(J)}function sK(f,$,J){if(typeof f.expires_in==="number"&&f.expires_in>0)return Date.now()+f.expires_in*1000;let W=Ff($)?.exp;if(typeof W==="number"&&W>0)return W*1000;let Z=Ff(J)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return Date.now()+3600000}function cZ(f,$,J){let H=f.access_token;if(!H)throw Error("Token response did not include an access token");let W=f.refresh_token??J?.refresh;if(!W)throw Error("Token response did not include a refresh token");let Q=Ff(f.id_token),Z=Ff(H),j=Q?.sub??Z?.sub,P=Q?.email??Z?.email;return{access:H,refresh:W,expires:sK(f,H,f.id_token),accountId:j??J?.accountId,email:P??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:$,subject:j,idToken:f.id_token}}}async function dZ(f,$){let J=_6(f),H=cW.get(J);if(H)return H;let W=`${J}/.well-known/openid-configuration`,Q=await fetch(W,{method:"GET",signal:AbortSignal.timeout($)});if(!Q.ok){let P=`${J}/oauth2/v1/token`;return cW.set(J,P,Date.now(),nK),P}let j=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return cW.set(J,j),j}function rZ(f){return{code:f.error,message:f.error_description}}async function oK(f){let $=T8.get(f.state);if(!$)throw Error("No PKCE verifier found for this state");T8.delete(f.state);let J=f.mode==="external"?f.config.external:f.config.internal,H=await dZ(J.idcsUrl,f.requestTimeoutMs),W=new URLSearchParams({grant_type:"authorization_code",code:f.code,redirect_uri:$.redirectUri,client_id:J.clientId,code_verifier:$.verifier}),Q=await fetch(H,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:W,signal:AbortSignal.timeout(f.requestTimeoutMs)}),Z=await Q.json();if(!Q.ok){let P=rZ(Z);throw new v6(`Token exchange failed: ${Q.status}${P.message?` - ${P.message}`:""}`,{status:Q.status,errorCode:P.code})}let j=Ff(Z.id_token);if(!Z.id_token||!j)throw Error("No ID token received from OCA");if(j.nonce!==$.nonce)throw Error("OIDC nonce verification failed");return cZ(Z,f.mode)}function eK(f){let $=f.mode==="external"?f.config.external:f.config.internal,J=new URL(`${_6($.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",$.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",$.scopes),J.searchParams.set("code_challenge",f.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",f.callbackUrl),J.searchParams.set("state",f.state),J.searchParams.set("nonce",f.nonce),J.toString()}async function x1(f){Y0(f.telemetry,"oca");let $=uZ(f.config),J=vZ(f.mode),H=f.callbackPorts?.length?f.callbackPorts:dK,W=f.callbackPath??cK,Q=f.requestTimeoutMs??gZ,Z=await M0({ports:H,callbackPath:W,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),j=Z.callbackUrl;if(!j)throw Error("Unable to bind local OAuth callback server");let P=xZ(16),X=xZ(16),{verifier:V,challenge:Y}=await M6();tK(),T8.set(P,{verifier:V,nonce:X,mode:J,redirectUri:j,createdAt:Date.now()});let B=eK({callbackUrl:j,mode:J,state:P,nonce:X,challenge:Y,config:$});f.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let A=await q1({waitForCallback:Z.waitForCallback,cancelWait:Z.cancelWait,onManualCodeInput:f.callbacks.onManualCodeInput}),R=A.code,U=A.state;if(A.error)throw Error(`OAuth error: ${A.error}`);if(!R){if(!f.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!U||U!==P)throw Error("State mismatch");let y=await oK({code:R,state:U,mode:J,config:$,requestTimeoutMs:Q});return B0(f.telemetry,"oca"),R0(f.telemetry,{id:y.accountId,email:y.email,provider:"oca"}),y}catch(A){throw A0(f.telemetry,"oca",A instanceof Error?A.message:String(A)),A}finally{Z.close()}}async function D8(f,$={}){let J=uZ($.config),H=$.requestTimeoutMs??gZ,W=f.metadata?.mode,Q=W==="internal"||W==="external"?W:vZ($.mode),Z=Q==="external"?J.external:J.internal,j=await dZ(Z.idcsUrl,H),P=new URLSearchParams({grant_type:"refresh_token",refresh_token:f.refresh,client_id:Z.clientId}),X=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:P,signal:AbortSignal.timeout(H)}),V=await X.json();if(!X.ok){let Y=rZ(V);throw new v6(`Token refresh failed: ${X.status}${Y.message?` - ${Y.message}`:""}`,{status:X.status,errorCode:Y.code})}return cZ(V,Q,f)}async function M8(f,$,J){if(!f)return null;let H=$?.refreshBufferMs??J?.refreshBufferMs??rK,W=$?.retryableTokenGraceMs??J?.retryableTokenGraceMs??lK;if($?.forceRefresh!==!0&&!C$(f,H))return f;try{return await D8(f,J)}catch(Z){if(Z instanceof v6&&Z.isLikelyInvalidGrant())return C0(J?.telemetry,"oca","invalid_grant"),null;if(f.expires-Date.now()>W)return f;return null}}function dW(f={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login($){return x1({...f,callbacks:$})},async refreshToken($){return D8($,f)},getApiKey($){return $.access}}}async function u6(f,$){let J=new TextEncoder,H=async(X)=>{let V=await crypto.subtle.digest("SHA-256",J.encode(X));return Array.from(new Uint8Array(V).slice(0,4),(Y)=>Y.toString(16).padStart(2,"0")).join("")},[W,Q]=await Promise.all([H($),H(f)]),Z=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),j=new Uint32Array(1);crypto.getRandomValues(j);let P=(j[0]??0).toString(16).padStart(8,"0");return W+Q+Z+P}async function rW(f){let $=await u6(f.taskId,f.accessToken);return{Authorization:`Bearer ${f.accessToken}`,"Content-Type":"application/json",client:f.metadata?.client??"Cline","client-version":f.metadata?.clientVersion??"unknown","client-ide":f.metadata?.clientIde??"unknown","client-ide-version":f.metadata?.clientIdeVersion??"unknown",[g6]:$}}var sZ={};N(sZ,{resolveProviderConfig:()=>z8,getProviderConfig:()=>a6,getLiveModelsCatalog:()=>g1,clearPublicModelsCatalogCache:()=>GU,clearPrivateModelsCatalogCache:()=>eW,clearLiveModelsCatalogCache:()=>oW,OPENAI_COMPATIBLE_PROVIDERS:()=>L8,DEFAULT_MODELS_CATALOG_URL:()=>i6});import*as Af from"@cline/llms";function lW(f){if(!Array.isArray(f))return[];return f.map(($)=>{if(typeof $==="string")return $.trim();if($&&typeof $==="object"){let J=$;for(let H of[J.id,J.name,J.model])if(typeof H==="string"&&H.trim())return H.trim()}return""}).filter(($)=>$.length>0)}function fU(f,$){let J=lW(f);if(J.length>0)return J;if(!f||typeof f!=="object")return[];let H=f,W=lW(H.data??H.models);if(W.length>0)return W;if(H.models&&typeof H.models==="object"&&!Array.isArray(H.models)){let Z=Object.keys(H.models).filter((j)=>j.trim().length>0);if(Z.length>0)return Z}let Q=H.providers?.[$];if(Q&&typeof Q==="object"){let j=lW(Q.models??Q);if(j.length>0)return j}return[]}async function c6(f,$){let J=await fetch(f,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${f}: HTTP ${J.status}`);return fU(await J.json(),$)}function pZ(f){return f.replace(/\/+$/,"")}function d6(f,$,J){let H=J?.trim();if(!H)return;let W=f?.trim();if(!W||!$?.trim())return H;try{let Q=new URL(H),Z=new URL($),j=new URL(W);if(Q.origin!==Z.origin)return H;let P=pZ(Z.pathname),X=pZ(j.pathname);if(P&&Q.pathname.startsWith(`${P}/`)){let V=Q.pathname.slice(P.length);j.pathname=`${X}${V}`}else j.pathname=Q.pathname;return j.search=Q.search,j.hash=Q.hash,j.toString()}catch{return H}}function $U(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{...J}]))}function JU(f){if(f.baseUrl.length===0)return!1;switch(f.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return f.protocol==="openai-chat"}}var HU=Object.values(Af.MODEL_COLLECTIONS_BY_PROVIDER_ID).map((f)=>({id:f.provider.id,baseUrl:f.provider.baseUrl??"",modelsSourceUrl:f.provider.modelsSourceUrl,modelId:f.provider.defaultModelId,knownModels:$U(f.models),capabilities:f.provider.capabilities?[...f.provider.capabilities]:void 0,env:f.provider.env?[...f.provider.env]:void 0,client:f.provider.client,protocol:f.provider.protocol})),iZ=Object.fromEntries(HU.map((f)=>[f.id,f]));function WU(f){return iZ[f]}function QU(){return Object.fromEntries(Object.entries(iZ).filter(([,f])=>JU(f)))}function nZ(f=[]){let $=f.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return $.length>0?$:void 0}var i6="https://models.dev/api.json",ZU=600000,aZ=300000,jU=5000,p6=new Map,_8=new Map,iW=new Map,r6=new Map;async function PU(){return Af.getGeneratedProviderModels()}async function XU(f,$={},J={},H={},W={},Q={}){let Z=await PU(),j=Af.resolveProviderModelCatalogKeys(f),P=Object.assign({},...j.map((Y)=>Z[Y]??{})),X=Boolean(Af.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl),V=Object.keys(W).length>0;if(X&&V)return Af.sortModelsByReleaseDate({...W,...Q});return Af.sortModelsByReleaseDate({...P,...$,...J,...H,...W,...Q})}function VU(f,$){let J=Af.resolveProviderModelCatalogKeys(f);return Object.assign({},...J.map((H)=>$[H]??{}))}function aW(f){let $=f?.trim();return $&&$.length>0?$:""}function tW(f){let $=f.apiKey?.trim()||f.accessToken?.trim();return $&&$.length>0?$:void 0}function YU(f){let $=2166136261;for(let J=0;J<f.length;J+=1)$^=f.charCodeAt(J),$+=($<<1)+($<<4)+($<<7)+($<<8)+($<<24);return($>>>0).toString(16)}function BU(f,$){return`${f}:${aW($.baseUrl)}:${YU(tW($)??"")}`}async function sW(f,$,J=jU){let H=new AbortController,W=setTimeout(()=>H.abort(),J);try{return await fetch(f,{...$,signal:H.signal})}finally{clearTimeout(W)}}function pW(f,$,J){if(J&&!f.includes($))f.push($)}function n6(f,$){let J=["streaming","tools"];return pW(J,"images",Boolean($.supportsImages)),pW(J,"prompt-cache",Boolean($.supportsPromptCache)),pW(J,"reasoning",Boolean($.supportsReasoning)),{id:f,name:$.name??f,contextWindow:$.contextWindow,maxTokens:$.maxTokens,capabilities:J,releaseDate:$.releaseDate,status:"active"}}async function AU(f,$){let J=await sW("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let W=(await J.json())?.data??[],Q={};for(let Z of W){let j=Z.id?.trim();if(!j)continue;if(j.includes("whisper")||j.includes("tts")||j.includes("embedding"))continue;let P=Z.supported_features??[];Q[j]=n6(j,{name:j,contextWindow:Z.context_length,maxTokens:Z.max_completion_tokens,supportsReasoning:P.includes("reasoning")||P.includes("reasoning_effort"),supportsImages:!1})}return Q}async function RU(f,$){let J=await sW("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":$}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let W=(await J.json())?.data??[],Q={};for(let Z of W){let j=Z.id?.trim();if(!j)continue;Q[j]=n6(j,{name:j,contextWindow:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}function FU(f){let $=aW(f);if(!$)return"http://localhost:4000";return $.endsWith("/v1")?$.slice(0,-3):$}async function yU(f,$){let H=`${FU(f.baseUrl)}/v1/model/info`,W=async(X)=>sW(H,{method:"GET",headers:{accept:"application/json",...X}}),Q=await W({"x-litellm-api-key":$});if(!Q.ok)Q=await W({Authorization:`Bearer ${$}`});if(!Q.ok)throw Error(`LiteLLM model refresh failed: HTTP ${Q.status}`);let j=(await Q.json())?.data??[],P={};for(let X of j){let V=X.model_name?.trim(),B=X.litellm_params?.model?.trim()||V;if(!B)continue;let A=X.model_info,R=n6(B,{name:V??B,maxTokens:A?.max_output_tokens??A?.max_tokens,contextWindow:A?.max_input_tokens??A?.max_tokens,supportsImages:A?.supports_vision,supportsPromptCache:A?.supports_prompt_caching,supportsReasoning:A?.supports_reasoning});if(P[B]=R,V)P[V]={...R,id:V,name:V}}return P}var tZ={baseten:AU,hicap:RU,litellm:yU},nW=new Map,l6=new Map;function KU(f,$){return`${f}:${aW($.baseUrl)}`}async function UU(f,$,J){let H=Af.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],W=d6(J.baseUrl,H?.provider.baseUrl,H?.provider.modelsSourceUrl);if(!W)return{};let Q=$?.cacheTtlMs??aZ,Z=KU(f,J),j=Date.now(),P=nW.get(Z);if(P&&P.expiresAt>j)return P.data;let X=l6.get(Z);if(X)return X;let V=c6(W,f).then((Y)=>{let B=Object.fromEntries(Y.map((A)=>[A,n6(A,{name:A})]));return nW.set(Z,{data:B,expiresAt:j+Q}),B}).finally(()=>{l6.delete(Z)});return l6.set(Z,V),V}function GU(){nW.clear(),l6.clear()}async function hU(f,$){let J=tW($);if(!J)return{};let H=tZ[f];if(!H)return{};return H($,J)}function TU(f,$,J){if(!J)return!1;if(!tZ[f])return!1;if($?.loadPrivateOnAuth===!1)return!1;return Boolean(tW(J))}async function DU(f,$,J){let H=$?.cacheTtlMs??aZ,W=BU(f,J),Q=Date.now(),Z=iW.get(W);if(Z&&Z.expiresAt>Q)return Z.data;let j=r6.get(W);if(j)return j;let P=hU(f,J).then((X)=>{return iW.set(W,{data:X,expiresAt:Q+H}),X}).finally(()=>{r6.delete(W)});return r6.set(W,P),P}async function MU(f){return Af.fetchModelsDevProviderModels(f)}async function g1(f={}){let $=f.url??i6,J=f.cacheTtlMs??ZU,H=Date.now(),W=p6.get($);if(W&&W.expiresAt>H)return W.data;let Q=_8.get($);if(Q)return Q;let Z=MU($).then((j)=>{return p6.set($,{data:j,expiresAt:H+J}),j}).finally(()=>{_8.delete($)});return _8.set($,Z),Z}function oW(f){if(f){p6.delete(f),_8.delete(f);return}p6.clear(),_8.clear()}function eW(){iW.clear(),r6.clear()}function _U(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:nZ(J.capabilities)}]))}var L8=_U(QU());function a6(f){let $=WU(f);if(!$||!$.baseUrl)return;return{baseUrl:$.baseUrl,modelId:$.modelId,knownModels:$.knownModels,capabilities:nZ($.capabilities)}}async function z8(f,$,J){let H=a6(f);if(!H)return;try{let W=$?.loadLatestOnInit?await g1($):void 0,Q=W?VU(f,W):{},Z=J&&TU(f,$,J)?await DU(f,$,J):{},P=Boolean(Af.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl)?J??{providerId:f,modelId:H.modelId,baseUrl:H.baseUrl}:J,X=P?await UU(f,$,P).catch(()=>({})):{},V=await XU(f,H.knownModels,Q,Z,X,J?.knownModels);return{...H,knownModels:V}}catch(W){if($?.failOnError)throw W;return H}}var O8=wf.BUILT_IN_PROVIDER,f5=wf.BUILT_IN_PROVIDER_IDS,$5=wf.isBuiltInProviderId,v1=wf.normalizeProviderId,N8=_.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),t6=_.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),s6=_.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),o6=_.object({apiKey:_.string().optional(),accessToken:_.string().optional(),refreshToken:_.string().optional(),expiresAt:_.number().int().positive().optional(),accountId:_.string().optional()}),LU=_.enum(["none","low","medium","high","xhigh"]),e6=_.object({enabled:_.boolean().optional(),effort:LU.optional(),budgetTokens:_.number().int().positive().optional()}),fJ=_.object({accessKey:_.string().optional(),secretKey:_.string().optional(),sessionToken:_.string().optional(),region:_.string().optional(),profile:_.string().optional(),authentication:_.enum(["iam","api-key","profile"]).optional(),usePromptCache:_.boolean().optional(),useCrossRegionInference:_.boolean().optional(),useGlobalInference:_.boolean().optional(),endpoint:_.string().url().optional(),customModelBaseId:_.string().optional()}),$J=_.object({projectId:_.string().optional(),region:_.string().optional()}),JJ=_.object({apiVersion:_.string().optional(),useIdentity:_.boolean().optional()}),HJ=_.object({clientId:_.string().optional(),clientSecret:_.string().optional(),tokenUrl:_.string().url().optional(),resourceGroup:_.string().optional(),deploymentId:_.string().optional(),useOrchestrationMode:_.boolean().optional(),api:_.enum(["orchestration","foundation-models"]).optional(),defaultSettings:_.record(_.string(),_.unknown()).optional()}),WJ=_.object({mode:_.enum(["internal","external"]).optional(),usePromptCache:_.boolean().optional()}),QJ=_.object({loadLatestOnInit:_.boolean().optional(),loadPrivateOnAuth:_.boolean().optional(),url:_.string().url().optional(),cacheTtlMs:_.number().int().positive().optional(),failOnError:_.boolean().optional()}),e0=_.object({provider:N8,apiKey:_.string().optional(),auth:o6.optional(),model:_.string().optional(),protocol:t6.optional(),client:s6.optional(),routingProviderId:N8.optional(),maxTokens:_.number().int().positive().optional(),contextWindow:_.number().int().positive().optional(),baseUrl:_.string().url().optional(),headers:_.record(_.string(),_.string()).optional(),timeout:_.number().int().positive().optional(),reasoning:e6.optional(),aws:fJ.optional(),gcp:$J.optional(),azure:JJ.optional(),sap:HJ.optional(),oca:WJ.optional(),region:_.string().optional(),apiLine:_.enum(["china","international"]).optional(),capabilities:_.array(_.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth"])).optional(),modelCatalog:QJ.optional()});function ZJ(f){return e0.parse(f)}function jJ(f){return e0.safeParse(f)}function zU(f){return f.protocol==="openai-responses"||f.client==="openai"}function Cf(f,$={}){let J=f.provider,H=v1(J),W=$.includeKnownModels!==!1,Q=f.reasoning?.effort||"none",Z=Q==="none"?void 0:Q,j=L8[H],P=Object.assign({},...wf.resolveProviderModelCatalogKeys(H).map((U)=>wf.getGeneratedModelsForProvider(U))),X=Object.keys(P)[0],V=f.auth?.accessToken??f.apiKey??f.auth?.apiKey,Y=f.baseUrl??(H==="oca"?f.oca?.mode==="internal"?m1:I1:j?.baseUrl),B=f.routingProviderId??(zU(f)&&H!==O8.OPENAI_NATIVE?O8.OPENAI_NATIVE:void 0),A=W?j?.knownModels??(Object.keys(P).length>0?P:void 0):void 0,R={providerId:J,clientType:f.client,routingProviderId:B,modelId:f.model??j?.modelId??X??"default",...W?{knownModels:A}:{},apiKey:V,accessToken:f.auth?.accessToken,refreshToken:f.auth?.refreshToken,accountId:f.auth?.accountId,baseUrl:Y,headers:f.headers,timeoutMs:f.timeout,maxOutputTokens:f.maxTokens,maxContextTokens:f.contextWindow,thinking:f.reasoning?.enabled,reasoningEffort:Z,thinkingBudgetTokens:f.reasoning?.budgetTokens,region:f.region??f.aws?.region??f.gcp?.region,apiLine:f.apiLine,useCrossRegionInference:f.aws?.useCrossRegionInference,useGlobalInference:f.aws?.useGlobalInference,aws:f.aws?{accessKey:f.aws.accessKey,secretKey:f.aws.secretKey,sessionToken:f.aws.sessionToken,authentication:f.aws.authentication,profile:f.aws.profile,usePromptCache:f.aws.usePromptCache,endpoint:f.aws.endpoint,customModelBaseId:f.aws.customModelBaseId}:void 0,gcp:f.gcp?{projectId:f.gcp.projectId,region:f.gcp.region}:void 0,azure:f.azure,sap:f.sap,oca:f.oca,capabilities:f.capabilities??j?.capabilities,modelCatalog:f.modelCatalog?{loadLatestOnInit:f.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:f.modelCatalog.loadPrivateOnAuth,url:f.modelCatalog.url,cacheTtlMs:f.modelCatalog.cacheTtlMs,failOnError:f.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(R).filter(([U,y])=>y!==void 0))}function J5(f){let $=ZJ(f);return Cf($)}function H5(f){let $=jJ(f);if($.success)return{success:!0,config:Cf($.data)};return{success:!1,error:$.error}}var q8=e0;var PJ=f$.object({settings:e0,updatedAt:f$.string().datetime(),tokenSource:f$.enum(["manual","oauth","migration"]).default("manual")}),u1=f$.object({version:f$.literal(1),lastUsedProvider:f$.string().min(1).optional(),providers:f$.record(f$.string(),PJ)});function $$(){return{version:1,providers:{}}}F0();var fj={};N(fj,{InMemoryWorkspaceManager:()=>c1});import{upsertWorkspaceInfo as OU,WorkspaceManifestSchema as W5}from"@cline/shared";class c1{manifest;listeners=new Set;constructor(f){this.manifest=W5.parse(f??{workspaces:{}})}async addWorkspacePath(f){let $=await W1(f);return this.manifest=OU(this.manifest,$),this.emit({type:"workspace_added",workspace:$}),$}async switchWorkspace(f){let $=V0(f),J=this.manifest.workspaces[$];if(J)return this.manifest=W5.parse({...this.manifest,currentWorkspacePath:$}),this.emit({type:"workspace_switched",workspace:J}),J;let H=await this.addWorkspacePath($);return this.manifest=W5.parse({...this.manifest,currentWorkspacePath:H.rootPath}),this.emit({type:"workspace_switched",workspace:H}),H}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}getCurrentWorkspace(){let f=this.manifest.currentWorkspacePath;if(!f)return;return this.manifest.workspaces[f]}getWorkspace(f){let $=V0(f);return this.manifest.workspaces[$]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(f){for(let $ of this.listeners)$(f)}}Kf();import{createHash as NU}from"node:crypto";var $j=new Set,Jj=new Set;function qU(f){return NU("sha256").update(f).digest("hex")}function bU(f){if(f.vcsTypes&&f.vcsTypes.length>0)return f.vcsTypes;return[f.vcsType==="git"?"git":"none"]}function Hj(f){if(!f.telemetry)return;let $=qU(f.rootPath),J=f.rootCount??1;if(!$j.has($))$j.add($),E4(f.telemetry,{root_count:J,vcs_types:bU(f),init_duration_ms:f.durationMs,feature_flag_enabled:f.featureFlagEnabled??!0,is_remote_workspace:f.isRemoteWorkspace});if(f.initError&&!Jj.has($)){Jj.add($);let H=Error(f.initError.message);H.name=f.initError.errorType||"Error",S4(f.telemetry,H,{fallback_to_single_root:!0,workspace_count:J})}}function CU(f){return`${f.pluginName??f.pluginPath}: ${f.message}`}function EU(f,$,J){if($.length>0)for(let Q of $)J?.log(Q.message,{severity:"warn"});if(f.length===0)return;let H=f.slice(0,3).map(CU).join("; "),W=f.length>3?`; and ${f.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${H}${W}. Use --verbose for more details.`,{severity:"warn"});for(let Q of f)J?.log(`Plugin initialization failed (${Q.phase}) for ${Q.pluginPath}`,{severity:"warn",stack:Q.stack,pluginPath:Q.pluginPath,pluginName:Q.pluginName})}function SU(f,$){let J=typeof f.thinking==="boolean",H=typeof f.reasoningEffort==="string";if(!J&&!H)return $;return{...$??{},...J?{enabled:f.thinking}:{},...H?{effort:f.reasoningEffort}:{}}}function kU(f,$){return wU(f,$)}function mU(f){let $=0;for(let J of f??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;$+=1}return $}function IU(f){let $={...f.storedHeaders??{},...f.configHeaders??{}},J=f.accountId?.trim()||xU(f.accessToken);if($.originator="cline",$.session_id=f.sessionId,$["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)$["ChatGPT-Account-Id"]=J;return $}function xU(f){let $=f?.trim();if(!$)return;let J=Ff($),H=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof H==="string"&&H.length>0)return H;let W=J?.organizations?.[0]?.id;if(typeof W==="string"&&W.length>0)return W;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}function gU(f,$,J,H,W){let Q=J.getProviderSettings(f.providerId),Z=H||Q?.modelCatalog?{...H??{},...Q?.modelCatalog??{}}:void 0,j={...Q??{},provider:f.providerId,model:f.modelId,apiKey:f.apiKey??Q?.apiKey,baseUrl:f.baseUrl??Q?.baseUrl,headers:f.providerId==="openai-codex"?IU({sessionId:$,configHeaders:f.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:f.apiKey??Q?.auth?.accessToken??Q?.apiKey}):f.headers??Q?.headers,reasoning:SU(f,Q?.reasoning),modelCatalog:Z},P=Cf(j);if(f.knownModels)P.knownModels=f.knownModels;if(f.extensionContext)P.extensionContext=f.extensionContext;let V=f.fetch??P.fetch??W;if(V)P.fetch=V;return P}async function Wj(f){let{input:$,sessionId:J,providerSettingsManager:H,defaultTelemetry:W,defaultCapabilities:Q,defaultToolPolicies:Z,defaultFetch:j,onPluginEvent:P,onTeamEvent:X,createSpawnTool:V,localRuntime:Y,readSessionMetadata:B,writeSessionMetadata:A}=f,R=n0($.config),{modelCatalogDefaults:U,userInstructionService:y,configExtensions:F,onTeamRestored:K,...M}=Y??{},T=Object.keys(M).length>0?M:void 0,{workspaceInfo:G,workspaceMetadata:h,durationMs:z,vcsType:u,initError:gf}=await PH(R),a=T?.extensionContext,c={...a??{},workspace:{...G,...a?.workspace??{}},session:{...a?.session??{},sessionId:J},logger:a?.logger??T?.logger,telemetry:a?.telemetry??T?.telemetry??W};Hj({telemetry:c.telemetry,rootPath:G.rootPath,workspaceInfo:G,rootCount:1,vcsType:u,durationMs:z,initError:gf,featureFlagEnabled:!0});let d=k1({cwd:$.config.cwd,workspacePath:R,rootSessionId:J,logger:T?.logger,workspaceInfo:G}),t=$Z(T?.hooks)?void 0:S1({rootSessionId:J,workspacePath:R,workspaceInfo:G}),pf=I$([T?.hooks,t]),C;if(kU(F,"plugins"))try{C=await w1({pluginPaths:T?.pluginPaths,workspacePath:R,cwd:$.config.cwd,onEvent:P,providerId:$.config.providerId,modelId:$.config.modelId,workspaceInfo:G,session:c.session,client:c.client,user:c.user,logger:c.logger,telemetry:c.telemetry,automation:c.automation}),EU(C.failures,C.warnings,T?.logger)}catch(F2){let r=F2 instanceof Error?F2.message:String(F2);T?.logger?.log?.(`plugin loading failed; continuing without plugins (${r})`)}let vf=TW(d?[d]:void 0,TW(T?.extensions,t4(C?.extensions))),$f={...$.config,...T??{},sessionId:J,hooks:pf,extensions:vf,extensionContext:c,telemetry:c.telemetry},A2=gU($f,J,H,U,j),P$=I$([$f.hooks,$f.checkpoint?.enabled===!0?OZ({cwd:$f.cwd,sessionId:J,logger:$f.logger,createCheckpoint:$f.checkpoint?.createCheckpoint,initialRunCount:mU($.initialMessages),readSessionMetadata:B,writeSessionMetadata:A}):void 0]),X$={...$f,providerConfig:A2,workspaceMetadata:h,hooks:P$},o$=$.toolPolicies??$f.toolPolicies??Z,R2=Bf(Q,$.capabilities),z4=R2?.requestToolApproval,WH=R2?.toolExecutors,e$=new c1({currentWorkspacePath:G.rootPath,workspaces:{[G.rootPath]:G}});return{effectiveInput:$,config:X$,providerConfig:A2,workspaceMetadata:h,workspaceInfo:G,extensions:vf,hooks:P$,toolPolicies:o$,requestToolApproval:z4,pluginSandboxShutdown:C?.shutdown,runtimeBuilderInput:{config:X$,hooks:P$,extensions:vf,onTeamEvent:X,createSpawnTool:V,onTeamRestored:K,userInstructionService:y,configExtensions:F,toolExecutors:WH,workspaceManager:e$,logger:X$.logger,telemetry:X$.telemetry}}}import{existsSync as VJ,mkdirSync as vU,readdirSync as uU,rmdirSync as cU,rmSync as dU,unlinkSync as rU}from"node:fs";import{dirname as Qj,join as XJ}from"node:path";function s(){return new Date().toISOString()}function b8(f){if(!f||!VJ(f))return;try{rU(f)}catch{}}function lU(f){let $=L1(f);if($)return{rootSessionId:$.rootSessionId,fileStem:`${$.agentId}__${$.teamTaskId}`};let J=P8(f);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:f,fileStem:f}}class Q5{ensureSessionsDir;constructor(f){this.ensureSessionsDir=f}sessionArtifactsDir(f){return XJ(this.ensureSessionsDir(),f)}ensureSessionArtifactsDir(f){let $=this.sessionArtifactsDir(f);if(!VJ($))vU($,{recursive:!0});return $}sessionMessagesPath(f){return XJ(this.sessionArtifactsDir(f),`${f}.messages.json`)}sessionManifestPath(f,$=!1){let J=$?this.ensureSessionArtifactsDir(f):this.sessionArtifactsDir(f);return XJ(J,`${f}.json`)}removeSessionDirIfEmpty(f){let $=this.sessionArtifactsDir(f),J=this.ensureSessionsDir();while($.startsWith(J)&&$!==J){if(!VJ($)){$=Qj($);continue}try{if(uU($).length>0)break;cU($)}catch{break}$=Qj($)}}removeSessionDir(f){this.removeDir(this.sessionArtifactsDir(f))}removeDir(f){if(!VJ(f))return;try{dU(f,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths(f,$,J){let{rootSessionId:H,fileStem:W}=lU(f),Q=this.sessionArtifactsDir(H);return{messagesPath:XJ(Q,`${W}.messages.json`)}}}import{resolveDocumentsExtensionPath as pU}from"@cline/shared/storage";Kf();function Zj(f,$,J,H,W){if(J)m4(f.telemetry,{ulid:$,apiProvider:f.providerId,...W});else k4(f.telemetry,{ulid:$,apiProvider:f.providerId,...W});iU(f.telemetry,{workspacePath:H})}function iU(f,$){let J=pU("Hooks"),H=t0($.workspacePath),W=new Map;for(let Q of H){let Z=Q.hookEventName??"unknown",j=W.get(Z)??{global:0,workspace:0};if(Q.path===J||Q.path.startsWith(`${J}/`))j.global+=1;else j.workspace+=1;W.set(Z,j)}for(let[Q,Z]of W.entries())p4(f,Q,Z.global,Z.workspace)}function jj(f,$){for(let J of $.mentions)r4(f,J,$.matchedFiles.includes(J)?1:0,"file",!$.matchedFiles.includes(J));for(let J of $.matchedFiles)c4(f,"file",J.length);for(let J of $.ignoredMentions)d4(f,"file","not_found",J)}var JV={};N(JV,{ProviderSettingsManager:()=>P0});import{chmodSync as PV,existsSync as d9,mkdirSync as k_,readFileSync as m_,writeFileSync as I_}from"node:fs";import{basename as XV,dirname as r9}from"node:path";import{resolveProviderSettingsPath as x_}from"@cline/shared/storage";var L={};N(L,{writeHubDiscovery:()=>f6,writeGlobalSettings:()=>A$,withHubStartupLock:()=>$6,verifyHubConnection:()=>sf,updateLocalProvider:()=>dJ,truncateNotificationBody:()=>h4,toggleDisabledTool:()=>n4,toTeamProgressLifecycleEvent:()=>t1,toProviderConfig:()=>Cf,toHubHealthUrl:()=>LH,toHookConfigFileName:()=>G8,summarizeUsageFromMessages:()=>A8,stopLocalHubServerGracefully:()=>mH,startLocalOAuthServer:()=>M0,startHubWebSocketServer:()=>M4,startHubServer:()=>QV,startClineDeviceAuth:()=>Y5,splitCoreSessionConfig:()=>e8,spawnDetachedHubServer:()=>Y1,setTelemetryOptOutGlobally:()=>v3,setDisabledTools:()=>UH,setDisabledPlugin:()=>r3,sendHubCommand:()=>K7,saveLocalProviderSettings:()=>T9,saveLocalProviderOAuthCredentials:()=>L9,sanitizeTeamName:()=>K6,sanitizeSessionToken:()=>q$,safeParseSettings:()=>jJ,safeCreateProviderConfig:()=>H5,runSubprocessEvent:()=>W2,runHook:()=>Z2,reviveTeamStateDates:()=>y6,restartLocalHubIfIdleAfterStartupTimeout:()=>W6,resolveWorkspaceHubOwnerContext:()=>Q7,resolveWorkflowsConfigSearchPaths:()=>p8,resolveSkillsConfigSearchPaths:()=>r8,resolveSharedHubOwnerContext:()=>Xf,resolveSessionBackend:()=>J9,resolveRulesConfigSearchPaths:()=>l8,resolveProviderConfig:()=>z8,resolvePluginConfigSearchPaths:()=>F8,resolveMcpServerRegistrations:()=>A4,resolveLocalClineAuthToken:()=>z9,resolveHubUrl:()=>IH,resolveHubOwnerContext:()=>y0,resolveHubEndpointOptions:()=>tf,resolveHubBuildId:()=>S0,resolveHooksConfigSearchPaths:()=>K8,resolveDisabledToolNames:()=>uf,resolveDisabledPluginPaths:()=>q2,resolveDefaultMcpSettingsPath:()=>Q$,resolveDefaultHubPort:()=>V1,resolveDefaultHubPathname:()=>bH,resolveDefaultHubHost:()=>qH,resolveCoreSelectedToolIds:()=>G6,resolveCompatibleLocalHubUrl:()=>x2,resolveClineDir:()=>$7,resolveClineDataDir:()=>S2,resolveAndLoadAgentPlugins:()=>w1,resolveAgentPluginPaths:()=>E$,requestHubShutdown:()=>I2,requestDesktopToolApproval:()=>A9,rememberRecoverableLocalHubUrl:()=>k0,registerMcpServersFromSettingsFile:()=>J2,registerDisposable:()=>C_,refreshProviderModelsFromSource:()=>D9,refreshOpenAICodexToken:()=>m8,refreshOcaToken:()=>D8,refreshClineToken:()=>S8,readSessionCheckpointHistory:()=>U4,readHubDiscovery:()=>Qf,readGlobalSettings:()=>af,probeHubServer:()=>Pf,probeHubConnection:()=>y7,prewarmFileIndex:()=>V6,prewarmDetachedHubServer:()=>J6,parseWorkflowConfigFromMarkdown:()=>d8,parseUserCommandEnvelope:()=>w_,parseSkillConfigFromMarkdown:()=>u8,parseSettings:()=>ZJ,parseRuleConfigFromMarkdown:()=>c8,parseHookEventPayload:()=>Q2,openaiCodexOAuthProvider:()=>y5,normalizeWorkspacePath:()=>V0,normalizeUserInput:()=>b_,normalizeRuntimeCapabilities:()=>Bf,normalizeProviderId:()=>v1,normalizeOpenAICodexCredentials:()=>F5,normalizeOAuthProvider:()=>M9,normalizeHubWebSocketUrl:()=>m0,noopBasicLogger:()=>q_,migrateLegacyProviderSettings:()=>K4,mergeRulesForSystemPrompt:()=>H1,mergeAgentHooks:()=>I$,makeTeamTaskSubSessionId:()=>j8,makeSubSessionId:()=>_1,loginOpenAICodex:()=>l1,loginOcaOAuth:()=>x1,loginLocalProvider:()=>_9,loginClineOAuth:()=>r1,loadOpenTelemetryAdapter:()=>G_,loadMcpSettingsFile:()=>B4,loadLlmsConfigFromFile:()=>v9,loadAgentPluginsFromPathsWithDiagnostics:()=>D0,loadAgentPluginsFromPaths:()=>O6,loadAgentPluginFromPath:()=>R8,listSessionHistoryFromBackend:()=>I5,listPluginTools:()=>o8,listLocalProviders:()=>G9,listHookConfigFiles:()=>t0,isToolDisabledGlobally:()=>u3,isTelemetryOptedOutGlobally:()=>i4,isRuleEnabled:()=>O4,isPluginDisabledGlobally:()=>d3,isOpenAICodexTokenExpired:()=>R5,isHubReconnectableTransportError:()=>SH,isHubCommandTimeoutError:()=>H6,isDiscoveryFilePresent:()=>H7,isClineAccountActionRequest:()=>YJ,isBuiltInProviderId:()=>$5,identifyAccount:()=>R0,hasMcpSettingsFile:()=>$2,getValidOpenAICodexCredentials:()=>I8,getValidOcaCredentials:()=>M8,getValidClineCredentials:()=>k8,getProviderConfigFields:()=>O9,getProviderConfig:()=>a6,getLocalProviderModels:()=>h9,getLiveModelsCatalog:()=>g1,getFileIndex:()=>U0,getCurrentContextSize:()=>LW,getCoreHeadlessToolNames:()=>Z8,getCoreDefaultEnabledToolIds:()=>U6,getCoreBuiltinToolCatalog:()=>O$,getCoreAcpToolNames:()=>h6,getClineDefaultSystemPrompt:()=>T_,generateWorkspaceInfoWithDiagnostics:()=>K2,generateWorkspaceInfo:()=>W1,generateOcaOpcRequestId:()=>u6,formatRulesForSystemPrompt:()=>J1,formatDisplayUserInput:()=>N_,filterExtensionToolRegistrations:()=>t4,filterDisabledTools:()=>R$,filterDisabledPluginPaths:()=>a4,fetchClineRecommendedModels:()=>x9,executeClineAccountAction:()=>BJ,ensureHubWebSocketServer:()=>oJ,ensureHubServer:()=>ZV,ensureDetachedHubServer:()=>j7,ensureCustomProvidersLoaded:()=>cJ,ensureCompatibleLocalHubUrl:()=>K$,enrichPromptWithMentions:()=>F1,emptyWorkspaceManifest:()=>O_,emptyStoredProviderSettings:()=>$$,discoverPluginModulePaths:()=>y8,deriveSubsessionStatus:()=>X8,deleteLocalProvider:()=>rJ,defineLlmsConfig:()=>g9,createWorkflowsConfigDefinition:()=>a8,createUserInstructionConfigService:()=>H$,createToolPoliciesWithPreset:()=>B6,createTool:()=>z_,createTeamName:()=>IJ,createSubprocessHooks:()=>mJ,createSpawnAgentTool:()=>r0,createSkillsConfigDefinition:()=>i8,createSessionHost:()=>e1,createRuntimeHost:()=>e1,createRulesConfigDefinition:()=>n8,createProviderConfig:()=>J5,createOpenTelemetryTelemetryService:()=>E2,createOcaRequestHeaders:()=>rW,createOcaOAuthProvider:()=>dW,createOAuthClientCallbacks:()=>E8,createMcpTools:()=>H2,createLocalHubScheduleRuntimeHandlers:()=>WV,createLlmsSdk:()=>c9,createInitialAccumulatedUsage:()=>p0,createInMemoryHubOwnerContext:()=>J7,createHubServerUrl:()=>cf,createHubAuthToken:()=>e4,createHookConfigFileHooks:()=>h8,createHookConfigFileExtension:()=>k1,createHookAuditHooks:()=>S1,createDisabledMcpToolPolicy:()=>R4,createDisabledMcpToolPolicies:()=>EJ,createDelegatedAgentConfigProvider:()=>h1,createDelegatedAgent:()=>T1,createDefaultToolsWithPreset:()=>A6,createDefaultTools:()=>u0,createDefaultMcpServerClientFactory:()=>f2,createDefaultExecutors:()=>y1,createCoreSettingsService:()=>v$,createCoreSessionSnapshot:()=>J0,createContributionRegistry:()=>L_,createContextCompactionPrepareTurn:()=>d2,createConfiguredTelemetryService:()=>y$,createConfiguredTelemetryHandle:()=>X1,createClineTelemetryServiceMetadata:()=>__,createClineTelemetryServiceConfig:()=>M_,createClineOAuthProvider:()=>A5,createBuiltinTools:()=>N$,createAgentTeamsTools:()=>z$,createAgentRuntime:()=>S_,createAgentHooksExtension:()=>C1,connectToHub:()=>Q6,completeClineDeviceAuth:()=>B5,clearPrivateModelsCatalogCache:()=>eW,clearLiveModelsCatalogCache:()=>oW,clearHubDiscovery:()=>zf,captureWorkspacePathResolved:()=>k3,captureWorkspaceInitialized:()=>E4,captureWorkspaceInitError:()=>S4,captureToolUsage:()=>g4,captureTokenUsage:()=>I4,captureTaskRestarted:()=>m4,captureTaskCreated:()=>k4,captureTaskCompleted:()=>_2,captureSubagentExecution:()=>z2,captureSkillUsed:()=>v4,captureProviderApiError:()=>L2,captureModeSwitch:()=>x4,captureMentionUsed:()=>c4,captureMentionSearchResults:()=>r4,captureMentionFailed:()=>d4,captureHookDiscovery:()=>p4,captureExtensionActivated:()=>S3,captureDiffEditFailure:()=>u4,captureConversationTurnEvent:()=>Z1,captureAuthSucceeded:()=>B0,captureAuthStarted:()=>Y0,captureAuthLoggedOut:()=>C0,captureAuthFailed:()=>A0,captureAgentTeamCreated:()=>l4,captureAgentCreated:()=>E0,buildWorkspaceMetadata:()=>U2,buildTeamProgressSummary:()=>a1,buildDelegatedAgentConfig:()=>_$,bootstrapAgentTeams:()=>M1,addLocalProvider:()=>U9,accumulateUsageTotals:()=>i0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>v8,UnifiedConfigFileWatcher:()=>x$,ToolPresets:()=>bf,TelemetryService:()=>j1,TelemetryLoggerSink:()=>C2,TEAM_TOOL_NAMES:()=>D1,SubprocessSandbox:()=>b1,StoredProviderSettingsSchema:()=>u1,StoredProviderSettingsEntrySchema:()=>PJ,SqliteTeamStore:()=>n$,SqliteSessionStore:()=>W0,SessionVersioningService:()=>Z$,SessionVersioningError:()=>Df,SessionSource:()=>Vf,SapSettingsSchema:()=>HJ,SKILLS_CONFIG_DIRECTORY_NAME:()=>g8,SESSION_STATUSES:()=>V8,RpcClineAccountService:()=>C8,RemoteRuntimeHost:()=>n1,ReasoningSettingsSchema:()=>e6,RULES_CONFIG_DIRECTORY_NAME:()=>hJ,ProviderSettingsSchema:()=>e0,ProviderSettingsManager:()=>P0,ProviderProtocolSchema:()=>t6,ProviderIdSchema:()=>N8,ProviderClientSchema:()=>s6,OpenTelemetryProvider:()=>P1,OcaSettingsSchema:()=>WJ,OPENAI_COMPATIBLE_PROVIDERS:()=>L8,OCI_HEADER_OPC_REQUEST_ID:()=>g6,NodeHubClient:()=>df,NativeHubTransportAdapter:()=>D4,ModelCatalogSettingsSchema:()=>QJ,LocalRuntimeHost:()=>j0,Llms:()=>h_,InMemoryWorkspaceManager:()=>c1,InMemoryMcpManager:()=>l$,HubUIClient:()=>gH,HubTransportError:()=>Rf,HubSessionClient:()=>xH,HubServerTransport:()=>B2,HubScheduleService:()=>Q1,HubScheduleCommandService:()=>$1,HubRuntimeHost:()=>_0,HubCommandError:()=>B1,HookEventPayloadSchema:()=>kJ,HookEventNameSchema:()=>SJ,HookConfigFileName:()=>E1,HOOK_CONFIG_FILE_EVENT_MAP:()=>U8,HOOKS_CONFIG_DIRECTORY_NAME:()=>b6,GlobalSettingsSchema:()=>N2,GcpSettingsSchema:()=>$J,FileTeamPersistenceStore:()=>lJ,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>sJ,DefaultToolNames:()=>ff,DefaultRuntimeBuilder:()=>X2,DefaultLlmsSdk:()=>G4,DEFAULT_MODELS_CATALOG_URL:()=>i6,DEFAULT_INTERNAL_OCA_BASE_URL:()=>m1,DEFAULT_INTERNAL_IDCS_URL:()=>S6,DEFAULT_INTERNAL_IDCS_SCOPES:()=>k6,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>E6,DEFAULT_HUB_PORT:()=>OH,DEFAULT_HUB_PATHNAME:()=>NH,DEFAULT_HUB_HOST:()=>zH,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>I1,DEFAULT_EXTERNAL_IDCS_URL:()=>I6,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>x6,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>m6,CoreSettingsService:()=>W$,CoreSessionService:()=>Z0,ContributionRegistry:()=>D_,ClineCore:()=>V4,ClineAccountService:()=>w8,ChatViewStateSchema:()=>m9,ChatSummarySchema:()=>tJ,ChatSessionStatusSchema:()=>iJ,ChatSessionConfigSchema:()=>pJ,ChatMessageSchema:()=>aJ,ChatMessageRoleSchema:()=>nJ,CORE_TELEMETRY_EVENTS:()=>g,CORE_BUILD_VERSION:()=>I9,BrowserWebSocketHubAdapter:()=>T4,BUILT_IN_PROVIDER_IDS:()=>f5,BUILT_IN_PROVIDER:()=>O8,AzureSettingsSchema:()=>JJ,AwsSettingsSchema:()=>fJ,AuthSettingsSchema:()=>o6,AgentTeamsRuntime:()=>r$,AgentTeam:()=>o1,Agent:()=>E_,ALL_DEFAULT_TOOL_NAMES:()=>q0});O(L,HI);import*as h_ from"@cline/llms";import{buildClineSystemPrompt as T_,ContributionRegistry as D_,createClineTelemetryServiceConfig as M_,createClineTelemetryServiceMetadata as __,createContributionRegistry as L_,createTool as z_,emptyWorkspaceManifest as O_,formatDisplayUserInput as N_,noopBasicLogger as q_,normalizeUserInput as b_,parseUserCommandEnvelope as w_,registerDisposable as C_}from"@cline/shared";import"@cline/shared/storage";var Xj={};N(Xj,{isClineAccountActionRequest:()=>YJ,executeClineAccountAction:()=>BJ,RpcClineAccountService:()=>C8,ClineAccountService:()=>w8});function nU(f){if(typeof f!=="object"||f===null||!("error"in f))return;let $=f.error;return typeof $==="string"&&$.trim()?$:void 0}function Pj(f,$,J){let H=nU(J);if(H)return H;let W=$.trim();if(W){let Q=W.length>200?`${W.slice(0,200)}...`:W;return`Cline account request failed with status ${f}: ${Q}`}return`Cline account request failed with status ${f}`}class w8{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor(f){let $=f.apiBaseUrl.trim();if(!$)throw Error("apiBaseUrl is required");this.apiBaseUrl=$,this.getAuthTokenFn=f.getAuthToken,this.getCurrentUserIdFn=f.getCurrentUserId,this.getOrganizationMemberIdFn=f.getOrganizationMemberId,this.getHeadersFn=f.getHeaders,this.requestTimeoutMs=f.requestTimeoutMs??30000,this.fetchImpl=f.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance(f){let $=await this.resolveUserId(f);return this.request(`/api/v1/users/${encodeURIComponent($)}/balance`)}async fetchUsageTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/usages`)).items??[]}async fetchPaymentTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}`)}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}/balance`)}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId($,f.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent($)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount(f){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:f?.trim()||null},expectNoContent:!0})}async resolveUserId(f){let $=f?.trim();if($)return $;let H=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(H)return H;let W=await this.fetchMe();if(!W.id?.trim())throw Error("Unable to resolve current user id");return W.id}async resolveOrganizationMemberId(f,$){let J=$?.trim();if(J)return J;let W=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn(f):void 0)?.trim();if(W)return W;let Z=(await this.fetchUserOrganizations()).find((j)=>j.organizationId===f)?.memberId;if(!Z?.trim())throw Error(`Unable to resolve memberId for organization ${f}`);return Z}async request(f,$){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let H=this.getHeadersFn?await this.getHeadersFn():{},W=new AbortController,Q=setTimeout(()=>W.abort(),this.requestTimeoutMs);try{let Z=await this.fetchImpl(new URL(f,this.apiBaseUrl),{method:$?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...H??{}},body:$?.body!==void 0?JSON.stringify($.body):void 0,signal:W.signal});if(Z.status===204||$?.expectNoContent){if(!Z.ok)throw Error(`Cline account request failed with status ${Z.status}`);return}let j=await Z.text(),P;if(j.trim())try{P=JSON.parse(j)}catch{if(!Z.ok)throw Error(Pj(Z.status,j,void 0));throw Error("Cline account response was not valid JSON")}if(!Z.ok)throw Error(Pj(Z.status,j,P));if(typeof P==="object"&&P!==null){let X=P;if(typeof X.success==="boolean"){if(!X.success)throw Error(X.error||"Cline account request failed");if(X.data!==void 0)return X.data}}if(P===void 0||P===null)throw Error("Cline account response payload was empty");return P}finally{clearTimeout(Q)}}}function YJ(f){return f.action==="clineAccount"}async function BJ(f,$){switch(f.operation){case"fetchMe":return $.fetchMe();case"fetchBalance":return $.fetchBalance(f.userId);case"fetchUsageTransactions":return $.fetchUsageTransactions(f.userId);case"fetchPaymentTransactions":return $.fetchPaymentTransactions(f.userId);case"fetchUserOrganizations":return $.fetchUserOrganizations();case"fetchOrganizationBalance":return $.fetchOrganizationBalance(f.organizationId);case"fetchOrganizationUsageTransactions":return $.fetchOrganizationUsageTransactions({organizationId:f.organizationId,memberId:f.memberId});case"switchAccount":return await $.switchAccount(f.organizationId),{updated:!0};case"fetchFeaturebaseToken":return $.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String(f)}`)}}class C8{executor;constructor(f){this.executor=f}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance(f){return this.request({action:"clineAccount",operation:"fetchBalance",...f?.trim()?{userId:f.trim()}:{}})}async fetchUsageTransactions(f){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchPaymentTransactions(f){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:$})}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:$,...f.memberId?.trim()?{memberId:f.memberId.trim()}:{}})}async switchAccount(f){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:f?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request(f){return(await this.executor.runProviderAction(f)).result}}var Vj={};N(Vj,{createOAuthClientCallbacks:()=>E8});function E8(f){return{onAuth:({url:$,instructions:J})=>{if(f.onOutput?.(J??"Complete sign-in in your browser."),f.openUrl)try{Promise.resolve(f.openUrl($)).catch((H)=>{f.onOpenUrlError?.({url:$,error:H})})}catch(H){f.onOpenUrlError?.({url:$,error:H})}f.onOutput?.($)},onPrompt:f.onPrompt,onServerListening:f.onServerListening,onServerClose:f.onServerClose}}Kf();var Uj={};N(Uj,{startClineDeviceAuth:()=>Y5,refreshClineToken:()=>S8,loginClineOAuth:()=>r1,getValidClineCredentials:()=>k8,createClineOAuthProvider:()=>A5,completeClineDeviceAuth:()=>B5});var AJ={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},Rj={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},Z5="https://api.workos.com",j5="client_01K3A541FN8TA3EPPHTD2325AR",aU="/auth",Yj=Array.from({length:11},(f,$)=>48801+$),tU=300000,sU=30000,d1=30000,oU=300,eU=5;class J$ extends Error{status;errorCode;constructor(f,$){super(f);this.name="ClineOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function fG(f){let $=Date.parse(f);if(Number.isNaN($))throw Error(`Invalid expiresAt value: ${f}`);return $}function P5(f,$,J={}){let H=f.userInfo.clineUserId??J.accountId,W=f.refreshToken??J.refresh;if(!W)throw Error("Token response did not include a refresh token");return{access:f.accessToken,refresh:W,expires:fG(f.expiresAt),accountId:H??void 0,email:f.userInfo.email||J.email,metadata:{provider:$,tokenType:f.tokenType,userInfo:f.userInfo}}}async function X5(f){if(!f)return{};return typeof f==="function"?await f():f}function Bj(f,$){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return $;return Math.floor(f)}async function Aj(f){await new Promise(($)=>setTimeout($,f))}function V5(f,$){if(!f.success||!f.data?.accessToken)throw Error($);return f.data}async function Fj(f,$){let J=await fetch(w$(Z5,Rj.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:f}),signal:AbortSignal.timeout($?.requestTimeoutMs??d1)}),H=await J.json().catch(()=>({}));if(!J.ok)throw new J$(`Device authorization failed: ${J.status}${H.error_description?` - ${H.error_description}`:""}`,{status:J.status,errorCode:H.error});if(!H.device_code||!H.user_code||!H.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:H.device_code,userCode:H.user_code,verificationUri:H.verification_uri,verificationUriComplete:H.verification_uri_complete,expiresInSeconds:Bj(H.expires_in,oU),pollIntervalSeconds:Bj(H.interval,eU)}}async function yj(f){let $=Date.now()+f.expiresInSeconds*1000,J=Math.max(1,f.initialPollIntervalSeconds);while(Date.now()<=$){let H=await fetch(w$(f.workosApiBaseUrl,Rj.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:f.deviceCode,client_id:f.clientId}),signal:AbortSignal.timeout(f.requestTimeoutMs)}),W=await H.json().catch(()=>({}));if(H.ok){if(!W.access_token||!W.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:W.access_token,refreshToken:W.refresh_token,tokenType:W.token_type??"Bearer"}}switch(W.error){case"authorization_pending":{await Aj(J*1000);break}case"slow_down":{J+=1,await Aj(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new J$(W.error_description||"WorkOS authorization failed",{status:H.status,errorCode:W.error});default:throw new J$(`WorkOS token polling failed: ${H.status}${W.error_description?` - ${W.error_description}`:""}`,{status:H.status,errorCode:W.error})}f.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function Kj(f,$,J){let H={accessToken:f.accessToken,refreshToken:f.refreshToken},W=await fetch(w$($.apiBaseUrl,AJ.register),{method:"POST",headers:{"Content-Type":"application/json",...await X5($.headers)},body:JSON.stringify(H),signal:AbortSignal.timeout($.requestTimeoutMs??d1)});if(!W.ok){let Z=await W.text().catch(()=>""),j=N1(Z);throw new J$(`Token registration failed: ${W.status}${j.message?` - ${j.message}`:""}`,{status:W.status,errorCode:j.code})}let Q=await W.json();return P5(V5(Q,"Invalid token exchange response"),J??$.provider)}async function $G(f,$,J,H){let W={grant_type:"authorization_code",code:f,client_type:"extension",redirect_uri:$,provider:H??J.provider},Q=await fetch(w$(J.apiBaseUrl,AJ.token),{method:"POST",headers:{"Content-Type":"application/json",...await X5(J.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(J.requestTimeoutMs??d1)});if(!Q.ok){let j=await Q.text().catch(()=>""),P=N1(j);throw new J$(`Token exchange failed: ${Q.status}${P.message?` - ${P.message}`:""}`,{status:Q.status,errorCode:P.code})}let Z=await Q.json();return P5(V5(Z,"Invalid token exchange response"),H??J.provider)}async function r1(f){Y0(f.telemetry,f.provider??"cline");let $=f.useWorkOSDeviceAuth??!0,J=f.callbackPorts?.length?f.callbackPorts:Yj,H=f.callbackPath??aU,W=$?null:await M0({ports:J,callbackPath:H,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),Q=W?.callbackUrl||`http://127.0.0.1:${J[0]??Yj[0]}${H}`;try{let Z;if($){let j=j5,P=await Fj(j,f);f.callbacks.onAuth({url:P.verificationUriComplete??P.verificationUri,instructions:`Enter this code in your browser: ${P.userCode}`});let X=await yj({clientId:j,deviceCode:P.deviceCode,expiresInSeconds:P.expiresInSeconds,initialPollIntervalSeconds:P.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??d1,workosApiBaseUrl:Z5,onProgress:f.callbacks.onProgress});Z=await Kj(X,f,f.provider)}else{let j=new URL(w$(f.apiBaseUrl,AJ.authorize));j.searchParams.set("client_type","extension"),j.searchParams.set("callback_url",Q),j.searchParams.set("redirect_uri",Q),f.callbacks.onAuth({url:j.toString(),instructions:"Continue the authentication process in your browser."});let P,X=f.provider,V=await q1({waitForCallback:W?.waitForCallback??(async()=>null),cancelWait:W?.cancelWait??(()=>{}),onManualCodeInput:f.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(V.error)throw Error(`OAuth error: ${V.error}`);if(P=V.code,X=V.provider??X,!P){let Y=await f.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=O1(Y,{includeProvider:!0});P=B.code,X=B.provider??X}if(!P)throw Error("Missing authorization code");Z=await $G(P,Q,f,X)}return B0(f.telemetry,f.provider??"cline"),R0(f.telemetry,{id:Z.accountId,email:Z.email,provider:f.provider??"cline"}),Z}catch(Z){throw A0(f.telemetry,f.provider??"cline",Z instanceof Error?Z.message:String(Z)),Z}finally{W?.close()}}async function Y5(f){return await Fj(j5,f)}async function B5(f){let $=f.provider??"cline";Y0(f.telemetry,$);try{let J=await yj({clientId:j5,deviceCode:f.deviceCode,expiresInSeconds:f.expiresInSeconds,initialPollIntervalSeconds:f.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??d1,workosApiBaseUrl:Z5}),H=await Kj(J,{apiBaseUrl:f.apiBaseUrl,headers:f.headers,requestTimeoutMs:f.requestTimeoutMs,provider:f.provider},f.provider);return B0(f.telemetry,$),R0(f.telemetry,{id:H.accountId,email:H.email,provider:$}),H}catch(J){throw A0(f.telemetry,$,J instanceof Error?J.message:String(J)),J}}async function S8(f,$){let J=await fetch(w$($.apiBaseUrl,AJ.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await X5($.headers)},body:JSON.stringify({refreshToken:f.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout($.requestTimeoutMs??d1)});if(!J.ok){let Q=await J.text().catch(()=>""),Z=N1(Q);throw new J$(`Token refresh failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let H=await J.json(),W=f.metadata?.provider??$.provider;return P5(V5(H,"Invalid token refresh response"),W,f)}async function k8(f,$,J){if(!f)return null;let H=J?.refreshBufferMs??tU,W=J?.retryableTokenGraceMs??sU;if(J?.forceRefresh!==!0&&!C$(f,H))return f;try{return await S8(f,$)}catch(Z){if(Z instanceof J$&&Z.isLikelyInvalidGrant())return C0($.telemetry,$.provider??"cline","invalid_grant"),null;if(f.expires-Date.now()>W)return f;return null}}function A5(f){return{id:"cline",name:"Cline Account",usesCallbackServer:!(f.useWorkOSDeviceAuth??!0),async login($){return r1({...f,callbacks:$})},async refreshToken($){return S8($,f)},getApiKey($){return`workos:${$.access}`}}}Kf();var Tj={};N(Tj,{refreshOpenAICodexToken:()=>m8,openaiCodexOAuthProvider:()=>y5,normalizeOpenAICodexCredentials:()=>F5,loginOpenAICodex:()=>l1,isOpenAICodexTokenExpired:()=>R5,getValidOpenAICodexCredentials:()=>I8,OPENAI_CODEX_OAUTH_CONFIG:()=>o});import{nanoid as JG}from"nanoid";var o={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 RJ extends Error{status;errorCode;constructor(f,$){super(f);this.name="OpenAICodexOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function HG(f,$,J=o.redirectUri){let H=await fetch(o.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:o.clientId,code:f,code_verifier:$,redirect_uri:J}),signal:AbortSignal.timeout(o.httpTimeoutMs)});if(!H.ok)return{type:"failed"};let W=await H.json();if(!W.access_token||!W.refresh_token||typeof W.expires_in!=="number")return{type:"failed"};return{type:"success",access:W.access_token,refresh:W.refresh_token,expires:Date.now()+W.expires_in*1000,email:W.email,idToken:W.id_token}}async function WG(f){try{let $=await fetch(o.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:f,client_id:o.clientId}),signal:AbortSignal.timeout(o.httpTimeoutMs)});if(!$.ok){let H=await $.text().catch(()=>""),W=N1(H);throw new RJ(`Token refresh failed: ${$.status}${W.message?` - ${W.message}`:""}`,{status:$.status,errorCode:W.code})}let J=await $.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch($){if($ instanceof RJ)throw $;return{type:"failed"}}}async function QG(f="pi"){let{verifier:$,challenge:J}=await M6(),H=JG(32),W=new URL(o.authorizationEndpoint);return W.searchParams.set("response_type","code"),W.searchParams.set("client_id",o.clientId),W.searchParams.set("redirect_uri",o.redirectUri),W.searchParams.set("scope",o.scopes),W.searchParams.set("code_challenge",J),W.searchParams.set("code_challenge_method","S256"),W.searchParams.set("state",H),W.searchParams.set("id_token_add_organizations","true"),W.searchParams.set("codex_cli_simplified_flow","true"),W.searchParams.set("originator",f),{verifier:$,state:H,url:W.toString()}}function ZG(){try{let f=new URL(o.redirectUri),$=f.port.length>0?Number.parseInt(f.port,10):o.callbackPort;return{host:f.hostname||"localhost",port:Number.isFinite($)?$:o.callbackPort,callbackPath:f.pathname||"/auth/callback",redirectUri:f.toString()}}catch{return{host:"localhost",port:o.callbackPort,callbackPath:"/auth/callback",redirectUri:o.redirectUri}}}function Gj(f,$){let J=$?Ff($):Ff(f),H=J?J:Ff(f),Q=H?.[o.jwtClaimPath]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=H?.organizations;if(Array.isArray(Z)&&Z.length>0){let P=Z[0];if(typeof P?.id==="string"&&P.id.length>0)return P.id}let j=H?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return null}function hj(f,$){let J=Gj(f.access,f.idToken)??$?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:f.access,refresh:f.refresh||$?.refresh||"",expires:f.expires,accountId:J,email:f.email??$?.email,metadata:{...$?.metadata??{},provider:"openai-codex"}}}async function l1(f){Y0(f.telemetry,"openai-codex");let $=ZG(),{verifier:J,state:H,url:W}=await QG(f.originator),Q=await M0({host:$.host,ports:[$.port],callbackPath:$.callbackPath,expectedState:H});f.onAuth({url:W,instructions:"Continue the authentication process in your browser."});let Z;try{let j=await q1({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:f.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(j.state&&j.state!==H)throw Error("State mismatch");if(Z=j.code,!Z){let V=await f.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),Y=O1(V,{allowHashCodeState:!0});if(Y.state&&Y.state!==H)throw Error("State mismatch");Z=Y.code}if(!Z)throw Error("Missing authorization code");let P=await HG(Z,J,$.redirectUri);if(P.type!=="success")throw Error("Token exchange failed");let X=hj(P);return B0(f.telemetry,"openai-codex"),R0(f.telemetry,{id:X.accountId,email:X.email,provider:"openai-codex"}),X}catch(j){throw A0(f.telemetry,"openai-codex",j instanceof Error?j.message:String(j)),j}finally{Q.close()}}async function m8(f,$){let J=await WG(f);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let H=hj(J,$);if(!H.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return H}async function I8(f,$){if(!f)return null;let J=$?.refreshBufferMs??o.refreshBufferMs,H=$?.retryableTokenGraceMs??o.retryableTokenGraceMs;if($?.forceRefresh!==!0&&!C$(f,J))return f;try{return await m8(f.refresh,f)}catch(Q){if(Q instanceof RJ&&Q.isLikelyInvalidGrant())return C0($?.telemetry,"openai-codex","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function R5(f,$=o.refreshBufferMs){return C$(f,$)}function F5(f){let $=f.accountId??Gj(f.access);if(!$)throw Error("Failed to extract accountId from token");return{...f,accountId:$,metadata:{...f.metadata??{},provider:"openai-codex"}}}var y5={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login(f){return l1({onAuth:f.onAuth,onPrompt:f.onPrompt,onProgress:f.onProgress,onManualCodeInput:f.onManualCodeInput})},async refreshToken(f){return m8(f.refresh,f)},getApiKey(f){return f.access}};var rP={};N(rP,{ClineCore:()=>V4});function Dj(f){if(f===!0)return{};if(!f)return;return f}function Mj(f){if(f==="user")return"global";return f}class K5{getService;constructor(f){this.getService=f}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent(f){let $=this.getService().ingestEvent(f);return{event:$.event,duplicate:$.duplicate,matchedSpecIds:$.matchedSpecs.map((J)=>J.specId),queuedRuns:$.queuedRuns,suppressions:$.suppressions}}listEvents(f){return this.getService().listEventLogs(f)}getEvent(f){return this.getService().getEventLog(f)}listSpecs(f){return this.getService().listSpecs(f)}listRuns(f){return this.getService().listRuns(f)}}function _j(f){let{host:$}=f;return{async startSession(J){let H=(J.cwd?.trim()||J.workspaceRoot).trim(),W=await $.startSession({source:J.source?.trim()||Vf.CLI,interactive:!1,config:{providerId:v1(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:H,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:XG(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:f.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(J,H){let W=await $.runTurn({sessionId:J,prompt:H.prompt,userImages:H.attachments?.userImages,userFiles:H.attachments?.userFiles?.map((Q)=>Q.content),delivery:H.delivery});if(!W)throw Error("ClineCore automation runtime returned no result");return{result:PG(W)}},async abortSession(J){return await $.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function FJ(f){let $=jG(f.automationService,f.automation),J=f.context?.client??(f.clientName?{name:f.clientName}:void 0),H=f.context?.user??(f.distinctId?{distinctId:f.distinctId}:void 0),W=f.context?.logger??f.logger,Q=f.context?.telemetry??f.telemetry;if(!$&&!J&&!H&&!W&&!Q)return f.context;return{...f.context??{},...J?{client:J}:{},...H?{user:H}:{},...W?{logger:W}:{},...Q?{telemetry:Q}:{},...$?{automation:$}:{}}}function jG(f,$){if(!f)return;return{ingestEvent:(J)=>{$.ingestEvent(J)}}}function PG(f){return{text:f.text,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost},inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function XG(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}var rj={};N(rj,{createCoreSettingsService:()=>v$,CoreSettingsService:()=>W$});import{existsSync as M5}from"node:fs";import{basename as uj,isAbsolute as IG,relative as xG}from"node:path";var mj={};N(mj,{resolveWorkflowsConfigSearchPaths:()=>p8,resolveSkillsConfigSearchPaths:()=>r8,resolveRulesConfigSearchPaths:()=>l8,parseWorkflowConfigFromMarkdown:()=>d8,parseSkillConfigFromMarkdown:()=>u8,parseRuleConfigFromMarkdown:()=>c8,createWorkflowsConfigDefinition:()=>a8,createUserInstructionConfigService:()=>H$,createSkillsConfigDefinition:()=>i8,createRulesConfigDefinition:()=>n8,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>v8,UnifiedConfigFileWatcher:()=>x$,SKILLS_CONFIG_DIRECTORY_NAME:()=>g8,RULES_CONFIG_DIRECTORY_NAME:()=>hJ});import{createHash as VG}from"node:crypto";import{watch as YG}from"node:fs";import{readdir as BG,readFile as AG}from"node:fs/promises";import{join as RG}from"node:path";function FG(f){return VG("sha1").update(f).digest("hex")}function Oj(f){return Boolean(f&&typeof f==="object"&&"code"in f)}function Lj(f){return Oj(f)&&f.code==="ENOENT"}function zj(f){return Oj(f)&&(f.code==="EACCES"||f.code==="EPERM")}class x${definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor(f,$){if(f.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=f,this.debounceMs=$?.debounceMs??75,this.emitParseErrors=$?.emitParseErrors??!1;for(let J of f){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let H of J.directories){let W=this.baseTypesByDirectory.get(H);if(W)W.add(J.type);else this.baseTypesByDirectory.set(H,new Set([J.type]))}}}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let f of this.watchersByDirectory.values())f.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let f of this.definitions)await this.refreshTypeInternal(f)})}async refreshType(f){let $=this.definitionsByType.get(f);if(!$)throw Error(`Unknown unified config type '${f}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal($)})}getSnapshot(f){let $=this.recordsByType.get(f);return new Map([...$?.entries()??[]].map(([J,H])=>[J,{...H}]))}getAllSnapshots(){let f=new Map;for(let[$,J]of this.recordsByType.entries())f.set($,new Map([...J.entries()].map(([H,W])=>[H,{...W}])));return f}emit(f){for(let $ of this.listeners)$(f)}enqueueRefresh(f){return this.refreshQueue=this.refreshQueue.then(f,f),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let f=this.buildDesiredTypesByDirectory();for(let[$,J]of this.watchersByDirectory.entries()){if(f.has($))continue;J.close(),this.watchersByDirectory.delete($)}this.watchedTypesByDirectory=f;for(let $ of f.keys()){if(this.watchersByDirectory.has($))continue;try{let J=YG($,()=>{let H=this.watchedTypesByDirectory.get($);if(!H)return;for(let W of H)this.pendingTypes.add(W);this.scheduleFlush()});this.watchersByDirectory.set($,J),J.on("error",(H)=>{let W=this.watchedTypesByDirectory.get($);if(!W)return;for(let Q of W)this.emit({kind:"error",type:Q,error:H,filePath:$})})}catch(J){if(!Lj(J)&&!zj(J)){let H=f.get($);if(!H)continue;for(let W of H)this.emit({kind:"error",type:W,error:J,filePath:$})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let f=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let $ of f){let J=this.definitionsByType.get($);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal(f){let{records:$,discoveredDirectories:J}=await this.loadDefinition(f),H=this.recordsByType.get(f.type)??new Map;for(let[W,Q]of H.entries()){if($.has(W))continue;this.emit({kind:"remove",type:f.type,id:W,filePath:Q.filePath})}for(let[W,Q]of $.entries()){let Z=H.get(W);if(Z&&Z.filePath===Q.filePath&&Z.fingerprint===Q.fingerprint)continue;this.emit({kind:"upsert",record:{type:Q.type,id:W,item:Q.item,filePath:Q.filePath}})}if(this.recordsByType.set(f.type,$),this.discoveredDirectoriesByType.set(f.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition(f){let $=new Map,J=new Set;for(let H of f.directories){J.add(H);let W=f.discoverFiles?await f.discoverFiles(H):await this.readDirectoryFileCandidates(H);for(let Q of W){let{fileName:Z,filePath:j}=Q;if(J.add(Q.directoryPath),f.includeFile&&!f.includeFile(Z,j))continue;try{let P=await AG(j,"utf8"),X={type:f.type,directoryPath:Q.directoryPath,fileName:Z,filePath:j,content:P},V=f.parseFile(X),Y=f.resolveId(V,X).trim();if(!Y)continue;$.set(Y,{type:f.type,id:Y,item:V,filePath:j,fingerprint:FG(P)})}catch(P){if(this.emitParseErrors)this.emit({kind:"error",type:f.type,error:P,filePath:j})}}}return{records:$,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let f=new Map;for(let[$,J]of this.baseTypesByDirectory.entries())f.set($,new Set(J));for(let[$,J]of this.discoveredDirectoriesByType.entries())for(let H of J){let W=f.get(H);if(W)W.add($);else f.set(H,new Set([$]))}return f}async readDirectoryFileCandidates(f){try{return(await BG(f,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:f,fileName:J.name,filePath:RG(f,J.name)})).sort((J,H)=>J.fileName.localeCompare(H.fileName))}catch($){if(Lj($)||zj($))return[];throw $}}}import{readdir as U5,readFile as yG,stat as Nj}from"node:fs/promises";import{basename as g$,dirname as KG,extname as G5,join as hf}from"node:path";import{RULES_CONFIG_DIRECTORY_NAME as hJ,resolveRulesConfigSearchPaths as UG,resolveSkillsConfigSearchPaths as GG,resolveWorkflowsConfigSearchPaths as hG,SKILLS_CONFIG_DIRECTORY_NAME as g8,WORKFLOWS_CONFIG_DIRECTORY_NAME as v8}from"@cline/shared/storage";import TG from"yaml";var yJ="SKILL.md",DG="managed.json",MG=new Set([".md",".markdown",".txt"]);function h5(f){return f.trim().toLowerCase()}function x8(f){let $=f;return $?.code==="ENOENT"||$?.code==="EACCES"||$?.code==="EPERM"}function KJ(f){return MG.has(G5(f).toLowerCase())}async function T5(f){try{let $=await U5(f,{withFileTypes:!0}),J=[];for(let H of $){if(!H.isDirectory())continue;let W=hf(f,H.name),Q=hf(W,DG);try{let Z=await yG(Q,"utf8"),j=JSON.parse(Z);if(j&&typeof j==="object")J.push(W)}catch(Z){if(x8(Z))continue;if(Z?.name==="SyntaxError")continue;throw Z}}return J.sort((H,W)=>H.localeCompare(W))}catch($){if(x8($))return[];throw $}}function D5(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,H,W]=J;try{let Q=TG.parse(H);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:W,hadFrontmatter:!0}}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);return{data:{},body:f,hadFrontmatter:!0,parseError:Z}}}function UJ(f,$,J){if(f===void 0||f===null){if(J)throw Error(`Missing required frontmatter field '${$}'.`);return}if(typeof f!=="string")throw Error(`Frontmatter field '${$}' must be a string.`);let H=f.trim();if(!H&&J)throw Error(`Frontmatter field '${$}' cannot be empty.`);return H||void 0}function p1(f,$){if(f===void 0||f===null)return;if(typeof f!=="boolean")throw Error(`Frontmatter field '${$}' must be a boolean.`);return f}function u8(f,$){let{data:J,body:H,parseError:W}=D5(f);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let Q=H.trim();if(!Q)throw Error("Missing instructions body in skill file.");let j=UJ(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing skill name.");return{name:j,description:UJ(J.description,"description",!1),disabled:p1(J.disabled,"disabled")??(p1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function c8(f,$){let{data:J,body:H,parseError:W}=D5(f);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let Q=H.trim();if(!Q)throw Error("Missing instructions body in rule file.");let Z=UJ(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing rule name.");return{name:Z,disabled:p1(J.disabled,"disabled")??(p1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function d8(f,$){let{data:J,body:H,parseError:W}=D5(f);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let Q=H.trim();if(!Q)throw Error("Missing instructions body in workflow file.");let Z=UJ(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing workflow name.");return{name:Z,disabled:p1(J.disabled,"disabled")??(p1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function r8(f){return GG(f)}function l8(f){return UG(f)}function p8(f){return hG(f)}async function qj(f){if(g$(f)===".cline"){let $=await T5(f);return(await Promise.all($.map((H)=>qj(hf(H,g8))))).flat()}try{let $=await U5(f,{withFileTypes:!0}),J=[];for(let H of $){if(H.isFile()&&H.name===yJ){J.push({directoryPath:f,fileName:H.name,filePath:hf(f,H.name)});continue}if(H.isDirectory())J.push({directoryPath:hf(f,H.name),fileName:yJ,filePath:hf(f,H.name,yJ)})}return J}catch($){if(x8($))return[];throw $}}async function GJ(f){if(g$(f)===".cline"){let $=await T5(f);return(await Promise.all($.map((H)=>GJ(hf(H,"rules.md"))))).flat()}try{if((await Nj(f)).isFile())return[{directoryPath:KG(f),fileName:g$(f),filePath:f}]}catch($){if(!x8($))throw $}try{let J=(await U5(f,{withFileTypes:!0})).filter((W)=>W.isFile()&&KJ(W.name)).map((W)=>({directoryPath:f,fileName:W.name,filePath:hf(f,W.name)})),H=hf(f,"AGENTS.md");try{if((await Nj(H)).isFile()){if(!J.some((Z)=>Z.fileName==="AGENTS.md"))J.push({directoryPath:f,fileName:"AGENTS.md",filePath:H})}}catch{}return J}catch($){if(x8($))return[];throw $}}async function _G(f){if(g$(f)===".cline"){let $=await T5(f);return(await Promise.all($.map((H)=>GJ(hf(H,v8))))).flat()}return GJ(f)}function i8(f){let $=f?.directories??r8(f?.workspacePath),J=f?.workspacePath?hf(f.workspacePath,".cline"):void 0;return{type:"skill",directories:J?[...$,J]:$,discoverFiles:qj,includeFile:(H)=>H===yJ,parseFile:(H)=>u8(H.content,g$(H.directoryPath)),resolveId:(H)=>h5(H.name)}}function n8(f){let $=f?.directories??l8(f?.workspacePath),J=f?.workspacePath?hf(f.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...$,J]:$,discoverFiles:GJ,includeFile:(H,W)=>H===".clinerules"||KJ(H)||KJ(W),parseFile:(H)=>c8(H.content,g$(H.filePath,G5(H.filePath))),resolveId:(H)=>h5(H.name)}}function a8(f){let $=f?.directories??p8(f?.workspacePath),J=f?.workspacePath?hf(f.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...$,J]:$,discoverFiles:_G,includeFile:(H)=>KJ(H),parseFile:(H)=>d8(H.content,g$(H.filePath,G5(H.filePath))),resolveId:(H)=>h5(H.name)}}function bj(f){let $=[i8(f?.skills),n8(f?.rules),a8(f?.workflows)];return new x$($,{debounceMs:f?.debounceMs,emitParseErrors:f?.emitParseErrors})}import{truncateSplit as wj}from"@cline/shared";function LG(f,$){if(f.description?.trim())return wj(f.description,".");if($==="workflow")return;return wj(f.instructions,".")}function zG(f){return f.disabled!==!0}function Cj(f,$){return[...f.getSnapshot($).entries()].map(([J,H])=>({id:J,record:H})).filter(({record:J})=>zG(J.item)).map(({id:J,record:H})=>({id:J,name:H.item.name,instructions:H.item.instructions,description:LG(H.item,$),kind:$})).sort((J,H)=>J.name.localeCompare(H.name))}function t8(f){let $=new Map;for(let J of[...Cj(f,"workflow"),...Cj(f,"skill")])if(!$.has(J.name))$.set(J.name,J);return[...$.values()].sort((J,H)=>J.name.localeCompare(H.name))}function Ej(f,$){if(!f.startsWith("/")||f.length<2)return f;let J=f.match(/^\/(\S+)/);if(!J)return f;let H=J[1];if(!H)return f;let W=H.length+1,Q=f.slice(W),Z=t8($).find((j)=>j.name===H);return Z?`${Z.instructions}${Q}`:f}function TJ(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function OG(f){if(!f||f.length===0)return;let $=f.map(TJ).filter((J)=>J.length>0);return $.length>0?new Set($):void 0}function NG(f,$,J){if(!J)return!0;let H=TJ(f),W=TJ($),Q=H.includes(":")?H.split(":").at(-1)??H:H,Z=W.includes(":")?W.split(":").at(-1)??W:W;return J.has(H)||J.has(W)||J.has(Q)||J.has(Z)}function s8(f,$){let J=OG($);return[...f.getSnapshot("skill").entries()].map(([W,Q])=>{let Z=Q.item;return{id:W,name:Z.name.trim(),description:Z.description?.trim(),disabled:Z.disabled===!0,skill:Z}}).filter((W)=>NG(W.id,W.name,J))}function qG(f,$){return s8(f,$).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,H)=>J.localeCompare(H))}function bG(f,$,J){let H=TJ($);if(!H)return{error:"Missing skill name."};let W=s8(f,J),Q=W.find((V)=>V.id===H);if(Q){let{skill:V}=Q;if(V.disabled===!0)return{error:`Skill "${V.name}" is configured but disabled.`};return{id:Q.id,skill:V}}let Z=H.includes(":")?H.split(":").at(-1)??H:H,j=W.filter(({id:V})=>{if(V===Z)return!0;return V.endsWith(`:${Z}`)}),P=j.filter(({skill:V})=>V.disabled!==!0);if(P.length===1){let{id:V,skill:Y}=P[0];return{id:V,skill:Y}}if(P.length>1)return{error:`Skill "${$}" is ambiguous. Use one of: ${P.map(({id:V})=>V).join(", ")}`};if(j.length===1){let{skill:V}=j[0];return{error:`Skill "${V.name}" is configured but disabled.`}}if(j.length>1)return{error:`Skill "${$}" is ambiguous, and all matches are disabled: ${j.map(({id:V})=>V).join(", ")}`};let X=qG(f,J);return{error:X.length>0?`Skill "${$}" not found. Available skills: ${X.join(", ")}`:"No skills are currently available."}}function wG(f,$=Promise.resolve(),J){let H=new Set,W=async(Q,Z)=>{await $;let j=bG(f,Q,J);if("error"in j)return j.error;let{id:P,skill:X}=j;if(H.has(P))return`Skill "${X.name}" is already running.`;H.add(P);try{let V=Z?.trim(),Y=V?`
457
- <command-args>${V}</command-args>`:"",B=X.description?.trim()?`Description: ${X.description.trim()}
456
+ </html>`;var fj="a8331954c0cf48ba99b5dd223a14c6ea",$j="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",Jj="openid offline_access",m6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",Wj="c1aba3deed5740659981a752714eba33",Hj="https://login-ext.identity.oraclecloud.com",Qj="openid offline_access",x6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",Zj="opc-request-id",KU="/auth/oca",yU=Array.from({length:11},(f,$)=>48801+$),UU=300000,GU=30000,jj=30000,TU=600000;class g6 extends Error{status;errorCode;constructor(f,$){super(f);this.name="OcaOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var $$={internal:{clientId:fj,idcsUrl:$j,scopes:Jj,baseUrl:m6},external:{clientId:Wj,idcsUrl:Hj,scopes:Qj,baseUrl:x6}},h8=new Map,DU=86400000,_U=300000,MU=32,pW=new lW(DU,MU);function Xj(f){if(typeof f==="function")return f();return f??"internal"}function Aj(f){return{internal:{clientId:f?.internal?.clientId??$$.internal.clientId,idcsUrl:f?.internal?.idcsUrl??$$.internal.idcsUrl,scopes:f?.internal?.scopes??$$.internal.scopes,baseUrl:f?.internal?.baseUrl??$$.internal.baseUrl},external:{clientId:f?.external?.clientId??$$.external.clientId,idcsUrl:f?.external?.idcsUrl??$$.external.idcsUrl,scopes:f?.external?.scopes??$$.external.scopes,baseUrl:f?.external?.baseUrl??$$.external.baseUrl}}}function LU(f=Date.now()){let $=f-TU;for(let[J,W]of h8.entries())if(W.createdAt<$)h8.delete(J)}function hU(f,$,J){if(typeof f.expires_in==="number"&&f.expires_in>0)return Date.now()+f.expires_in*1000;let H=Kf($)?.exp;if(typeof H==="number"&&H>0)return H*1000;let Z=Kf(J)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return Date.now()+3600000}function Pj(f,$,J){let W=f.access_token;if(!W)throw Error("Token response did not include an access token");let H=f.refresh_token??J?.refresh;if(!H)throw Error("Token response did not include a refresh token");let Q=Kf(f.id_token),Z=Kf(W),j=Q?.sub??Z?.sub,X=Q?.email??Z?.email;return{access:W,refresh:H,expires:hU(f,W,f.id_token),accountId:j??J?.accountId,email:X??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:$,subject:j,idToken:f.id_token}}}async function Bj(f,$){let J=q6(f),W=pW.get(J);if(W)return W;let H=`${J}/.well-known/openid-configuration`,Q=await fetch(H,{method:"GET",signal:AbortSignal.timeout($)});if(!Q.ok){let X=`${J}/oauth2/v1/token`;return pW.set(J,X,Date.now(),_U),X}let j=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return pW.set(J,j),j}function Yj(f){return{code:f.error,message:f.error_description}}async function OU(f){let $=h8.get(f.state);if(!$)throw Error("No PKCE verifier found for this state");h8.delete(f.state);let J=f.mode==="external"?f.config.external:f.config.internal,W=await Bj(J.idcsUrl,f.requestTimeoutMs),H=new URLSearchParams({grant_type:"authorization_code",code:f.code,redirect_uri:$.redirectUri,client_id:J.clientId,code_verifier:$.verifier}),Q=await fetch(W,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H,signal:AbortSignal.timeout(f.requestTimeoutMs)}),Z=await Q.json();if(!Q.ok){let X=Yj(Z);throw new g6(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let j=Kf(Z.id_token);if(!Z.id_token||!j)throw Error("No ID token received from OCA");if(j.nonce!==$.nonce)throw Error("OIDC nonce verification failed");return Pj(Z,f.mode)}function zU(f){let $=f.mode==="external"?f.config.external:f.config.internal,J=new URL(`${q6($.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",$.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",$.scopes),J.searchParams.set("code_challenge",f.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",f.callbackUrl),J.searchParams.set("state",f.state),J.searchParams.set("nonce",f.nonce),J.toString()}async function u1(f){F0(f.telemetry,"oca");let $=Aj(f.config),J=Xj(f.mode),W=f.callbackPorts?.length?f.callbackPorts:yU,H=f.callbackPath??KU,Q=f.requestTimeoutMs??jj,Z=await N0({ports:W,callbackPath:H,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),j=Z.callbackUrl;if(!j)throw Error("Unable to bind local OAuth callback server");let X=eZ(16),A=eZ(16),{verifier:P,challenge:B}=await N6();LU(),h8.set(X,{verifier:P,nonce:A,mode:J,redirectUri:j,createdAt:Date.now()});let Y=zU({callbackUrl:j,mode:J,state:X,nonce:A,challenge:B,config:$});f.callbacks.onAuth({url:Y,instructions:"Continue the authentication process in your browser."});try{let V=await C1({waitForCallback:Z.waitForCallback,cancelWait:Z.cancelWait,onManualCodeInput:f.callbacks.onManualCodeInput}),R=V.code,U=V.state;if(V.error)throw Error(`OAuth error: ${V.error}`);if(!R){if(!f.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!U||U!==X)throw Error("State mismatch");let K=await OU({code:R,state:U,mode:J,config:$,requestTimeoutMs:Q});return K0(f.telemetry,"oca"),U0(f.telemetry,{id:K.accountId,email:K.email,provider:"oca"}),K}catch(V){throw y0(f.telemetry,"oca",V instanceof Error?V.message:String(V)),V}finally{Z.close()}}async function O8(f,$={}){let J=Aj($.config),W=$.requestTimeoutMs??jj,H=f.metadata?.mode,Q=H==="internal"||H==="external"?H:Xj($.mode),Z=Q==="external"?J.external:J.internal,j=await Bj(Z.idcsUrl,W),X=new URLSearchParams({grant_type:"refresh_token",refresh_token:f.refresh,client_id:Z.clientId}),A=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout(W)}),P=await A.json();if(!A.ok){let B=Yj(P);throw new g6(`Token refresh failed: ${A.status}${B.message?` - ${B.message}`:""}`,{status:A.status,errorCode:B.code})}return Pj(P,Q,f)}async function z8(f,$,J){if(!f)return null;let W=$?.refreshBufferMs??J?.refreshBufferMs??UU,H=$?.retryableTokenGraceMs??J?.retryableTokenGraceMs??GU;if($?.forceRefresh!==!0&&!k$(f,W))return f;try{return await O8(f,J)}catch(Z){if(Z instanceof g6&&Z.isLikelyInvalidGrant())return x0(J?.telemetry,"oca","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function iW(f={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login($){return u1({...f,callbacks:$})},async refreshToken($){return O8($,f)},getApiKey($){return $.access}}}async function v6(f,$){let J=new TextEncoder,W=async(A)=>{let P=await crypto.subtle.digest("SHA-256",J.encode(A));return Array.from(new Uint8Array(P).slice(0,4),(B)=>B.toString(16).padStart(2,"0")).join("")},[H,Q]=await Promise.all([W($),W(f)]),Z=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),j=new Uint32Array(1);crypto.getRandomValues(j);let X=(j[0]??0).toString(16).padStart(8,"0");return H+Q+Z+X}async function nW(f){let $=await v6(f.taskId,f.accessToken);return{Authorization:`Bearer ${f.accessToken}`,"Content-Type":"application/json",client:f.metadata?.client??"Cline","client-version":f.metadata?.clientVersion??"unknown","client-ide":f.metadata?.clientIde??"unknown","client-ide-version":f.metadata?.clientIdeVersion??"unknown",[Zj]:$}}var Gj={};N(Gj,{resolveProviderConfig:()=>b8,getProviderConfig:()=>i6,getLiveModelsCatalog:()=>c1,clearPublicModelsCatalogCache:()=>tU,clearPrivateModelsCatalogCache:()=>WH,clearLiveModelsCatalogCache:()=>JH,OPENAI_COMPATIBLE_PROVIDERS:()=>w8,DEFAULT_MODELS_CATALOG_URL:()=>p6});import*as ff from"@cline/llms";function aW(f){if(!Array.isArray(f))return[];return f.map(($)=>{if(typeof $==="string")return $.trim();if($&&typeof $==="object"){let J=$;for(let W of[J.id,J.name,J.model])if(typeof W==="string"&&W.trim())return W.trim()}return""}).filter(($)=>$.length>0)}function NU(f,$){let J=aW(f);if(J.length>0)return J;if(!f||typeof f!=="object")return[];let W=f,H=aW(W.data??W.models);if(H.length>0)return H;if(W.models&&typeof W.models==="object"&&!Array.isArray(W.models)){let Z=Object.keys(W.models).filter((j)=>j.trim().length>0);if(Z.length>0)return Z}let Q=W.providers?.[$];if(Q&&typeof Q==="object"){let j=aW(Q.models??Q);if(j.length>0)return j}return[]}async function u6(f,$){let J=await fetch(f,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${f}: HTTP ${J.status}`);return NU(await J.json(),$)}function Rj(f){return f.replace(/\/+$/,"")}function c6(f,$,J){let W=J?.trim();if(!W)return;let H=f?.trim();if(!H||!$?.trim())return W;try{let Q=new URL(W),Z=new URL($),j=new URL(H);if(Q.origin!==Z.origin)return W;let X=Rj(Z.pathname),A=Rj(j.pathname);if(X&&Q.pathname.startsWith(`${X}/`)){let P=Q.pathname.slice(X.length);j.pathname=`${A}${P}`}else j.pathname=Q.pathname;return j.search=Q.search,j.hash=Q.hash,j.toString()}catch{return W}}function qU(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{...J}]))}function wU(f){if(f.baseUrl.length===0)return!1;switch(f.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return f.protocol==="openai-chat"}}var bU=Object.values(ff.MODEL_COLLECTIONS_BY_PROVIDER_ID).map((f)=>({id:f.provider.id,baseUrl:f.provider.baseUrl??"",modelsSourceUrl:f.provider.modelsSourceUrl,modelId:f.provider.defaultModelId,knownModels:qU(f.models),capabilities:f.provider.capabilities?[...f.provider.capabilities]:void 0,env:f.provider.env?[...f.provider.env]:void 0,client:f.provider.client,protocol:f.provider.protocol})),Fj=Object.fromEntries(bU.map((f)=>[f.id,f]));function CU(f){return Fj[f]}function EU(){return Object.fromEntries(Object.entries(Fj).filter(([,f])=>wU(f)))}function Kj(f=[]){let $=f.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return $.length>0?$:void 0}var p6="https://models.dev/api.json",SU=600000,yj=300000,kU=5000,l6=new Map,N8=new Map,sW=new Map,d6=new Map;async function IU(){return ff.getGeneratedProviderModels()}async function mU(f,$={},J={},W={},H={},Q={}){let Z=await IU(),j=ff.resolveProviderModelCatalogKeys(f),X=Object.assign({},...j.map((Y)=>Z[Y]??{})),A=Boolean(ff.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl),P=Object.keys(H).length>0;if(A&&P)return ff.sortModelsByReleaseDate({...H,...Q});let B=Object.keys(W).length>0;if(f==="openai-codex"&&B)return ff.sortModelsByReleaseDate({...W,...Q});return ff.sortModelsByReleaseDate({...X,...$,...J,...W,...H,...Q})}function xU(f,$){let J=ff.resolveProviderModelCatalogKeys(f);return Object.assign({},...J.map((W)=>$[W]??{}))}function eW(f){let $=f?.trim();return $&&$.length>0?$:""}function fH(f){let $=f.apiKey?.trim()||f.accessToken?.trim();return $&&$.length>0?$:void 0}function gU(f){let $=2166136261;for(let J=0;J<f.length;J+=1)$^=f.charCodeAt(J),$+=($<<1)+($<<4)+($<<7)+($<<8)+($<<24);return($>>>0).toString(16)}function vU(f,$){return`${f}:${eW($.baseUrl)}:${gU(fH($)??"")}`}function uU(f){let $=f?.trim();if(!$)return;let J=Kf($),W=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let H=J?.organizations?.[0]?.id;if(typeof H==="string"&&H.length>0)return H;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}async function $H(f,$,J=kU){let W=new AbortController,H=setTimeout(()=>W.abort(),J);try{return await fetch(f,{...$,signal:W.signal})}finally{clearTimeout(H)}}function tW(f,$,J){if(J&&!f.includes($))f.push($)}function q8(f,$){let J=["streaming","tools"];return tW(J,"images",Boolean($.supportsImages)),tW(J,"prompt-cache",Boolean($.supportsPromptCache)),tW(J,"reasoning",Boolean($.supportsReasoning)),{id:f,name:$.name??f,contextWindow:$.contextWindow,maxTokens:$.maxTokens,capabilities:J,releaseDate:$.releaseDate,status:"active"}}function cU(f){let $=ff.getGeneratedModelsForProvider("openai")[f.id];if($)return{...$,id:f.id,name:f.name??$.name??f.id};return q8(f.id,{name:f.name??f.id})}async function dU(f,$){let J=await $H("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let H=(await J.json())?.data??[],Q={};for(let Z of H){let j=Z.id?.trim();if(!j)continue;if(j.includes("whisper")||j.includes("tts")||j.includes("embedding"))continue;let X=Z.supported_features??[];Q[j]=q8(j,{name:j,contextWindow:Z.context_length,maxTokens:Z.max_completion_tokens,supportsReasoning:X.includes("reasoning")||X.includes("reasoning_effort"),supportsImages:!1})}return Q}async function rU(f,$){let J=await $H("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":$}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let H=(await J.json())?.data??[],Q={};for(let Z of H){let j=Z.id?.trim();if(!j)continue;Q[j]=q8(j,{name:j,contextWindow:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}function lU(f){let $=eW(f);if(!$)return"http://localhost:4000";return $.endsWith("/v1")?$.slice(0,-3):$}async function pU(f,$){let W=`${lU(f.baseUrl)}/v1/model/info`,H=async(A)=>$H(W,{method:"GET",headers:{accept:"application/json",...A}}),Q=await H({"x-litellm-api-key":$});if(!Q.ok)Q=await H({Authorization:`Bearer ${$}`});if(!Q.ok)throw Error(`LiteLLM model refresh failed: HTTP ${Q.status}`);let j=(await Q.json())?.data??[],X={};for(let A of j){let P=A.model_name?.trim(),Y=A.litellm_params?.model?.trim()||P;if(!Y)continue;let V=A.model_info,R=q8(Y,{name:P??Y,maxTokens:V?.max_output_tokens??V?.max_tokens,contextWindow:V?.max_input_tokens??V?.max_tokens,supportsImages:V?.supports_vision,supportsPromptCache:V?.supports_prompt_caching,supportsReasoning:V?.supports_reasoning});if(X[Y]=R,P)X[P]={...R,id:P,name:P}}return X}async function iU(f,$){let J=await ff.listOpenAICodexModels({accessToken:$,accountId:f.accountId??uU($),cwd:typeof f.codex?.defaultSettings?.cwd==="string"?f.codex.defaultSettings.cwd:void 0,codexPath:typeof f.codex?.defaultSettings?.codexPath==="string"?f.codex.defaultSettings.codexPath:void 0,env:f.codex?.defaultSettings?.env&&typeof f.codex.defaultSettings.env==="object"&&!Array.isArray(f.codex.defaultSettings.env)?f.codex.defaultSettings.env:void 0});return Object.fromEntries(J.map((W)=>[W.id,cU(W)]))}var Uj={baseten:dU,hicap:rU,litellm:pU,"openai-codex":iU},oW=new Map,r6=new Map;function nU(f,$){return`${f}:${eW($.baseUrl)}`}async function aU(f,$,J){let W=ff.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],H=c6(J.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!H)return{};let Q=$?.cacheTtlMs??yj,Z=nU(f,J),j=Date.now(),X=oW.get(Z);if(X&&X.expiresAt>j)return X.data;let A=r6.get(Z);if(A)return A;let P=u6(H,f).then((B)=>{let Y=Object.fromEntries(B.map((V)=>[V,q8(V,{name:V})]));return oW.set(Z,{data:Y,expiresAt:j+Q}),Y}).finally(()=>{r6.delete(Z)});return r6.set(Z,P),P}function tU(){oW.clear(),r6.clear()}async function sU(f,$){let J=fH($);if(!J)return{};let W=Uj[f];if(!W)return{};return W($,J)}function oU(f,$,J){if(!J)return!1;if(!Uj[f])return!1;if($?.loadPrivateOnAuth===!1)return!1;return Boolean(fH(J))}async function eU(f,$,J){let W=$?.cacheTtlMs??yj,H=vU(f,J),Q=Date.now(),Z=sW.get(H);if(Z&&Z.expiresAt>Q)return Z.data;let j=d6.get(H);if(j)return j;let X=sU(f,J).then((A)=>{return sW.set(H,{data:A,expiresAt:Q+W}),A}).finally(()=>{d6.delete(H)});return d6.set(H,X),X}async function fG(f){return ff.fetchModelsDevProviderModels(f)}async function c1(f={}){let $=f.url??p6,J=f.cacheTtlMs??SU,W=Date.now(),H=l6.get($);if(H&&H.expiresAt>W)return H.data;let Q=N8.get($);if(Q)return Q;let Z=fG($).then((j)=>{return l6.set($,{data:j,expiresAt:W+J}),j}).finally(()=>{N8.delete($)});return N8.set($,Z),Z}function JH(f){if(f){l6.delete(f),N8.delete(f);return}l6.clear(),N8.clear()}function WH(){sW.clear(),d6.clear()}function $G(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:Kj(J.capabilities)}]))}var w8=$G(EU());function i6(f){let $=CU(f);if(!$||!$.baseUrl)return;return{baseUrl:$.baseUrl,modelId:$.modelId,knownModels:$.knownModels,capabilities:Kj($.capabilities)}}async function b8(f,$,J){let W=i6(f);if(!W)return;try{let H=$?.loadLatestOnInit?await c1($):void 0,Q=H?xU(f,H):{},Z=J&&oU(f,$,J)?await eU(f,$,J):{},X=Boolean(ff.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl)?J??{providerId:f,modelId:W.modelId,baseUrl:W.baseUrl}:J,A=X?await aU(f,$,X).catch(()=>({})):{},P=await mU(f,W.knownModels,Q,Z,A,J?.knownModels);return{...W,knownModels:P}}catch(H){if($?.failOnError)throw H;return W}}var C8=If.BUILT_IN_PROVIDER,HH=If.BUILT_IN_PROVIDER_IDS,QH=If.isBuiltInProviderId,d1=If.normalizeProviderId,E8=h.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),n6=h.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),a6=h.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),t6=h.object({apiKey:h.string().optional(),accessToken:h.string().optional(),refreshToken:h.string().optional(),expiresAt:h.number().int().positive().optional(),accountId:h.string().optional()}),JG=h.enum(["none","low","medium","high","xhigh"]),s6=h.object({enabled:h.boolean().optional(),effort:JG.optional(),budgetTokens:h.number().int().positive().optional()}),o6=h.object({accessKey:h.string().optional(),secretKey:h.string().optional(),sessionToken:h.string().optional(),region:h.string().optional(),profile:h.string().optional(),authentication:h.enum(["iam","api-key","profile"]).optional(),usePromptCache:h.boolean().optional(),useCrossRegionInference:h.boolean().optional(),useGlobalInference:h.boolean().optional(),endpoint:h.string().url().optional(),customModelBaseId:h.string().optional()}),e6=h.object({projectId:h.string().optional(),region:h.string().optional()}),fJ=h.object({apiVersion:h.string().optional(),useIdentity:h.boolean().optional()}),$J=h.object({clientId:h.string().optional(),clientSecret:h.string().optional(),tokenUrl:h.string().url().optional(),resourceGroup:h.string().optional(),deploymentId:h.string().optional(),useOrchestrationMode:h.boolean().optional(),api:h.enum(["orchestration","foundation-models"]).optional(),defaultSettings:h.record(h.string(),h.unknown()).optional()}),JJ=h.object({mode:h.enum(["internal","external"]).optional(),usePromptCache:h.boolean().optional()}),WJ=h.object({loadLatestOnInit:h.boolean().optional(),loadPrivateOnAuth:h.boolean().optional(),url:h.string().url().optional(),cacheTtlMs:h.number().int().positive().optional(),failOnError:h.boolean().optional()}),J$=h.object({provider:E8,apiKey:h.string().optional(),auth:t6.optional(),model:h.string().optional(),protocol:n6.optional(),client:a6.optional(),routingProviderId:E8.optional(),maxTokens:h.number().int().positive().optional(),contextWindow:h.number().int().positive().optional(),baseUrl:h.string().url().optional(),headers:h.record(h.string(),h.string()).optional(),timeout:h.number().int().positive().optional(),reasoning:s6.optional(),aws:o6.optional(),gcp:e6.optional(),azure:fJ.optional(),sap:$J.optional(),oca:JJ.optional(),region:h.string().optional(),apiLine:h.enum(["china","international"]).optional(),capabilities:h.array(h.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth"])).optional(),modelCatalog:WJ.optional()});function HJ(f){return J$.parse(f)}function QJ(f){return J$.safeParse(f)}function WG(f){return f.protocol==="openai-responses"||f.client==="openai"}function mf(f,$={}){let J=f.provider,W=d1(J),H=$.includeKnownModels!==!1,Q=f.reasoning?.effort||"none",Z=Q==="none"?void 0:Q,j=w8[W],X=Object.assign({},...If.resolveProviderModelCatalogKeys(W).map((U)=>If.getGeneratedModelsForProvider(U))),A=Object.keys(X)[0],P=f.auth?.accessToken??f.apiKey??f.auth?.apiKey,B=f.baseUrl??(W==="oca"?f.oca?.mode==="internal"?m6:x6:j?.baseUrl),Y=f.routingProviderId??(WG(f)&&W!==C8.OPENAI_NATIVE?C8.OPENAI_NATIVE:void 0),V=H?j?.knownModels??(Object.keys(X).length>0?X:void 0):void 0,R={providerId:J,clientType:f.client,routingProviderId:Y,modelId:f.model??j?.modelId??A??"default",...H?{knownModels:V}:{},apiKey:P,accessToken:f.auth?.accessToken,refreshToken:f.auth?.refreshToken,accountId:f.auth?.accountId,baseUrl:B,headers:f.headers,timeoutMs:f.timeout,maxOutputTokens:f.maxTokens,maxContextTokens:f.contextWindow,thinking:f.reasoning?.enabled,reasoningEffort:Z,thinkingBudgetTokens:f.reasoning?.budgetTokens,region:f.region??f.aws?.region??f.gcp?.region,apiLine:f.apiLine,useCrossRegionInference:f.aws?.useCrossRegionInference,useGlobalInference:f.aws?.useGlobalInference,aws:f.aws?{accessKey:f.aws.accessKey,secretKey:f.aws.secretKey,sessionToken:f.aws.sessionToken,authentication:f.aws.authentication,profile:f.aws.profile,usePromptCache:f.aws.usePromptCache,endpoint:f.aws.endpoint,customModelBaseId:f.aws.customModelBaseId}:void 0,gcp:f.gcp?{projectId:f.gcp.projectId,region:f.gcp.region}:void 0,azure:f.azure,sap:f.sap,oca:f.oca,capabilities:f.capabilities??j?.capabilities,modelCatalog:f.modelCatalog?{loadLatestOnInit:f.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:f.modelCatalog.loadPrivateOnAuth,url:f.modelCatalog.url,cacheTtlMs:f.modelCatalog.cacheTtlMs,failOnError:f.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(R).filter(([U,K])=>K!==void 0))}function ZH(f){let $=HJ(f);return mf($)}function jH(f){let $=QJ(f);if($.success)return{success:!0,config:mf($.data)};return{success:!1,error:$.error}}var S8=J$;var ZJ=W$.object({settings:J$,updatedAt:W$.string().datetime(),tokenSource:W$.enum(["manual","oauth","migration"]).default("manual")}),r1=W$.object({version:W$.literal(1),lastUsedProvider:W$.string().min(1).optional(),providers:W$.record(W$.string(),ZJ)});function H$(){return{version:1,providers:{}}}G0();var _j={};N(_j,{InMemoryWorkspaceManager:()=>l1});import{upsertWorkspaceInfo as HG,WorkspaceManifestSchema as XH}from"@cline/shared";class l1{manifest;listeners=new Set;constructor(f){this.manifest=XH.parse(f??{workspaces:{}})}async addWorkspacePath(f){let $=await Z1(f);return this.manifest=HG(this.manifest,$),this.emit({type:"workspace_added",workspace:$}),$}async switchWorkspace(f){let $=R0(f),J=this.manifest.workspaces[$];if(J)return this.manifest=XH.parse({...this.manifest,currentWorkspacePath:$}),this.emit({type:"workspace_switched",workspace:J}),J;let W=await this.addWorkspacePath($);return this.manifest=XH.parse({...this.manifest,currentWorkspacePath:W.rootPath}),this.emit({type:"workspace_switched",workspace:W}),W}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}getCurrentWorkspace(){let f=this.manifest.currentWorkspacePath;if(!f)return;return this.manifest.workspaces[f]}getWorkspace(f){let $=R0(f);return this.manifest.workspaces[$]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(f){for(let $ of this.listeners)$(f)}}_f();import{createHash as QG}from"node:crypto";var Mj=new Set,Lj=new Set;function ZG(f){return QG("sha256").update(f).digest("hex")}function jG(f){if(f.vcsTypes&&f.vcsTypes.length>0)return f.vcsTypes;return[f.vcsType==="git"?"git":"none"]}function hj(f){if(!f.telemetry)return;let $=ZG(f.rootPath),J=f.rootCount??1;if(!Mj.has($))Mj.add($),g4(f.telemetry,{root_count:J,vcs_types:jG(f),init_duration_ms:f.durationMs,feature_flag_enabled:f.featureFlagEnabled??!0,is_remote_workspace:f.isRemoteWorkspace});if(f.initError&&!Lj.has($)){Lj.add($);let W=Error(f.initError.message);W.name=f.initError.errorType||"Error",v4(f.telemetry,W,{fallback_to_single_root:!0,workspace_count:J})}}function AG(f){return`${f.pluginName??f.pluginPath}: ${f.message}`}function PG(f,$,J){if($.length>0)for(let Q of $)J?.log(Q.message,{severity:"warn"});if(f.length===0)return;let W=f.slice(0,3).map(AG).join("; "),H=f.length>3?`; and ${f.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${W}${H}. Use --verbose for more details.`,{severity:"warn"});for(let Q of f)J?.log(`Plugin initialization failed (${Q.phase}) for ${Q.pluginPath}`,{severity:"warn",stack:Q.stack,pluginPath:Q.pluginPath,pluginName:Q.pluginName})}function BG(f,$){let J=typeof f.thinking==="boolean",W=typeof f.reasoningEffort==="string";if(!J&&!W)return $;return{...$??{},...J?{enabled:f.thinking}:{},...W?{effort:f.reasoningEffort}:{}}}function YG(f,$){return XG(f,$)}function VG(f){let $=0;for(let J of f??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;$+=1}return $}function RG(f){let $={...f.storedHeaders??{},...f.configHeaders??{}},J=f.accountId?.trim()||FG(f.accessToken);if($.originator="cline",$.session_id=f.sessionId,$["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)$["ChatGPT-Account-Id"]=J;return $}function FG(f){let $=f?.trim();if(!$)return;let J=Kf($),W=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let H=J?.organizations?.[0]?.id;if(typeof H==="string"&&H.length>0)return H;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}function KG(f,$,J,W,H){let Q=J.getProviderSettings(f.providerId),Z=W||Q?.modelCatalog?{...W??{},...Q?.modelCatalog??{}}:void 0,j={...Q??{},provider:f.providerId,model:f.modelId,apiKey:f.apiKey??Q?.apiKey,baseUrl:f.baseUrl??Q?.baseUrl,headers:f.providerId==="openai-codex"?RG({sessionId:$,configHeaders:f.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:f.apiKey??Q?.auth?.accessToken??Q?.apiKey}):f.headers??Q?.headers,reasoning:BG(f,Q?.reasoning),modelCatalog:Z},X=mf(j);if(f.knownModels)X.knownModels=f.knownModels;if(f.extensionContext)X.extensionContext=f.extensionContext;let P=f.fetch??X.fetch??H;if(P)X.fetch=P;return X}async function Oj(f){let{input:$,sessionId:J,providerSettingsManager:W,defaultTelemetry:H,defaultCapabilities:Q,defaultToolPolicies:Z,defaultFetch:j,onPluginEvent:X,onTeamEvent:A,createSpawnTool:P,localRuntime:B,readSessionMetadata:Y,writeSessionMetadata:V}=f,R=o0($.config),{modelCatalogDefaults:U,userInstructionService:K,configExtensions:F,onTeamRestored:y,...D}=B??{},M=Object.keys(D).length>0?D:void 0,{workspaceInfo:T,workspaceMetadata:_,durationMs:L,vcsType:q,initError:Wf}=await A5(R),Hf=M?.extensionContext,o={...Hf??{},workspace:{...T,...Hf?.workspace??{}},session:{...Hf?.session??{},sessionId:J},logger:Hf?.logger??M?.logger,telemetry:Hf?.telemetry??M?.telemetry??H};hj({telemetry:o.telemetry,rootPath:T.rootPath,workspaceInfo:T,rootCount:1,vcsType:q,durationMs:L,initError:Wf,featureFlagEnabled:!0});let c=v1({cwd:$.config.cwd,workspacePath:R,rootSessionId:J,logger:M?.logger,workspaceInfo:T}),Gf=RZ(M?.hooks)?void 0:g1({rootSessionId:J,workspacePath:R,workspaceInfo:T}),E0=v$([M?.hooks,Gf]),i;if(YG(F,"plugins"))try{i=await I1({pluginPaths:M?.pluginPaths,workspacePath:R,cwd:$.config.cwd,onEvent:X,providerId:$.config.providerId,modelId:$.config.modelId,workspaceInfo:T,session:o.session,client:o.client,user:o.user,logger:o.logger,telemetry:o.telemetry,automation:o.automation}),PG(i.failures,i.warnings,M?.logger)}catch(y2){let r=y2 instanceof Error?y2.message:String(y2);M?.logger?.log?.(`plugin loading failed; continuing without plugins (${r})`)}let S=MW(c?[c]:void 0,MW(M?.extensions,J6(i?.extensions))),n={...$.config,...M??{},sessionId:J,hooks:E0,extensions:S,extensionContext:o,telemetry:o.telemetry},B0=KG(n,J,W,U,j),Y0=v$([n.hooks,n.checkpoint?.enabled===!0?cZ({cwd:n.cwd,sessionId:J,logger:n.logger,createCheckpoint:n.checkpoint?.createCheckpoint,initialRunCount:VG($.initialMessages),readSessionMetadata:Y,writeSessionMetadata:V}):void 0]),V$={...n,providerConfig:B0,workspaceMetadata:_,hooks:Y0},f1=$.toolPolicies??n.toolPolicies??Z,K2=Uf(Q,$.capabilities),C4=K2?.requestToolApproval,Q5=K2?.toolExecutors,$1=new l1({currentWorkspacePath:T.rootPath,workspaces:{[T.rootPath]:T}});return{effectiveInput:$,config:V$,providerConfig:B0,workspaceMetadata:_,workspaceInfo:T,extensions:S,hooks:Y0,toolPolicies:f1,requestToolApproval:C4,pluginSandboxShutdown:i?.shutdown,runtimeBuilderInput:{config:V$,hooks:Y0,extensions:S,onTeamEvent:A,createSpawnTool:P,onTeamRestored:y,userInstructionService:K,configExtensions:F,toolExecutors:Q5,workspaceManager:$1,logger:V$.logger,telemetry:V$.telemetry}}}import{existsSync as XJ,mkdirSync as yG,readdirSync as UG,rmdirSync as GG,rmSync as TG,unlinkSync as DG}from"node:fs";import{dirname as zj,join as jJ}from"node:path";function s(){return new Date().toISOString()}function k8(f){if(!f||!XJ(f))return;try{DG(f)}catch{}}function _G(f){let $=z1(f);if($)return{rootSessionId:$.rootSessionId,fileStem:`${$.agentId}__${$.teamTaskId}`};let J=P8(f);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:f,fileStem:f}}class AH{ensureSessionsDir;constructor(f){this.ensureSessionsDir=f}sessionArtifactsDir(f){return jJ(this.ensureSessionsDir(),f)}ensureSessionArtifactsDir(f){let $=this.sessionArtifactsDir(f);if(!XJ($))yG($,{recursive:!0});return $}sessionMessagesPath(f){return jJ(this.sessionArtifactsDir(f),`${f}.messages.json`)}sessionManifestPath(f,$=!1){let J=$?this.ensureSessionArtifactsDir(f):this.sessionArtifactsDir(f);return jJ(J,`${f}.json`)}removeSessionDirIfEmpty(f){let $=this.sessionArtifactsDir(f),J=this.ensureSessionsDir();while($.startsWith(J)&&$!==J){if(!XJ($)){$=zj($);continue}try{if(UG($).length>0)break;GG($)}catch{break}$=zj($)}}removeSessionDir(f){this.removeDir(this.sessionArtifactsDir(f))}removeDir(f){if(!XJ(f))return;try{TG(f,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths(f,$,J){let{rootSessionId:W,fileStem:H}=_G(f),Q=this.sessionArtifactsDir(W);return{messagesPath:jJ(Q,`${H}.messages.json`)}}}import{resolveDocumentsExtensionPath as MG}from"@cline/shared/storage";_f();function Nj(f,$,J,W,H){if(J)c4(f.telemetry,{ulid:$,apiProvider:f.providerId,...H});else u4(f.telemetry,{ulid:$,apiProvider:f.providerId,...H});LG(f.telemetry,{workspacePath:W})}function LG(f,$){let J=MG("Hooks"),W=e0($.workspacePath),H=new Map;for(let Q of W){let Z=Q.hookEventName??"unknown",j=H.get(Z)??{global:0,workspace:0};if(Q.path===J||Q.path.startsWith(`${J}/`))j.global+=1;else j.workspace+=1;H.set(Z,j)}for(let[Q,Z]of H.entries())o4(f,Q,Z.global,Z.workspace)}function qj(f,$){for(let J of $.mentions)t4(f,J,$.matchedFiles.includes(J)?1:0,"file",!$.matchedFiles.includes(J));for(let J of $.matchedFiles)n4(f,"file",J.length);for(let J of $.ignoredMentions)a4(f,"file","not_found",J)}var MP={};N(MP,{ProviderSettingsManager:()=>A0});import{chmodSync as qP,existsSync as e9,mkdirSync as Dh,readFileSync as _h,writeFileSync as Mh}from"node:fs";import{basename as wP,dirname as f3}from"node:path";import{resolveProviderSettingsPath as Lh}from"@cline/shared/storage";var O={};N(O,{writeHubDiscovery:()=>Z6,writeGlobalSettings:()=>y$,withHubStartupLock:()=>j6,verifyHubConnection:()=>ef,updateLocalProvider:()=>rJ,truncateNotificationBody:()=>h4,toggleDisabledTool:()=>f6,toTeamProgressLifecycleEvent:()=>e1,toProviderConfig:()=>mf,toHubHealthUrl:()=>O5,toHookConfigFileName:()=>M8,summarizeUsageFromMessages:()=>q1,stopLocalHubServerGracefully:()=>x5,startLocalOAuthServer:()=>N0,startHubWebSocketServer:()=>N4,startHubServer:()=>OP,startClineDeviceAuth:()=>FH,splitCoreSessionConfig:()=>H4,spawnDetachedHubServerWithRetry:()=>V1,spawnDetachedHubServer:()=>C5,setTelemetryOptOutGlobally:()=>o3,setDisabledTools:()=>G5,setDisabledPlugin:()=>JQ,sendHubCommand:()=>qQ,saveLocalProviderSettings:()=>b9,saveLocalProviderOAuthCredentials:()=>k9,sanitizeSessionToken:()=>C$,safeParseSettings:()=>QJ,safeCreateProviderConfig:()=>jH,runSubprocessEvent:()=>j2,runHook:()=>A2,reviveTeamStateDates:()=>_6,restartLocalHubIfIdleAfterStartupTimeout:()=>P6,resolveWorkspaceHubOwnerContext:()=>yQ,resolveWorkflowsConfigSearchPaths:()=>s8,resolveSkillsConfigSearchPaths:()=>a8,resolveSharedHubOwnerContext:()=>Rf,resolveSessionBackend:()=>X9,resolveRulesConfigSearchPaths:()=>t8,resolveProviderConfig:()=>b8,resolvePluginConfigSearchPaths:()=>G8,resolveMcpServerRegistrations:()=>U4,resolveLocalClineAuthToken:()=>I9,resolveHubUrl:()=>g5,resolveHubOwnerContext:()=>D0,resolveHubEndpointOptions:()=>of,resolveHubBuildId:()=>v0,resolveHooksConfigSearchPaths:()=>D8,resolveDisabledToolNames:()=>rf,resolveDisabledPluginPaths:()=>b2,resolveDefaultMcpSettingsPath:()=>P$,resolveDefaultHubPort:()=>Y1,resolveDefaultHubPathname:()=>b5,resolveDefaultHubHost:()=>w5,resolveCoreSelectedToolIds:()=>L6,resolveCompatibleLocalHubUrl:()=>v2,resolveClineDir:()=>VQ,resolveClineDataDir:()=>I2,resolveAndLoadAgentPlugins:()=>I1,resolveAgentPluginPaths:()=>I$,requestHubShutdown:()=>g2,requestDesktopToolApproval:()=>M9,rememberRecoverableLocalHubUrl:()=>u0,registerRemoteConfigSessionBlobUpload:()=>mJ,registerMcpServersFromSettingsFile:()=>Q2,registerDisposable:()=>Uh,refreshProviderModelsFromSource:()=>C9,refreshOpenAICodexToken:()=>u8,refreshOcaToken:()=>O8,refreshClineToken:()=>g8,readSessionCheckpointHistory:()=>M4,readRemoteConfigSessionBlobUploadMetadata:()=>V9,readHubDiscovery:()=>Af,readGlobalSettings:()=>sf,probeHubServer:()=>Vf,probeHubConnection:()=>NQ,prewarmFileIndex:()=>K6,prewarmDetachedHubServer:()=>X6,prepareRemoteConfigCoreIntegration:()=>F9,parseWorkflowConfigFromMarkdown:()=>n8,parseUserCommandEnvelope:()=>yh,parseSkillConfigFromMarkdown:()=>p8,parseSettings:()=>HJ,parseRuleConfigFromMarkdown:()=>i8,parseHookEventPayload:()=>X2,openaiCodexOAuthProvider:()=>TH,normalizeWorkspacePath:()=>R0,normalizeUserInput:()=>Kh,normalizeRuntimeCapabilities:()=>Uf,normalizeProviderId:()=>d1,normalizeOpenAICodexCredentials:()=>GH,normalizeOAuthProvider:()=>E9,normalizeHubWebSocketUrl:()=>c0,noopBasicLogger:()=>Fh,migrateLegacyProviderSettings:()=>_4,mergeRulesForSystemPrompt:()=>Q1,mergeAgentHooks:()=>v$,makeTeamTaskSubSessionId:()=>A8,makeSubSessionId:()=>O1,loginOpenAICodex:()=>n1,loginOcaOAuth:()=>u1,loginLocalProvider:()=>S9,loginClineOAuth:()=>i1,loadOpenTelemetryAdapter:()=>Qh,loadMcpSettingsFile:()=>y4,loadLlmsConfigFromFile:()=>t9,loadAgentPluginsFromPathsWithDiagnostics:()=>z0,loadAgentPluginsFromPaths:()=>b6,loadAgentPluginFromPath:()=>U8,listSessionHistoryFromBackend:()=>cH,listPluginTools:()=>W4,listLocalProviders:()=>q9,listHookConfigFiles:()=>e0,isToolDisabledGlobally:()=>e3,isTelemetryOptedOutGlobally:()=>e4,isRuleEnabled:()=>E4,isPluginDisabledGlobally:()=>$Q,isOpenAICodexTokenExpired:()=>UH,isHubReconnectableTransportError:()=>I5,isHubCommandTimeoutError:()=>A6,isDiscoveryFilePresent:()=>FQ,isClineAccountActionRequest:()=>AJ,isBuiltInProviderId:()=>QH,identifyAccount:()=>U0,hasMcpSettingsFile:()=>H2,getValidOpenAICodexCredentials:()=>c8,getValidOcaCredentials:()=>z8,getValidClineCredentials:()=>v8,getProviderConfigFields:()=>m9,getProviderConfig:()=>i6,getLocalProviderModels:()=>w9,getLiveModelsCatalog:()=>c1,getFileIndex:()=>M0,getCurrentContextSize:()=>zW,getCoreHeadlessToolNames:()=>X8,getCoreDefaultEnabledToolIds:()=>M6,getCoreBuiltinToolCatalog:()=>w$,getCoreAcpToolNames:()=>h6,getClineDefaultSystemPrompt:()=>jh,generateWorkspaceInfoWithDiagnostics:()=>G2,generateWorkspaceInfo:()=>Z1,generateOcaOpcRequestId:()=>v6,formatRulesForSystemPrompt:()=>H1,formatDisplayUserInput:()=>Rh,filterExtensionToolRegistrations:()=>J6,filterDisabledTools:()=>U$,filterDisabledPluginPaths:()=>$6,fetchClineRecommendedModels:()=>n9,executeClineAccountAction:()=>PJ,ensureHubWebSocketServer:()=>eJ,ensureHubServer:()=>zP,ensureDetachedHubServer:()=>GQ,ensureCustomProvidersLoaded:()=>dJ,ensureCompatibleLocalHubUrl:()=>T$,enrichPromptWithMentions:()=>y1,emptyWorkspaceManifest:()=>Vh,emptyStoredProviderSettings:()=>H$,discoverPluginModulePaths:()=>T8,deriveSubsessionStatus:()=>B8,deleteLocalProvider:()=>lJ,defineLlmsConfig:()=>a9,createWorkflowsConfigDefinition:()=>f4,createUserInstructionConfigService:()=>Z$,createToolPoliciesWithPreset:()=>U6,createTool:()=>Yh,createTeamName:()=>xJ,createSubprocessHooks:()=>SJ,createSpawnAgentTool:()=>t0,createSkillsConfigDefinition:()=>o8,createSessionHost:()=>J2,createRuntimeHost:()=>J2,createRulesConfigDefinition:()=>e8,createRemoteConfigSessionMessagesArtifactUploader:()=>R9,createProviderConfig:()=>ZH,createOpenTelemetryTelemetryService:()=>k2,createOcaRequestHeaders:()=>nW,createOcaOAuthProvider:()=>iW,createOAuthClientCallbacks:()=>x8,createMcpTools:()=>Z2,createLocalHubScheduleRuntimeHandlers:()=>hP,createLlmsSdk:()=>o9,createInitialAccumulatedUsage:()=>Pf,createInMemoryHubOwnerContext:()=>RQ,createHubServerUrl:()=>lf,createHubAuthToken:()=>Q6,createHookConfigFileHooks:()=>L8,createHookConfigFileExtension:()=>v1,createHookAuditHooks:()=>g1,createDisabledMcpToolPolicy:()=>G4,createDisabledMcpToolPolicies:()=>bJ,createDelegatedAgentConfigProvider:()=>_1,createDelegatedAgent:()=>M1,createDefaultToolsWithPreset:()=>G6,createDefaultTools:()=>i0,createDefaultMcpServerClientFactory:()=>W2,createDefaultExecutors:()=>U1,createCoreSettingsService:()=>d$,createCoreSessionSnapshot:()=>W0,createContributionRegistry:()=>Bh,createContextCompactionPrepareTurn:()=>l2,createConfiguredTelemetryService:()=>T0,createConfiguredTelemetryHandle:()=>B1,createClineTelemetryServiceMetadata:()=>Ph,createClineTelemetryServiceConfig:()=>Ah,createClineOAuthProvider:()=>yH,createBuiltinTools:()=>b$,createAgentTeamsTools:()=>q$,createAgentRuntime:()=>Th,createAgentHooksExtension:()=>m1,connectToHub:()=>B6,completeClineDeviceAuth:()=>KH,clearPrivateModelsCatalogCache:()=>WH,clearLiveModelsCatalogCache:()=>JH,clearHubDiscovery:()=>bf,captureWorkspacePathResolved:()=>i3,captureWorkspaceInitialized:()=>g4,captureWorkspaceInitError:()=>v4,captureToolUsage:()=>l4,captureTokenUsage:()=>d4,captureTaskRestarted:()=>c4,captureTaskCreated:()=>u4,captureTaskCompleted:()=>O2,captureSubagentExecution:()=>N2,captureSkillUsed:()=>p4,captureProviderApiError:()=>z2,captureModeSwitch:()=>r4,captureMentionUsed:()=>n4,captureMentionSearchResults:()=>t4,captureMentionFailed:()=>a4,captureHookDiscovery:()=>o4,captureExtensionActivated:()=>p3,captureDiffEditFailure:()=>i4,captureConversationTurnEvent:()=>X1,captureAuthSucceeded:()=>K0,captureAuthStarted:()=>F0,captureAuthLoggedOut:()=>x0,captureAuthFailed:()=>y0,captureAgentTeamCreated:()=>s4,captureAgentCreated:()=>g0,buildWorkspaceMetadata:()=>T2,buildTeamProgressSummary:()=>o1,buildRemoteConfigSessionBlobUploadMetadata:()=>kJ,buildDelegatedAgentConfig:()=>z$,bootstrapAgentTeams:()=>h1,addLocalProvider:()=>N9,accumulateUsageTotals:()=>Xf,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>l8,UnifiedConfigFileWatcher:()=>u$,ToolPresets:()=>kf,TelemetryService:()=>A1,TelemetryLoggerSink:()=>S2,TEAM_TOOL_NAMES:()=>L1,SubprocessSandbox:()=>k1,StoredProviderSettingsSchema:()=>r1,StoredProviderSettingsEntrySchema:()=>ZJ,SqliteTeamStore:()=>t$,SqliteSessionStore:()=>Q0,SessionVersioningService:()=>B$,SessionVersioningError:()=>zf,SessionSource:()=>Ff,SapSettingsSchema:()=>$J,SKILLS_CONFIG_DIRECTORY_NAME:()=>r8,SESSION_STATUSES:()=>Y8,RpcClineAccountService:()=>m8,RemoteRuntimeHost:()=>s1,ReasoningSettingsSchema:()=>s6,RULES_CONFIG_DIRECTORY_NAME:()=>UJ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>IJ,ProviderSettingsSchema:()=>J$,ProviderSettingsManager:()=>A0,ProviderProtocolSchema:()=>n6,ProviderIdSchema:()=>E8,ProviderClientSchema:()=>a6,OpenTelemetryProvider:()=>P1,OcaSettingsSchema:()=>JJ,OPENAI_COMPATIBLE_PROVIDERS:()=>w8,NodeHubClient:()=>pf,NativeHubTransportAdapter:()=>z4,ModelCatalogSettingsSchema:()=>WJ,LocalRuntimeHost:()=>X0,Llms:()=>Zh,InMemoryWorkspaceManager:()=>l1,InMemoryMcpManager:()=>i$,HubUIClient:()=>u5,HubTransportError:()=>Df,HubSessionClient:()=>v5,HubServerTransport:()=>F2,HubScheduleService:()=>j1,HubScheduleCommandService:()=>W1,HubRuntimeHost:()=>q0,HubCommandError:()=>R1,HookEventPayloadSchema:()=>EJ,HookEventNameSchema:()=>CJ,HookConfigFileName:()=>x1,HOOK_CONFIG_FILE_EVENT_MAP:()=>_8,HOOKS_CONFIG_DIRECTORY_NAME:()=>S6,GlobalSettingsSchema:()=>w2,GcpSettingsSchema:()=>e6,FileTeamPersistenceStore:()=>pJ,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>oJ,DefaultToolNames:()=>Jf,DefaultRuntimeBuilder:()=>Y2,DefaultLlmsSdk:()=>L4,DEFAULT_MODELS_CATALOG_URL:()=>p6,DEFAULT_HUB_PORT:()=>N5,DEFAULT_HUB_PATHNAME:()=>q5,DEFAULT_HUB_HOST:()=>z5,CoreSettingsService:()=>j$,CoreSessionService:()=>j0,ContributionRegistry:()=>Xh,ClineCore:()=>F4,ClineAccountService:()=>I8,ChatViewStateSchema:()=>p9,ChatSummarySchema:()=>sJ,ChatSessionStatusSchema:()=>nJ,ChatSessionConfigSchema:()=>iJ,ChatMessageSchema:()=>tJ,ChatMessageRoleSchema:()=>aJ,CORE_TELEMETRY_EVENTS:()=>v,CORE_BUILD_VERSION:()=>i9,BrowserWebSocketHubAdapter:()=>O4,BUILT_IN_PROVIDER_IDS:()=>HH,BUILT_IN_PROVIDER:()=>C8,AzureSettingsSchema:()=>fJ,AwsSettingsSchema:()=>o6,AuthSettingsSchema:()=>t6,AgentTeamsRuntime:()=>p$,AgentTeam:()=>$2,Agent:()=>Gh,ALL_DEFAULT_TOOL_NAMES:()=>k0});z(O,tm);import*as Zh from"@cline/llms";import{buildClineSystemPrompt as jh,ContributionRegistry as Xh,createClineTelemetryServiceConfig as Ah,createClineTelemetryServiceMetadata as Ph,createContributionRegistry as Bh,createTool as Yh,emptyWorkspaceManifest as Vh,formatDisplayUserInput as Rh,noopBasicLogger as Fh,normalizeUserInput as Kh,parseUserCommandEnvelope as yh,registerDisposable as Uh}from"@cline/shared";import"@cline/shared/storage";var bj={};N(bj,{isClineAccountActionRequest:()=>AJ,executeClineAccountAction:()=>PJ,RpcClineAccountService:()=>m8,ClineAccountService:()=>I8});function hG(f){if(typeof f!=="object"||f===null||!("error"in f))return;let $=f.error;return typeof $==="string"&&$.trim()?$:void 0}function wj(f,$,J){let W=hG(J);if(W)return W;let H=$.trim();if(H){let Q=H.length>200?`${H.slice(0,200)}...`:H;return`Cline account request failed with status ${f}: ${Q}`}return`Cline account request failed with status ${f}`}class I8{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor(f){let $=f.apiBaseUrl.trim();if(!$)throw Error("apiBaseUrl is required");this.apiBaseUrl=$,this.getAuthTokenFn=f.getAuthToken,this.getCurrentUserIdFn=f.getCurrentUserId,this.getOrganizationMemberIdFn=f.getOrganizationMemberId,this.getHeadersFn=f.getHeaders,this.requestTimeoutMs=f.requestTimeoutMs??30000,this.fetchImpl=f.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance(f){let $=await this.resolveUserId(f);return this.request(`/api/v1/users/${encodeURIComponent($)}/balance`)}async fetchUsageTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/usages`)).items??[]}async fetchPaymentTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}`)}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}/balance`)}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId($,f.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent($)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount(f){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:f?.trim()||null},expectNoContent:!0})}async resolveUserId(f){let $=f?.trim();if($)return $;let W=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(W)return W;let H=await this.fetchMe();if(!H.id?.trim())throw Error("Unable to resolve current user id");return H.id}async resolveOrganizationMemberId(f,$){let J=$?.trim();if(J)return J;let H=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn(f):void 0)?.trim();if(H)return H;let Z=(await this.fetchUserOrganizations()).find((j)=>j.organizationId===f)?.memberId;if(!Z?.trim())throw Error(`Unable to resolve memberId for organization ${f}`);return Z}async request(f,$){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let W=this.getHeadersFn?await this.getHeadersFn():{},H=new AbortController,Q=setTimeout(()=>H.abort(),this.requestTimeoutMs);try{let Z=await this.fetchImpl(new URL(f,this.apiBaseUrl),{method:$?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...W??{}},body:$?.body!==void 0?JSON.stringify($.body):void 0,signal:H.signal});if(Z.status===204||$?.expectNoContent){if(!Z.ok)throw Error(`Cline account request failed with status ${Z.status}`);return}let j=await Z.text(),X;if(j.trim())try{X=JSON.parse(j)}catch{if(!Z.ok)throw Error(wj(Z.status,j,void 0));throw Error("Cline account response was not valid JSON")}if(!Z.ok)throw Error(wj(Z.status,j,X));if(typeof X==="object"&&X!==null){let A=X;if(typeof A.success==="boolean"){if(!A.success)throw Error(A.error||"Cline account request failed");if(A.data!==void 0)return A.data}}if(X===void 0||X===null)throw Error("Cline account response payload was empty");return X}finally{clearTimeout(Q)}}}function AJ(f){return f.action==="clineAccount"}async function PJ(f,$){switch(f.operation){case"fetchMe":return $.fetchMe();case"fetchBalance":return $.fetchBalance(f.userId);case"fetchUsageTransactions":return $.fetchUsageTransactions(f.userId);case"fetchPaymentTransactions":return $.fetchPaymentTransactions(f.userId);case"fetchUserOrganizations":return $.fetchUserOrganizations();case"fetchOrganizationBalance":return $.fetchOrganizationBalance(f.organizationId);case"fetchOrganizationUsageTransactions":return $.fetchOrganizationUsageTransactions({organizationId:f.organizationId,memberId:f.memberId});case"switchAccount":return await $.switchAccount(f.organizationId),{updated:!0};case"fetchFeaturebaseToken":return $.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String(f)}`)}}class m8{executor;constructor(f){this.executor=f}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance(f){return this.request({action:"clineAccount",operation:"fetchBalance",...f?.trim()?{userId:f.trim()}:{}})}async fetchUsageTransactions(f){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchPaymentTransactions(f){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:$})}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:$,...f.memberId?.trim()?{memberId:f.memberId.trim()}:{}})}async switchAccount(f){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:f?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request(f){return(await this.executor.runProviderAction(f)).result}}var Cj={};N(Cj,{createOAuthClientCallbacks:()=>x8});function x8(f){return{onAuth:({url:$,instructions:J})=>{if(f.onOutput?.(J??"Complete sign-in in your browser."),f.openUrl)try{Promise.resolve(f.openUrl($)).catch((W)=>{f.onOpenUrlError?.({url:$,error:W})})}catch(W){f.onOpenUrlError?.({url:$,error:W})}f.onOutput?.($)},onPrompt:f.onPrompt,onServerListening:f.onServerListening,onServerClose:f.onServerClose}}_f();var vj={};N(vj,{startClineDeviceAuth:()=>FH,refreshClineToken:()=>g8,loginClineOAuth:()=>i1,getValidClineCredentials:()=>v8,createClineOAuthProvider:()=>yH,completeClineDeviceAuth:()=>KH});import{getClineEnvironmentConfig as PH}from"@cline/shared";var BJ={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},Ij={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},BH="https://api.workos.com",OG="/auth",Ej=Array.from({length:11},(f,$)=>48801+$),zG=300000,NG=30000,p1=30000,qG=300,wG=5;class Q$ extends Error{status;errorCode;constructor(f,$){super(f);this.name="ClineOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function bG(f){let $=Date.parse(f);if(Number.isNaN($))throw Error(`Invalid expiresAt value: ${f}`);return $}function YH(f,$,J={}){let W=f.userInfo.clineUserId??J.accountId,H=f.refreshToken??J.refresh;if(!H)throw Error("Token response did not include a refresh token");return{access:f.accessToken,refresh:H,expires:bG(f.expiresAt),accountId:W??void 0,email:f.userInfo.email||J.email,metadata:{provider:$,tokenType:f.tokenType,userInfo:f.userInfo}}}async function VH(f){if(!f)return{};return typeof f==="function"?await f():f}function Sj(f,$){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return $;return Math.floor(f)}async function kj(f){await new Promise(($)=>setTimeout($,f))}function RH(f,$){if(!f.success||!f.data?.accessToken)throw Error($);return f.data}async function mj(f,$){let J=await fetch(S$(BH,Ij.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:f}),signal:AbortSignal.timeout($?.requestTimeoutMs??p1)}),W=await J.json().catch(()=>({}));if(!J.ok)throw new Q$(`Device authorization failed: ${J.status}${W.error_description?` - ${W.error_description}`:""}`,{status:J.status,errorCode:W.error});if(!W.device_code||!W.user_code||!W.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:W.device_code,userCode:W.user_code,verificationUri:W.verification_uri,verificationUriComplete:W.verification_uri_complete,expiresInSeconds:Sj(W.expires_in,qG),pollIntervalSeconds:Sj(W.interval,wG)}}async function xj(f){let $=Date.now()+f.expiresInSeconds*1000,J=Math.max(1,f.initialPollIntervalSeconds);while(Date.now()<=$){let W=await fetch(S$(f.workosApiBaseUrl,Ij.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:f.deviceCode,client_id:f.clientId}),signal:AbortSignal.timeout(f.requestTimeoutMs)}),H=await W.json().catch(()=>({}));if(W.ok){if(!H.access_token||!H.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:H.access_token,refreshToken:H.refresh_token,tokenType:H.token_type??"Bearer"}}switch(H.error){case"authorization_pending":{await kj(J*1000);break}case"slow_down":{J+=1,await kj(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new Q$(H.error_description||"WorkOS authorization failed",{status:W.status,errorCode:H.error});default:throw new Q$(`WorkOS token polling failed: ${W.status}${H.error_description?` - ${H.error_description}`:""}`,{status:W.status,errorCode:H.error})}f.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function gj(f,$,J){let W={accessToken:f.accessToken,refreshToken:f.refreshToken},H=await fetch(S$($.apiBaseUrl,BJ.register),{method:"POST",headers:{"Content-Type":"application/json",...await VH($.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout($.requestTimeoutMs??p1)});if(!H.ok){let Z=await H.text().catch(()=>""),j=b1(Z);throw new Q$(`Token registration failed: ${H.status}${j.message?` - ${j.message}`:""}`,{status:H.status,errorCode:j.code})}let Q=await H.json();return YH(RH(Q,"Invalid token exchange response"),J??$.provider)}async function CG(f,$,J,W){let H={grant_type:"authorization_code",code:f,client_type:"extension",redirect_uri:$,provider:W??J.provider},Q=await fetch(S$(J.apiBaseUrl,BJ.token),{method:"POST",headers:{"Content-Type":"application/json",...await VH(J.headers)},body:JSON.stringify(H),signal:AbortSignal.timeout(J.requestTimeoutMs??p1)});if(!Q.ok){let j=await Q.text().catch(()=>""),X=b1(j);throw new Q$(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let Z=await Q.json();return YH(RH(Z,"Invalid token exchange response"),W??J.provider)}async function i1(f){F0(f.telemetry,f.provider??"cline");let $=f.useWorkOSDeviceAuth??!0,J=f.callbackPorts?.length?f.callbackPorts:Ej,W=f.callbackPath??OG,H=$?null:await N0({ports:J,callbackPath:W,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),Q=H?.callbackUrl||`http://127.0.0.1:${J[0]??Ej[0]}${W}`;try{let Z;if($){let j=PH().workOsClientId,X=await mj(j,f);f.callbacks.onAuth({url:X.verificationUriComplete??X.verificationUri,instructions:`Enter this code in your browser: ${X.userCode}`});let A=await xj({clientId:j,deviceCode:X.deviceCode,expiresInSeconds:X.expiresInSeconds,initialPollIntervalSeconds:X.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??p1,workosApiBaseUrl:BH,onProgress:f.callbacks.onProgress});Z=await gj(A,f,f.provider)}else{let j=new URL(S$(f.apiBaseUrl,BJ.authorize));j.searchParams.set("client_type","extension"),j.searchParams.set("callback_url",Q),j.searchParams.set("redirect_uri",Q),f.callbacks.onAuth({url:j.toString(),instructions:"Continue the authentication process in your browser."});let X,A=f.provider,P=await C1({waitForCallback:H?.waitForCallback??(async()=>null),cancelWait:H?.cancelWait??(()=>{}),onManualCodeInput:f.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(P.error)throw Error(`OAuth error: ${P.error}`);if(X=P.code,A=P.provider??A,!X){let B=await f.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),Y=w1(B,{includeProvider:!0});X=Y.code,A=Y.provider??A}if(!X)throw Error("Missing authorization code");Z=await CG(X,Q,f,A)}return K0(f.telemetry,f.provider??"cline"),U0(f.telemetry,{id:Z.accountId,email:Z.email,provider:f.provider??"cline"}),Z}catch(Z){throw y0(f.telemetry,f.provider??"cline",Z instanceof Error?Z.message:String(Z)),Z}finally{H?.close()}}async function FH(f){return await mj(PH().workOsClientId,f)}async function KH(f){let $=f.provider??"cline";F0(f.telemetry,$);try{let J=await xj({clientId:PH().workOsClientId,deviceCode:f.deviceCode,expiresInSeconds:f.expiresInSeconds,initialPollIntervalSeconds:f.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??p1,workosApiBaseUrl:BH}),W=await gj(J,{apiBaseUrl:f.apiBaseUrl,headers:f.headers,requestTimeoutMs:f.requestTimeoutMs,provider:f.provider},f.provider);return K0(f.telemetry,$),U0(f.telemetry,{id:W.accountId,email:W.email,provider:$}),W}catch(J){throw y0(f.telemetry,$,J instanceof Error?J.message:String(J)),J}}async function g8(f,$){let J=await fetch(S$($.apiBaseUrl,BJ.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await VH($.headers)},body:JSON.stringify({refreshToken:f.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout($.requestTimeoutMs??p1)});if(!J.ok){let Q=await J.text().catch(()=>""),Z=b1(Q);throw new Q$(`Token refresh failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let W=await J.json(),H=f.metadata?.provider??$.provider;return YH(RH(W,"Invalid token refresh response"),H,f)}async function v8(f,$,J){if(!f)return null;let W=J?.refreshBufferMs??zG,H=J?.retryableTokenGraceMs??NG;if(J?.forceRefresh!==!0&&!k$(f,W))return f;try{return await g8(f,$)}catch(Z){if(Z instanceof Q$&&Z.isLikelyInvalidGrant())return x0($.telemetry,$.provider??"cline","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function yH(f){return{id:"cline",name:"Cline Account",usesCallbackServer:!(f.useWorkOSDeviceAuth??!0),async login($){return i1({...f,callbacks:$})},async refreshToken($){return g8($,f)},getApiKey($){return`workos:${$.access}`}}}_f();var dj={};N(dj,{refreshOpenAICodexToken:()=>u8,openaiCodexOAuthProvider:()=>TH,normalizeOpenAICodexCredentials:()=>GH,loginOpenAICodex:()=>n1,isOpenAICodexTokenExpired:()=>UH,getValidOpenAICodexCredentials:()=>c8,OPENAI_CODEX_OAUTH_CONFIG:()=>e});import{nanoid as EG}from"nanoid";var e={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class YJ extends Error{status;errorCode;constructor(f,$){super(f);this.name="OpenAICodexOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function SG(f,$,J=e.redirectUri){let W=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:f,code_verifier:$,redirect_uri:J}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!W.ok)return{type:"failed"};let H=await W.json();if(!H.access_token||!H.refresh_token||typeof H.expires_in!=="number")return{type:"failed"};return{type:"success",access:H.access_token,refresh:H.refresh_token,expires:Date.now()+H.expires_in*1000,email:H.email,idToken:H.id_token}}async function kG(f){try{let $=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:f,client_id:e.clientId}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!$.ok){let W=await $.text().catch(()=>""),H=b1(W);throw new YJ(`Token refresh failed: ${$.status}${H.message?` - ${H.message}`:""}`,{status:$.status,errorCode:H.code})}let J=await $.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch($){if($ instanceof YJ)throw $;return{type:"failed"}}}async function IG(f="pi"){let{verifier:$,challenge:J}=await N6(),W=EG(32),H=new URL(e.authorizationEndpoint);return H.searchParams.set("response_type","code"),H.searchParams.set("client_id",e.clientId),H.searchParams.set("redirect_uri",e.redirectUri),H.searchParams.set("scope",e.scopes),H.searchParams.set("code_challenge",J),H.searchParams.set("code_challenge_method","S256"),H.searchParams.set("state",W),H.searchParams.set("id_token_add_organizations","true"),H.searchParams.set("codex_cli_simplified_flow","true"),H.searchParams.set("originator",f),{verifier:$,state:W,url:H.toString()}}function mG(){try{let f=new URL(e.redirectUri),$=f.port.length>0?Number.parseInt(f.port,10):e.callbackPort;return{host:f.hostname||"localhost",port:Number.isFinite($)?$:e.callbackPort,callbackPath:f.pathname||"/auth/callback",redirectUri:f.toString()}}catch{return{host:"localhost",port:e.callbackPort,callbackPath:"/auth/callback",redirectUri:e.redirectUri}}}function uj(f,$){let J=$?Kf($):Kf(f),W=J?J:Kf(f),Q=W?.[e.jwtClaimPath]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=W?.organizations;if(Array.isArray(Z)&&Z.length>0){let X=Z[0];if(typeof X?.id==="string"&&X.id.length>0)return X.id}let j=W?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return null}function cj(f,$){let J=uj(f.access,f.idToken)??$?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:f.access,refresh:f.refresh||$?.refresh||"",expires:f.expires,accountId:J,email:f.email??$?.email,metadata:{...$?.metadata??{},provider:"openai-codex"}}}async function n1(f){F0(f.telemetry,"openai-codex");let $=mG(),{verifier:J,state:W,url:H}=await IG(f.originator),Q=await N0({host:$.host,ports:[$.port],callbackPath:$.callbackPath,expectedState:W});f.onAuth({url:H,instructions:"Continue the authentication process in your browser."});let Z;try{let j=await C1({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:f.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(j.state&&j.state!==W)throw Error("State mismatch");if(Z=j.code,!Z){let P=await f.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=w1(P,{allowHashCodeState:!0});if(B.state&&B.state!==W)throw Error("State mismatch");Z=B.code}if(!Z)throw Error("Missing authorization code");let X=await SG(Z,J,$.redirectUri);if(X.type!=="success")throw Error("Token exchange failed");let A=cj(X);return K0(f.telemetry,"openai-codex"),U0(f.telemetry,{id:A.accountId,email:A.email,provider:"openai-codex"}),A}catch(j){throw y0(f.telemetry,"openai-codex",j instanceof Error?j.message:String(j)),j}finally{Q.close()}}async function u8(f,$){let J=await kG(f);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=cj(J,$);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function c8(f,$){if(!f)return null;let J=$?.refreshBufferMs??e.refreshBufferMs,W=$?.retryableTokenGraceMs??e.retryableTokenGraceMs;if($?.forceRefresh!==!0&&!k$(f,J))return f;try{return await u8(f.refresh,f)}catch(Q){if(Q instanceof YJ&&Q.isLikelyInvalidGrant())return x0($?.telemetry,"openai-codex","invalid_grant"),null;if(f.expires-Date.now()>W)return f;return null}}function UH(f,$=e.refreshBufferMs){return k$(f,$)}function GH(f){let $=f.accountId??uj(f.access);if(!$)throw Error("Failed to extract accountId from token");return{...f,accountId:$,metadata:{...f.metadata??{},provider:"openai-codex"}}}var TH={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login(f){return n1({onAuth:f.onAuth,onPrompt:f.onPrompt,onProgress:f.onProgress,onManualCodeInput:f.onManualCodeInput})},async refreshToken(f){return u8(f.refresh,f)},getApiKey(f){return f.access}};var YA={};N(YA,{ClineCore:()=>F4});function rj(f){if(f===!0)return{};if(!f)return;return f}function lj(f){if(f==="user")return"global";return f}class DH{getService;constructor(f){this.getService=f}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent(f){let $=this.getService().ingestEvent(f);return{event:$.event,duplicate:$.duplicate,matchedSpecIds:$.matchedSpecs.map((J)=>J.specId),queuedRuns:$.queuedRuns,suppressions:$.suppressions}}listEvents(f){return this.getService().listEventLogs(f)}getEvent(f){return this.getService().getEventLog(f)}listSpecs(f){return this.getService().listSpecs(f)}listRuns(f){return this.getService().listRuns(f)}}function pj(f){let{host:$}=f;return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),H=await $.startSession({source:J.source?.trim()||Ff.CLI,interactive:!1,config:{providerId:d1(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:vG(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:f.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:H.sessionId,startResult:{sessionId:H.sessionId,manifestPath:H.manifestPath,messagesPath:H.messagesPath}}},async sendSession(J,W){let H=await $.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content),delivery:W.delivery});if(!H)throw Error("ClineCore automation runtime returned no result");return{result:gG(H)}},async abortSession(J){return await $.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function VJ(f){let $=xG(f.automationService,f.automation),J=f.context?.client??(f.clientName?{name:f.clientName}:void 0),W=f.context?.user??(f.distinctId?{distinctId:f.distinctId}:void 0),H=f.context?.logger??f.logger,Q=f.context?.telemetry??f.telemetry;if(!$&&!J&&!W&&!H&&!Q)return f.context;return{...f.context??{},...J?{client:J}:{},...W?{user:W}:{},...H?{logger:H}:{},...Q?{telemetry:Q}:{},...$?{automation:$}:{}}}function xG(f,$){if(!f)return;return{ingestEvent:(J)=>{$.ingestEvent(J)}}}function gG(f){return{text:f.text,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost},inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function vG(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}var YX={};N(YX,{createCoreSettingsService:()=>d$,CoreSettingsService:()=>j$});import{existsSync as zH}from"node:fs";import{basename as AX,isAbsolute as RT,relative as FT}from"node:path";var HX={};N(HX,{resolveWorkflowsConfigSearchPaths:()=>s8,resolveSkillsConfigSearchPaths:()=>a8,resolveRulesConfigSearchPaths:()=>t8,parseWorkflowConfigFromMarkdown:()=>n8,parseSkillConfigFromMarkdown:()=>p8,parseRuleConfigFromMarkdown:()=>i8,createWorkflowsConfigDefinition:()=>f4,createUserInstructionConfigService:()=>Z$,createSkillsConfigDefinition:()=>o8,createRulesConfigDefinition:()=>e8,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>l8,UnifiedConfigFileWatcher:()=>u$,SKILLS_CONFIG_DIRECTORY_NAME:()=>r8,RULES_CONFIG_DIRECTORY_NAME:()=>UJ});import{createHash as uG}from"node:crypto";import{watch as cG}from"node:fs";import{readdir as dG,readFile as rG}from"node:fs/promises";import{join as lG}from"node:path";function pG(f){return uG("sha1").update(f).digest("hex")}function aj(f){return Boolean(f&&typeof f==="object"&&"code"in f)}function ij(f){return aj(f)&&f.code==="ENOENT"}function nj(f){return aj(f)&&(f.code==="EACCES"||f.code==="EPERM")}class u${definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor(f,$){if(f.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=f,this.debounceMs=$?.debounceMs??75,this.emitParseErrors=$?.emitParseErrors??!1;for(let J of f){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let W of J.directories){let H=this.baseTypesByDirectory.get(W);if(H)H.add(J.type);else this.baseTypesByDirectory.set(W,new Set([J.type]))}}}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let f of this.watchersByDirectory.values())f.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let f of this.definitions)await this.refreshTypeInternal(f)})}async refreshType(f){let $=this.definitionsByType.get(f);if(!$)throw Error(`Unknown unified config type '${f}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal($)})}getSnapshot(f){let $=this.recordsByType.get(f);return new Map([...$?.entries()??[]].map(([J,W])=>[J,{...W}]))}getAllSnapshots(){let f=new Map;for(let[$,J]of this.recordsByType.entries())f.set($,new Map([...J.entries()].map(([W,H])=>[W,{...H}])));return f}emit(f){for(let $ of this.listeners)$(f)}enqueueRefresh(f){return this.refreshQueue=this.refreshQueue.then(f,f),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let f=this.buildDesiredTypesByDirectory();for(let[$,J]of this.watchersByDirectory.entries()){if(f.has($))continue;J.close(),this.watchersByDirectory.delete($)}this.watchedTypesByDirectory=f;for(let $ of f.keys()){if(this.watchersByDirectory.has($))continue;try{let J=cG($,()=>{let W=this.watchedTypesByDirectory.get($);if(!W)return;for(let H of W)this.pendingTypes.add(H);this.scheduleFlush()});this.watchersByDirectory.set($,J),J.on("error",(W)=>{let H=this.watchedTypesByDirectory.get($);if(!H)return;for(let Q of H)this.emit({kind:"error",type:Q,error:W,filePath:$})})}catch(J){if(!ij(J)&&!nj(J)){let W=f.get($);if(!W)continue;for(let H of W)this.emit({kind:"error",type:H,error:J,filePath:$})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let f=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let $ of f){let J=this.definitionsByType.get($);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal(f){let{records:$,discoveredDirectories:J}=await this.loadDefinition(f),W=this.recordsByType.get(f.type)??new Map;for(let[H,Q]of W.entries()){if($.has(H))continue;this.emit({kind:"remove",type:f.type,id:H,filePath:Q.filePath})}for(let[H,Q]of $.entries()){let Z=W.get(H);if(Z&&Z.filePath===Q.filePath&&Z.fingerprint===Q.fingerprint)continue;this.emit({kind:"upsert",record:{type:Q.type,id:H,item:Q.item,filePath:Q.filePath}})}if(this.recordsByType.set(f.type,$),this.discoveredDirectoriesByType.set(f.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition(f){let $=new Map,J=new Set;for(let W of f.directories){J.add(W);let H=f.discoverFiles?await f.discoverFiles(W):await this.readDirectoryFileCandidates(W);for(let Q of H){let{fileName:Z,filePath:j}=Q;if(J.add(Q.directoryPath),f.includeFile&&!f.includeFile(Z,j))continue;try{let X=await rG(j,"utf8"),A={type:f.type,directoryPath:Q.directoryPath,fileName:Z,filePath:j,content:X},P=f.parseFile(A),B=f.resolveId(P,A).trim();if(!B)continue;$.set(B,{type:f.type,id:B,item:P,filePath:j,fingerprint:pG(X)})}catch(X){if(this.emitParseErrors)this.emit({kind:"error",type:f.type,error:X,filePath:j})}}}return{records:$,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let f=new Map;for(let[$,J]of this.baseTypesByDirectory.entries())f.set($,new Set(J));for(let[$,J]of this.discoveredDirectoriesByType.entries())for(let W of J){let H=f.get(W);if(H)H.add($);else f.set(W,new Set([$]))}return f}async readDirectoryFileCandidates(f){try{return(await dG(f,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:f,fileName:J.name,filePath:lG(f,J.name)})).sort((J,W)=>J.fileName.localeCompare(W.fileName))}catch($){if(ij($)||nj($))return[];throw $}}}import{readdir as _H,readFile as iG,stat as tj}from"node:fs/promises";import{basename as c$,dirname as nG,extname as MH,join as hf}from"node:path";import{RULES_CONFIG_DIRECTORY_NAME as UJ,resolveRulesConfigSearchPaths as aG,resolveSkillsConfigSearchPaths as tG,resolveWorkflowsConfigSearchPaths as sG,SKILLS_CONFIG_DIRECTORY_NAME as r8,WORKFLOWS_CONFIG_DIRECTORY_NAME as l8}from"@cline/shared/storage";import oG from"yaml";var RJ="SKILL.md",eG="managed.json",fT=new Set([".md",".markdown",".txt"]);function LH(f){return f.trim().toLowerCase()}function d8(f){let $=f;return $?.code==="ENOENT"||$?.code==="EACCES"||$?.code==="EPERM"}function FJ(f){return fT.has(MH(f).toLowerCase())}async function hH(f){try{let $=await _H(f,{withFileTypes:!0}),J=[];for(let W of $){if(!W.isDirectory())continue;let H=hf(f,W.name),Q=hf(H,eG);try{let Z=await iG(Q,"utf8"),j=JSON.parse(Z);if(j&&typeof j==="object")J.push(H)}catch(Z){if(d8(Z))continue;if(Z?.name==="SyntaxError")continue;throw Z}}return J.sort((W,H)=>W.localeCompare(H))}catch($){if(d8($))return[];throw $}}function OH(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,W,H]=J;try{let Q=oG.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:H,hadFrontmatter:!0}}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);return{data:{},body:f,hadFrontmatter:!0,parseError:Z}}}function KJ(f,$,J){if(f===void 0||f===null){if(J)throw Error(`Missing required frontmatter field '${$}'.`);return}if(typeof f!=="string")throw Error(`Frontmatter field '${$}' must be a string.`);let W=f.trim();if(!W&&J)throw Error(`Frontmatter field '${$}' cannot be empty.`);return W||void 0}function a1(f,$){if(f===void 0||f===null)return;if(typeof f!=="boolean")throw Error(`Frontmatter field '${$}' must be a boolean.`);return f}function p8(f,$){let{data:J,body:W,parseError:H}=OH(f);if(H)throw Error(`Failed to parse YAML frontmatter: ${H}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in skill file.");let j=KJ(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing skill name.");return{name:j,description:KJ(J.description,"description",!1),disabled:a1(J.disabled,"disabled")??(a1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function i8(f,$){let{data:J,body:W,parseError:H}=OH(f);if(H)throw Error(`Failed to parse YAML frontmatter: ${H}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in rule file.");let Z=KJ(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing rule name.");return{name:Z,disabled:a1(J.disabled,"disabled")??(a1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function n8(f,$){let{data:J,body:W,parseError:H}=OH(f);if(H)throw Error(`Failed to parse YAML frontmatter: ${H}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in workflow file.");let Z=KJ(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing workflow name.");return{name:Z,disabled:a1(J.disabled,"disabled")??(a1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function a8(f){return tG(f)}function t8(f){return aG(f)}function s8(f){return sG(f)}async function sj(f){if(c$(f)===".cline"){let $=await hH(f);return(await Promise.all($.map((W)=>sj(hf(W,r8))))).flat()}try{let $=await _H(f,{withFileTypes:!0}),J=[];for(let W of $){if(W.isFile()&&W.name===RJ){J.push({directoryPath:f,fileName:W.name,filePath:hf(f,W.name)});continue}if(W.isDirectory())J.push({directoryPath:hf(f,W.name),fileName:RJ,filePath:hf(f,W.name,RJ)})}return J}catch($){if(d8($))return[];throw $}}async function yJ(f){if(c$(f)===".cline"){let $=await hH(f);return(await Promise.all($.map((W)=>yJ(hf(W,"rules.md"))))).flat()}try{if((await tj(f)).isFile())return[{directoryPath:nG(f),fileName:c$(f),filePath:f}]}catch($){if(!d8($))throw $}try{let J=(await _H(f,{withFileTypes:!0})).filter((H)=>H.isFile()&&FJ(H.name)).map((H)=>({directoryPath:f,fileName:H.name,filePath:hf(f,H.name)})),W=hf(f,"AGENTS.md");try{if((await tj(W)).isFile()){if(!J.some((Z)=>Z.fileName==="AGENTS.md"))J.push({directoryPath:f,fileName:"AGENTS.md",filePath:W})}}catch{}return J}catch($){if(d8($))return[];throw $}}async function $T(f){if(c$(f)===".cline"){let $=await hH(f);return(await Promise.all($.map((W)=>yJ(hf(W,l8))))).flat()}return yJ(f)}function o8(f){let $=f?.directories??a8(f?.workspacePath),J=f?.workspacePath?hf(f.workspacePath,".cline"):void 0;return{type:"skill",directories:J?[...$,J]:$,discoverFiles:sj,includeFile:(W)=>W===RJ,parseFile:(W)=>p8(W.content,c$(W.directoryPath)),resolveId:(W)=>LH(W.name)}}function e8(f){let $=f?.directories??t8(f?.workspacePath),J=f?.workspacePath?hf(f.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...$,J]:$,discoverFiles:yJ,includeFile:(W,H)=>W===".clinerules"||FJ(W)||FJ(H),parseFile:(W)=>i8(W.content,c$(W.filePath,MH(W.filePath))),resolveId:(W)=>LH(W.name)}}function f4(f){let $=f?.directories??s8(f?.workspacePath),J=f?.workspacePath?hf(f.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...$,J]:$,discoverFiles:$T,includeFile:(W)=>FJ(W),parseFile:(W)=>n8(W.content,c$(W.filePath,MH(W.filePath))),resolveId:(W)=>LH(W.name)}}function oj(f){let $=[o8(f?.skills),e8(f?.rules),f4(f?.workflows)];return new u$($,{debounceMs:f?.debounceMs,emitParseErrors:f?.emitParseErrors})}import{truncateSplit as ej}from"@cline/shared";function JT(f,$){if(f.description?.trim())return ej(f.description,".");if($==="workflow")return;return ej(f.instructions,".")}function WT(f){return f.disabled!==!0}function fX(f,$){return[...f.getSnapshot($).entries()].map(([J,W])=>({id:J,record:W})).filter(({record:J})=>WT(J.item)).map(({id:J,record:W})=>({id:J,name:W.item.name,instructions:W.item.instructions,description:JT(W.item,$),kind:$})).sort((J,W)=>J.name.localeCompare(W.name))}function $4(f){let $=new Map;for(let J of[...fX(f,"workflow"),...fX(f,"skill")])if(!$.has(J.name))$.set(J.name,J);return[...$.values()].sort((J,W)=>J.name.localeCompare(W.name))}function $X(f,$){if(!f.startsWith("/")||f.length<2)return f;let J=f.match(/^\/(\S+)/);if(!J)return f;let W=J[1];if(!W)return f;let H=W.length+1,Q=f.slice(H),Z=$4($).find((j)=>j.name===W);return Z?`${Z.instructions}${Q}`:f}function GJ(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function HT(f){if(!f||f.length===0)return;let $=f.map(GJ).filter((J)=>J.length>0);return $.length>0?new Set($):void 0}function QT(f,$,J){if(!J)return!0;let W=GJ(f),H=GJ($),Q=W.includes(":")?W.split(":").at(-1)??W:W,Z=H.includes(":")?H.split(":").at(-1)??H:H;return J.has(W)||J.has(H)||J.has(Q)||J.has(Z)}function J4(f,$){let J=HT($);return[...f.getSnapshot("skill").entries()].map(([H,Q])=>{let Z=Q.item;return{id:H,name:Z.name.trim(),description:Z.description?.trim(),disabled:Z.disabled===!0,skill:Z}}).filter((H)=>QT(H.id,H.name,J))}function ZT(f,$){return J4(f,$).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,W)=>J.localeCompare(W))}function jT(f,$,J){let W=GJ($);if(!W)return{error:"Missing skill name."};let H=J4(f,J),Q=H.find((P)=>P.id===W);if(Q){let{skill:P}=Q;if(P.disabled===!0)return{error:`Skill "${P.name}" is configured but disabled.`};return{id:Q.id,skill:P}}let Z=W.includes(":")?W.split(":").at(-1)??W:W,j=H.filter(({id:P})=>{if(P===Z)return!0;return P.endsWith(`:${Z}`)}),X=j.filter(({skill:P})=>P.disabled!==!0);if(X.length===1){let{id:P,skill:B}=X[0];return{id:P,skill:B}}if(X.length>1)return{error:`Skill "${$}" is ambiguous. Use one of: ${X.map(({id:P})=>P).join(", ")}`};if(j.length===1){let{skill:P}=j[0];return{error:`Skill "${P.name}" is configured but disabled.`}}if(j.length>1)return{error:`Skill "${$}" is ambiguous, and all matches are disabled: ${j.map(({id:P})=>P).join(", ")}`};let A=ZT(f,J);return{error:A.length>0?`Skill "${$}" not found. Available skills: ${A.join(", ")}`:"No skills are currently available."}}function XT(f,$=Promise.resolve(),J){let W=new Set,H=async(Q,Z)=>{await $;let j=jT(f,Q,J);if("error"in j)return j.error;let{id:X,skill:A}=j;if(W.has(X))return`Skill "${A.name}" is already running.`;W.add(X);try{let P=Z?.trim(),B=P?`
457
+ <command-args>${P}</command-args>`:"",Y=A.description?.trim()?`Description: ${A.description.trim()}
458
458
 
459
- `:"";return`<command-name>${X.name}</command-name>${Y}
459
+ `:"";return`<command-name>${A.name}</command-name>${B}
460
460
  <command-instructions>
461
- ${B}${X.instructions}
462
- </command-instructions>`}finally{H.delete(P)}};return Object.defineProperty(W,"configuredSkills",{get:()=>s8(f,J).map(({skill:Q,...Z})=>Z),enumerable:!0,configurable:!1}),W}function Sj(f){let $=f.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[f.includeRules?"rules":void 0,f.registerSkillsTool?"tools":void 0,f.includeSkills||f.includeWorkflows?"commands":void 0].filter((H)=>Boolean(H))},async setup(H){if(await $,f.includeRules)H.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>jH(f.watcher)});if(f.registerSkillsTool)H.registerTool(h$(wG(f.watcher,$,f.allowedSkillNames)));for(let W of t8(f.watcher).filter((Q)=>Q.kind==="skill"&&f.includeSkills||Q.kind==="workflow"&&f.includeWorkflows))H.registerCommand({name:W.name,description:W.description,handler:(Q)=>{let Z=Q.trim();return Z?`${W.instructions}
461
+ ${Y}${A.instructions}
462
+ </command-instructions>`}finally{W.delete(X)}};return Object.defineProperty(H,"configuredSkills",{get:()=>J4(f,J).map(({skill:Q,...Z})=>Z),enumerable:!0,configurable:!1}),H}function JX(f){let $=f.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[f.includeRules?"rules":void 0,f.registerSkillsTool?"tools":void 0,f.includeSkills||f.includeWorkflows?"commands":void 0].filter((W)=>Boolean(W))},async setup(W){if(await $,f.includeRules)W.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>X5(f.watcher)});if(f.registerSkillsTool)W.registerTool(M$(XT(f.watcher,$,f.allowedSkillNames)));for(let H of $4(f.watcher).filter((Q)=>Q.kind==="skill"&&f.includeSkills||Q.kind==="workflow"&&f.includeWorkflows))W.registerCommand({name:H.name,description:H.description,handler:(Q)=>{let Z=Q.trim();return Z?`${H.instructions}
463
463
 
464
- ${Z}`:W.instructions}})}}}class kj{watcher;ready;stopped=!1;constructor(f){this.watcher=bj(f)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType(f){await this.start(),await this.watcher.refreshType(f)}listRecords(f){return[...this.watcher.getSnapshot(f).entries()].map(([$,J])=>({type:f,id:$,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return t8(this.watcher)}resolveRuntimeSlashCommand(f){return Ej(f,this.watcher)}hasConfiguredSkills(f){return s8(this.watcher,f).length>0}createExtension(f){return Sj({...f,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function H$(f){return new kj(f)}import{readFile as CG,writeFile as EG}from"node:fs/promises";import xj from"yaml";function SG(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,H,W]=J,Q=xj.parse(H);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:W,hadFrontmatter:!0}}function Ij(f,$){return`---
465
- ${xj.stringify(f).trimEnd()}
464
+ ${Z}`:H.instructions}})}}}class WX{watcher;ready;stopped=!1;constructor(f){this.watcher=oj(f)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType(f){await this.start(),await this.watcher.refreshType(f)}listRecords(f){return[...this.watcher.getSnapshot(f).entries()].map(([$,J])=>({type:f,id:$,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return $4(this.watcher)}resolveRuntimeSlashCommand(f){return $X(f,this.watcher)}hasConfiguredSkills(f){return J4(this.watcher,f).length>0}createExtension(f){return JX({...f,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function Z$(f){return new WX(f)}import{readFile as AT,writeFile as PT}from"node:fs/promises";import ZX from"yaml";function BT(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,W,H]=J,Q=ZX.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:H,hadFrontmatter:!0}}function QX(f,$){return`---
465
+ ${ZX.stringify(f).trimEnd()}
466
466
  ---
467
- ${$}`}function kG(f,$){let{data:J,body:H,hadFrontmatter:W}=SG(f);if(!W&&$)return f;if($){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return H;return Ij(J,H)}return J.disabled=!0,Ij(J,H)}async function gj({filePath:f,enabled:$}){let J=await CG(f,"utf8"),H=kG(J,$);return await EG(f,H),{filePath:f,enabled:$,disabled:!$}}F0();var vj={};N(vj,{listPluginTools:()=>o8});F0();function mG(f,$){if(!f.setup)return[];let J=[],H={registerTool:(W)=>J.push(W),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return f.setup(H,{workspaceInfo:$}),J}async function o8(f){let $=E$({workspacePath:f.workspacePath,cwd:f.cwd}),J=uf(f.disabledToolNames),H=[];for(let W of $){let Q=await D0([W],{cwd:f.cwd,providerId:f.providerId,modelId:f.modelId});for(let Z of Q.plugins)for(let j of mG(Z,{rootPath:f.workspacePath}))H.push({name:j.name,pluginName:Z.name,path:W,source:W.startsWith(f.workspacePath)?"workspace-plugin":"global-plugin",enabled:!J.has(j.name),description:j.description?.trim()||void 0})}return H.sort((W,Q)=>{let Z=W.name.localeCompare(Q.name);if(Z!==0)return Z;return W.path.localeCompare(Q.path)})}function _5(f,$){if(!$)return"global";let J=xG($,f);return!J.startsWith("..")&&!IG(J)?"workspace":"global"}function DJ(f){return[...f].sort(($,J)=>{let H=(W)=>{switch(W){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if($.source!==J.source)return H($.source)-H(J.source);return $.name.localeCompare(J.name)})}function dj(f){return f.workspaceRoot?.trim()||f.cwd?.trim()||""}async function cj(f,$){if(f.userInstructionService)return await $(f.userInstructionService);let J=dj(f);if(!J)return await $(void 0);let H=H$({skills:{workspacePath:J},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await H.start(),await $(H)}finally{H.stop()}}function gG(f,$){if(!f)return;let J=f.listRecords("skill");if($.id){let H=J.find((W)=>W.id===$.id);if(H)return H}for(let H of J)if(H.filePath===$.path||H.item.name===$.name||H.id===$.name)return H;return}class W${async list(f={}){return await cj(f,async($)=>{let J=dj(f),H=[],W=[],Q=[],Z=[];if($){for(let j of $.listRecords("workflow")){let P=j.item;H.push({id:j.id,name:P.name,path:j.filePath,enabled:P.disabled!==!0,kind:"workflow",source:_5(j.filePath,J),description:P.instructions,toggleable:!1})}for(let j of $.listRecords("rule")){let P=j.item;W.push({id:j.id,name:P.name,path:j.filePath,enabled:P.disabled!==!0,kind:"rule",source:_5(j.filePath,J),description:P.instructions,toggleable:!1})}for(let j of $.listRecords("skill")){let P=j.item;Q.push({id:j.id,name:P.name,path:j.filePath,enabled:P.disabled!==!0,kind:"skill",source:_5(j.filePath,J),description:P.description,toggleable:!0})}}if(J)try{for(let j of await o8({workspacePath:J,cwd:f.cwd,providerId:f.availabilityContext?.providerId,modelId:f.availabilityContext?.modelId}))Z.push({id:`${j.pluginName}:${j.name}:${j.path}`,name:j.name,path:j.path,enabled:j.enabled,kind:"tool",source:j.source,description:j.description,toggleable:!0})}catch{}return{workflows:DJ(H.filter((j)=>M5(j.path))),rules:DJ(W.filter((j)=>M5(j.path))),skills:DJ(Q.filter((j)=>M5(j.path))),tools:DJ(Z)}})}async toggle(f){if(f.type==="skills")return await cj(f,async($)=>{let J=gG($,f),H=J?.filePath;if(!H)throw Error(`Unable to resolve skill setting '${f.id??f.name??uj(f.path??"")}'.`);let W=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,Q=f.enabled??(W!==void 0?!W:void 0);if(Q===void 0)throw Error(`Cannot determine toggle state for skill '${f.id??f.name??uj(f.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await gj({filePath:H,enabled:Q}),await $?.refreshType("skill"),{snapshot:await this.list({...f,userInstructionService:$}),changedTypes:["skills"]}});if(f.type==="tools"){if(!f.name?.trim())throw Error("Tool settings toggle requires a tool name.");if(f.enabled===void 0)n4(f.name);else c3(f.name,!f.enabled);return{snapshot:await this.list(f),changedTypes:["tools"]}}throw Error(`Settings type '${f.type}' does not support toggles.`)}}function v$(){return new W$}function lj(f){return{async list($){let J=f;if(J.listSettings)return await J.listSettings($);return await v$().list($)},async toggle($){let J=f;if(J.toggleSetting)return await J.toggleSetting($);return await v$().toggle($)}}}function pj(f){function $(){let J=f.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return $().list(J)},update(J){return $().update(J)},delete(J){return $().delete(J)}}}var ij={};N(ij,{splitCoreSessionConfig:()=>e8});function e8(f){let{hooks:$,logger:J,telemetry:H,extensionContext:W,extraTools:Q,extensions:Z,onTeamEvent:j,onConsecutiveMistakeLimitReached:P,checkpoint:X,compaction:V,...Y}=f,B={};if($)B.hooks=$;if(J)B.logger=J;if(H)B.telemetry=H;if(W)B.extensionContext=W;if(Q)B.extraTools=Q;if(Z)B.extensions=Z;if(j)B.onTeamEvent=j;if(P)B.onConsecutiveMistakeLimitReached=P;if(X?.createCheckpoint)B.checkpoint=X;if(V?.compact)B.compaction=V;let A=Object.keys(B).length>0?B:void 0;return{config:{...Y,...X?{checkpoint:{enabled:X.enabled}}:{},...V?{compaction:{enabled:V.enabled,strategy:V.strategy,thresholdRatio:V.thresholdRatio,reserveTokens:V.reserveTokens,preserveRecentTokens:V.preserveRecentTokens,contextWindowTokens:V.contextWindowTokens,summarizer:V.summarizer}}:{}},...A?{localRuntime:A}:{}}}function nj(f){let $=f.config;return"providerId"in $?{...f,config:{...$,...vG(f.localRuntime)},localRuntime:f.localRuntime}:f}function L5(f,$={}){let J=e8(f.config),H=Bf($.defaultCapabilities,f.capabilities),W=uG(J.localRuntime,f.localRuntime),Q=$.withExtensionContext?.(W?.extensionContext);if(Q)W={...W??{},extensionContext:Q};return{...f,...J,...W?{localRuntime:W}:{},...H?{capabilities:H}:{}}}function vG(f){if(!f)return{};let{modelCatalogDefaults:$,userInstructionService:J,configExtensions:H,onTeamRestored:W,...Q}=f;return Q}function uG(...f){let $={};for(let J of f)if(J)Object.assign($,J);return Object.keys($).length>0?$:void 0}Kf();function aj(f){let $=f.input.config.telemetry??f.telemetry;if(!$)return;$.capture({event:g.SESSION.STARTED,properties:{sessionId:f.sessionId,source:f.input.source??Vf.CORE,providerId:f.input.config.providerId,modelId:f.input.config.modelId,enableTools:f.input.config.enableTools,enableSpawnAgent:f.input.config.enableSpawnAgent,enableAgentTeams:f.input.config.enableAgentTeams,clientName:f.clientName,runtimeAddress:f.runtimeAddress}})}function f4(f){return!!f&&typeof f==="object"&&!Array.isArray(f)}function z5(f){let $=f?.trim();return $?$:void 0}function cG(f,$){let J=f?.trim();if(!J)return $;let H=Date.parse(J);if(!Number.isFinite(H))return $;return new Date(H).toISOString()}function tj(f,$){return new Date(new Date(f).getTime()+Math.max(0,Math.floor($))*1000).toISOString()}function sj(f,$){return new Date(new Date(f).getTime()-Math.max(0,Math.floor($))*1000).toISOString()}function dG(f,$){if(!f)return $;return new Date(f).getTime()>=new Date($).getTime()?f:$}function rG(f,$){let J=f.eventId.trim(),H=f.eventType.trim(),W=f.source.trim(),Q=z5(f.subject),Z=z5(f.dedupeKey)??`${H}:${W}:${Q??J}`;return{eventId:J,eventType:H,source:W,subject:Q,occurredAt:cG(f.occurredAt,$),workspaceRoot:z5(f.workspaceRoot),payload:f4(f.payload)?f.payload:void 0,attributes:f4(f.attributes)?f.attributes:void 0,dedupeKey:Z}}function O5(f,$){if(!$)return;let J=$.split("."),H=f;for(let W of J){if(!f4(H))return;H=H[W]}return H}function lG(f,$){if(f.attributes&&Object.hasOwn(f.attributes,$))return f.attributes[$];if(f.payload&&Object.hasOwn(f.payload,$))return f.payload[$];let J={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload},H=O5(J,$);if(H!==void 0)return H;if(f.attributes){let W=O5(f.attributes,$);if(W!==void 0)return W}if(f.payload)return O5(f.payload,$);return}function MJ(f,$){if(Array.isArray($))return $.some((J)=>MJ(f,J));if(Array.isArray(f))return f.some((J)=>MJ(J,$));if(f4($)){if(!f4(f))return!1;return Object.entries($).every(([J,H])=>MJ(f[J],H))}return Object.is(f,$)}function pG(f,$){if(!$||Object.keys($).length===0)return!0;return Object.entries($).every(([J,H])=>MJ(lG(f,J),H))}class N5{store;nowFn;logger;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now()),this.logger=f.logger}ingestEvent(f){let $=new Date(this.nowFn()).toISOString(),J=rG(f,$),H=this.store.insertEventLog(J,{receivedAtIso:$});if(!H.created)return this.logger?.debug("cron.event.duplicate",{eventId:H.record.eventId,eventType:H.record.eventType,source:H.record.source}),{event:H.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:H.record.dedupeKey}]};try{let W=this.store.listEventSpecsForType(J.eventType),Q=[],Z=[],j=[];for(let V of W){if(!pG(J,V.filters)){Q.push({specId:V.specId,externalId:V.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}Z.push(V);let Y=this.materializeForSpec(V,J,H.record.receivedAt);if(Y.run)j.push(Y.run);else Q.push({specId:V.specId,externalId:V.externalId,reason:Y.reason,dedupeKey:J.dedupeKey})}let P=Z.length===0?"unmatched":j.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(H.record.eventId,{status:P,matchedSpecCount:Z.length,queuedRunCount:j.length,suppressedCount:Q.filter((V)=>V.reason!=="filter_mismatch").length});let X=this.store.getEventLog(H.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:H.record.eventId,eventType:H.record.eventType,status:P,matchedSpecCount:Z.length,queuedRunCount:j.length}),{event:X??H.record,duplicate:!1,matchedSpecs:Z,queuedRuns:j,suppressions:Q}}catch(W){if(this.store.updateEventLogProcessing(H.record.eventId,{status:"failed",error:W instanceof Error?W.message:String(W)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:H.record.eventId,eventType:H.record.eventType,error:W});throw W}}materializeForSpec(f,$,J){let H=$.dedupeKey??$.eventId,W=f.debounceSeconds??0;if(W>0){let P=this.store.findQueuedEventRunForDedupe({specId:f.specId,dedupeKey:H});if(P){let X=dG(P.scheduledFor,tj(J,W)),V=this.store.updateQueuedEventRunForDebounce({runId:P.runId,triggerEventId:$.eventId,scheduledFor:X});if(V)return{run:V,reason:"dedupe_window"}}}let Q=f.dedupeWindowSeconds??0;if(Q>0&&this.store.hasRecentEventRunForDedupe({specId:f.specId,dedupeKey:H,sinceIso:sj(J,Q)}))return{reason:"dedupe_window"};let Z=f.cooldownSeconds??0;if(Z>0&&this.store.hasRecentEventRunForSpec({specId:f.specId,sinceIso:sj(J,Z)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"event",triggerEventId:$.eventId,scheduledFor:W>0?tj(J,W):J}),reason:"dedupe_window"}}}import{existsSync as Ph,readdirSync as Xh,readFileSync as Vh,statSync as Yh}from"node:fs";import{relative as Bh}from"node:path";import{resolveCronSpecsDir as Ah}from"@cline/shared/storage";import{createHash as iG}from"node:crypto";import nG from"yaml";function aG(f){let $=f.replace(/\\/g,"/");if($.startsWith("events/")&&$.endsWith(".event.md"))return"event";if($.endsWith(".cron.md"))return"schedule";return"one_off"}function tG(f){let $=f.replace(/\r\n/g,`
467
+ ${$}`}function YT(f,$){let{data:J,body:W,hadFrontmatter:H}=BT(f);if(!H&&$)return f;if($){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return W;return QX(J,W)}return J.disabled=!0,QX(J,W)}async function jX({filePath:f,enabled:$}){let J=await AT(f,"utf8"),W=YT(J,$);return await PT(f,W),{filePath:f,enabled:$,disabled:!$}}G0();var XX={};N(XX,{listPluginTools:()=>W4});G0();function VT(f,$){if(!f.setup)return[];let J=[],W={registerTool:(H)=>J.push(H),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return f.setup(W,{workspaceInfo:$}),J}async function W4(f){let $=I$({workspacePath:f.workspacePath,cwd:f.cwd}),J=rf(f.disabledToolNames),W=[];for(let H of $){let Q=await z0([H],{cwd:f.cwd,providerId:f.providerId,modelId:f.modelId});for(let Z of Q.plugins)for(let j of VT(Z,{rootPath:f.workspacePath}))W.push({name:j.name,pluginName:Z.name,path:H,source:H.startsWith(f.workspacePath)?"workspace-plugin":"global-plugin",enabled:!J.has(j.name),description:j.description?.trim()||void 0})}return W.sort((H,Q)=>{let Z=H.name.localeCompare(Q.name);if(Z!==0)return Z;return H.path.localeCompare(Q.path)})}function NH(f,$){if(!$)return"global";let J=FT($,f);return!J.startsWith("..")&&!RT(J)?"workspace":"global"}function TJ(f){return[...f].sort(($,J)=>{let W=(H)=>{switch(H){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if($.source!==J.source)return W($.source)-W(J.source);return $.name.localeCompare(J.name)})}function BX(f){return f.workspaceRoot?.trim()||f.cwd?.trim()||""}async function PX(f,$){if(f.userInstructionService)return await $(f.userInstructionService);let J=BX(f);if(!J)return await $(void 0);let W=Z$({skills:{workspacePath:J},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await W.start(),await $(W)}finally{W.stop()}}function KT(f,$){if(!f)return;let J=f.listRecords("skill");if($.id){let W=J.find((H)=>H.id===$.id);if(W)return W}for(let W of J)if(W.filePath===$.path||W.item.name===$.name||W.id===$.name)return W;return}class j${async list(f={}){return await PX(f,async($)=>{let J=BX(f),W=[],H=[],Q=[],Z=[];if($){for(let j of $.listRecords("workflow")){let X=j.item;W.push({id:j.id,name:X.name,path:j.filePath,enabled:X.disabled!==!0,kind:"workflow",source:NH(j.filePath,J),description:X.instructions,toggleable:!1})}for(let j of $.listRecords("rule")){let X=j.item;H.push({id:j.id,name:X.name,path:j.filePath,enabled:X.disabled!==!0,kind:"rule",source:NH(j.filePath,J),description:X.instructions,toggleable:!1})}for(let j of $.listRecords("skill")){let X=j.item;Q.push({id:j.id,name:X.name,path:j.filePath,enabled:X.disabled!==!0,kind:"skill",source:NH(j.filePath,J),description:X.description,toggleable:!0})}}if(J)try{for(let j of await W4({workspacePath:J,cwd:f.cwd,providerId:f.availabilityContext?.providerId,modelId:f.availabilityContext?.modelId}))Z.push({id:`${j.pluginName}:${j.name}:${j.path}`,name:j.name,path:j.path,enabled:j.enabled,kind:"tool",source:j.source,description:j.description,toggleable:!0})}catch{}return{workflows:TJ(W.filter((j)=>zH(j.path))),rules:TJ(H.filter((j)=>zH(j.path))),skills:TJ(Q.filter((j)=>zH(j.path))),tools:TJ(Z)}})}async toggle(f){if(f.type==="skills")return await PX(f,async($)=>{let J=KT($,f),W=J?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${f.id??f.name??AX(f.path??"")}'.`);let H=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,Q=f.enabled??(H!==void 0?!H:void 0);if(Q===void 0)throw Error(`Cannot determine toggle state for skill '${f.id??f.name??AX(f.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await jX({filePath:W,enabled:Q}),await $?.refreshType("skill"),{snapshot:await this.list({...f,userInstructionService:$}),changedTypes:["skills"]}});if(f.type==="tools"){if(!f.name?.trim())throw Error("Tool settings toggle requires a tool name.");if(f.enabled===void 0)f6(f.name);else fQ(f.name,!f.enabled);return{snapshot:await this.list(f),changedTypes:["tools"]}}throw Error(`Settings type '${f.type}' does not support toggles.`)}}function d$(){return new j$}function VX(f){return{async list($){let J=f;if(J.listSettings)return await J.listSettings($);return await d$().list($)},async toggle($){let J=f;if(J.toggleSetting)return await J.toggleSetting($);return await d$().toggle($)}}}function RX(f){function $(){let J=f.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return $().list(J)},update(J){return $().update(J)},delete(J){return $().delete(J)}}}var FX={};N(FX,{splitCoreSessionConfig:()=>H4});function H4(f){let{hooks:$,logger:J,telemetry:W,extensionContext:H,extraTools:Q,extensions:Z,onTeamEvent:j,onConsecutiveMistakeLimitReached:X,checkpoint:A,compaction:P,...B}=f,Y={};if($)Y.hooks=$;if(J)Y.logger=J;if(W)Y.telemetry=W;if(H)Y.extensionContext=H;if(Q)Y.extraTools=Q;if(Z)Y.extensions=Z;if(j)Y.onTeamEvent=j;if(X)Y.onConsecutiveMistakeLimitReached=X;if(A?.createCheckpoint)Y.checkpoint=A;if(P?.compact)Y.compaction=P;let V=Object.keys(Y).length>0?Y:void 0;return{config:{...B,...A?{checkpoint:{enabled:A.enabled}}:{},...P?{compaction:{enabled:P.enabled,strategy:P.strategy,thresholdRatio:P.thresholdRatio,reserveTokens:P.reserveTokens,preserveRecentTokens:P.preserveRecentTokens,contextWindowTokens:P.contextWindowTokens,summarizer:P.summarizer}}:{}},...V?{localRuntime:V}:{}}}function KX(f){let $=f.config;return"providerId"in $?{...f,config:{...$,...yT(f.localRuntime)},localRuntime:f.localRuntime}:f}function qH(f,$={}){let J=H4(f.config),W=Uf($.defaultCapabilities,f.capabilities),H=UT(J.localRuntime,f.localRuntime),Q=$.withExtensionContext?.(H?.extensionContext);if(Q)H={...H??{},extensionContext:Q};return{...f,...J,...H?{localRuntime:H}:{},...W?{capabilities:W}:{}}}function yT(f){if(!f)return{};let{modelCatalogDefaults:$,userInstructionService:J,configExtensions:W,onTeamRestored:H,...Q}=f;return Q}function UT(...f){let $={};for(let J of f)if(J)Object.assign($,J);return Object.keys($).length>0?$:void 0}_f();function yX(f){let $=f.input.config.telemetry??f.telemetry;if(!$)return;$.capture({event:v.SESSION.STARTED,properties:{sessionId:f.sessionId,source:f.input.source??Ff.CORE,providerId:f.input.config.providerId,modelId:f.input.config.modelId,enableTools:f.input.config.enableTools,enableSpawnAgent:f.input.config.enableSpawnAgent,enableAgentTeams:f.input.config.enableAgentTeams,clientName:f.clientName,runtimeAddress:f.runtimeAddress}})}function Q4(f){return!!f&&typeof f==="object"&&!Array.isArray(f)}function wH(f){let $=f?.trim();return $?$:void 0}function GT(f,$){let J=f?.trim();if(!J)return $;let W=Date.parse(J);if(!Number.isFinite(W))return $;return new Date(W).toISOString()}function UX(f,$){return new Date(new Date(f).getTime()+Math.max(0,Math.floor($))*1000).toISOString()}function GX(f,$){return new Date(new Date(f).getTime()-Math.max(0,Math.floor($))*1000).toISOString()}function TT(f,$){if(!f)return $;return new Date(f).getTime()>=new Date($).getTime()?f:$}function DT(f,$){let J=f.eventId.trim(),W=f.eventType.trim(),H=f.source.trim(),Q=wH(f.subject),Z=wH(f.dedupeKey)??`${W}:${H}:${Q??J}`;return{eventId:J,eventType:W,source:H,subject:Q,occurredAt:GT(f.occurredAt,$),workspaceRoot:wH(f.workspaceRoot),payload:Q4(f.payload)?f.payload:void 0,attributes:Q4(f.attributes)?f.attributes:void 0,dedupeKey:Z}}function bH(f,$){if(!$)return;let J=$.split("."),W=f;for(let H of J){if(!Q4(W))return;W=W[H]}return W}function _T(f,$){if(f.attributes&&Object.hasOwn(f.attributes,$))return f.attributes[$];if(f.payload&&Object.hasOwn(f.payload,$))return f.payload[$];let J={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload},W=bH(J,$);if(W!==void 0)return W;if(f.attributes){let H=bH(f.attributes,$);if(H!==void 0)return H}if(f.payload)return bH(f.payload,$);return}function DJ(f,$){if(Array.isArray($))return $.some((J)=>DJ(f,J));if(Array.isArray(f))return f.some((J)=>DJ(J,$));if(Q4($)){if(!Q4(f))return!1;return Object.entries($).every(([J,W])=>DJ(f[J],W))}return Object.is(f,$)}function MT(f,$){if(!$||Object.keys($).length===0)return!0;return Object.entries($).every(([J,W])=>DJ(_T(f,J),W))}class CH{store;nowFn;logger;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now()),this.logger=f.logger}ingestEvent(f){let $=new Date(this.nowFn()).toISOString(),J=DT(f,$),W=this.store.insertEventLog(J,{receivedAtIso:$});if(!W.created)return this.logger?.debug("cron.event.duplicate",{eventId:W.record.eventId,eventType:W.record.eventType,source:W.record.source}),{event:W.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:W.record.dedupeKey}]};try{let H=this.store.listEventSpecsForType(J.eventType),Q=[],Z=[],j=[];for(let P of H){if(!MT(J,P.filters)){Q.push({specId:P.specId,externalId:P.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}Z.push(P);let B=this.materializeForSpec(P,J,W.record.receivedAt);if(B.run)j.push(B.run);else Q.push({specId:P.specId,externalId:P.externalId,reason:B.reason,dedupeKey:J.dedupeKey})}let X=Z.length===0?"unmatched":j.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(W.record.eventId,{status:X,matchedSpecCount:Z.length,queuedRunCount:j.length,suppressedCount:Q.filter((P)=>P.reason!=="filter_mismatch").length});let A=this.store.getEventLog(W.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:W.record.eventId,eventType:W.record.eventType,status:X,matchedSpecCount:Z.length,queuedRunCount:j.length}),{event:A??W.record,duplicate:!1,matchedSpecs:Z,queuedRuns:j,suppressions:Q}}catch(H){if(this.store.updateEventLogProcessing(W.record.eventId,{status:"failed",error:H instanceof Error?H.message:String(H)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:W.record.eventId,eventType:W.record.eventType,error:H});throw H}}materializeForSpec(f,$,J){let W=$.dedupeKey??$.eventId,H=f.debounceSeconds??0;if(H>0){let X=this.store.findQueuedEventRunForDedupe({specId:f.specId,dedupeKey:W});if(X){let A=TT(X.scheduledFor,UX(J,H)),P=this.store.updateQueuedEventRunForDebounce({runId:X.runId,triggerEventId:$.eventId,scheduledFor:A});if(P)return{run:P,reason:"dedupe_window"}}}let Q=f.dedupeWindowSeconds??0;if(Q>0&&this.store.hasRecentEventRunForDedupe({specId:f.specId,dedupeKey:W,sinceIso:GX(J,Q)}))return{reason:"dedupe_window"};let Z=f.cooldownSeconds??0;if(Z>0&&this.store.hasRecentEventRunForSpec({specId:f.specId,sinceIso:GX(J,Z)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"event",triggerEventId:$.eventId,scheduledFor:H>0?UX(J,H):J}),reason:"dedupe_window"}}}import{existsSync as gT,readdirSync as vT,readFileSync as uT,statSync as cT}from"node:fs";import{relative as dT}from"node:path";import{resolveCronSpecsDir as rT}from"@cline/shared/storage";import{createHash as LT}from"node:crypto";import hT from"yaml";function OT(f){let $=f.replace(/\\/g,"/");if($.startsWith("events/")&&$.endsWith(".event.md"))return"event";if($.endsWith(".cron.md"))return"schedule";return"one_off"}function zT(f){let $=f.replace(/\r\n/g,`
468
468
  `);if(!$.startsWith(`---
469
- `))return{frontmatter:void 0,body:f};let J=$.slice(4),H=J.indexOf(`
470
- ---`);if(H===-1)return{frontmatter:void 0,body:f};let W=J.slice(0,H),Q=J.slice(H+4);if(Q.startsWith(`
471
- `))Q=Q.slice(1);return{frontmatter:W,body:Q}}function Ef(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function sG(f){if(!Array.isArray(f))return;let $=f.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return $.length>0?$:void 0}function w5(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return f}function oG(f){let $=w5(f);if(!$)return;let J=Ef($.providerId),H=Ef($.modelId);if(J===void 0&&H===void 0)return;return{providerId:J,modelId:H}}function eG(f){if(typeof f!=="string")return;let $=f.trim().toLowerCase();if($==="act"||$==="plan"||$==="yolo")return $;return}function ej(f,$={}){let J=Array.isArray(f)?f:typeof f==="string"?f.split(","):void 0;if(!J)return;let H=[...new Set(J.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0))];if(Array.isArray(f)&&$.preserveEmptyArray)return H;return H.length>0?H:void 0}var fh=new Set(q0);function $h(f){let $=ej(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((H)=>!fh.has(H));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return $}var Jh=new Set(["rules","skills","plugins"]);function Hh(f){let $=ej(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((H)=>!Jh.has(H));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return $}function q5(f){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return;return Math.floor(f)}function b5(f){if(typeof f!=="number"||!Number.isFinite(f)||f<0)return;return Math.floor(f)}function C5(f){if(f===null||typeof f!=="object")return JSON.stringify(f??null);if(Array.isArray(f))return`[${f.map((J)=>C5(J)).join(",")}]`;let $=Object.entries(f).filter(([,J])=>J!==void 0);return $.sort(([J],[H])=>J<H?-1:J>H?1:0),`{${$.map(([J,H])=>`${JSON.stringify(J)}:${C5(H)}`).join(",")}}`}function fP(f,$){let J=iG("sha256");return J.update(C5(f)),J.update(`
472
- `),J.update($),J.digest("hex")}function Wh(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var Qh=["schedule","timezone"],Zh=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],jh=["cwd"];function oj(f,$,J,H,W){return{externalId:f,relativePath:f,triggerKind:$,body:J,contentHash:fP(H,J),error:W}}function $0(f,$,J,H,W,Q){return{externalId:f,relativePath:$,triggerKind:J,body:H,contentHash:W,error:Q}}function $P(f){let $=f.relativePath.replace(/\\/g,"/"),J=aG($),{frontmatter:H,body:W}=tG(f.raw),Q={};if(H!==void 0&&H.trim().length>0)try{let K=nG.parse(H);if(K&&typeof K==="object"&&!Array.isArray(K))Q=K;else if(K!==null&&K!==void 0)return oj($,J,W,{},"frontmatter must be a YAML mapping")}catch(K){return oj($,J,W,{},K instanceof Error?`failed to parse frontmatter: ${K.message}`:"failed to parse frontmatter")}let Z=fP(Q,W),j=Ef(Q.id),P=j??$;if(J!=="schedule"){for(let K of Qh)if(Q[K]!==void 0)return $0(P,$,J,W,Z,`field "${K}" is only allowed on *.cron.md specs`)}for(let K of jh)if(Q[K]!==void 0)return $0(P,$,J,W,Z,`field "${K}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let K of Zh)if(Q[K]!==void 0)return $0(P,$,J,W,Z,`field "${K}" is only allowed on .event.md specs`)}let X=Ef(Q.prompt),V=W.trim(),Y=X??(V.length>0?V:void 0);if(!Y)return $0(P,$,J,W,Z,"prompt is required (frontmatter `prompt` or markdown body)");let B=Ef(Q.workspaceRoot);if(!B)return $0(P,$,J,W,Z,"workspaceRoot is required");let A,R;try{A=$h(Q.tools),R=Hh(Q.extensions)}catch(K){return $0(P,$,J,W,Z,K instanceof Error?K.message:String(K))}let U=eG(Q.mode);if(Q.mode!==void 0&&U===void 0)return $0(P,$,J,W,Z,"mode must be one of: act, plan, yolo");let y={id:j,title:Ef(Q.title)??j??Wh($),prompt:Y,workspaceRoot:B,mode:U??"yolo",systemPrompt:Ef(Q.systemPrompt),modelSelection:oG(Q.modelSelection),maxIterations:q5(Q.maxIterations),timeoutSeconds:q5(Q.timeoutSeconds),tools:A,notesDirectory:Ef(Q.notesDirectory),extensions:R,source:Ef(Q.source)??"user",tags:sG(Q.tags),enabled:typeof Q.enabled==="boolean"?Q.enabled:!0,metadata:w5(Q.metadata)},F;if(J==="schedule"){let K=Ef(Q.schedule);if(!K)return $0(P,$,J,W,Z,"schedule is required for *.cron.md specs");let M=Ef(Q.timezone);try{_3(K,M)}catch(G){return $0(P,$,J,W,Z,G instanceof Error?G.message:String(G))}F={...y,triggerKind:"schedule",schedule:K,timezone:M}}else if(J==="event"){let K=Ef(Q.event);if(!K)return $0(P,$,J,W,Z,"event is required for .event.md specs");F={...y,triggerKind:"event",event:K,filters:w5(Q.filters),debounceSeconds:b5(Q.debounceSeconds),dedupeWindowSeconds:b5(Q.dedupeWindowSeconds),cooldownSeconds:b5(Q.cooldownSeconds),maxParallel:q5(Q.maxParallel)}}else F={...y,triggerKind:"one_off"};return{externalId:P,relativePath:$,triggerKind:J,body:W,contentHash:Z,spec:F}}function Rh(f,$){return Bh(f,$).replace(/\\/g,"/")}function Fh(f){if(!Ph(f))return[];let $=[],J=[f];while(J.length>0){let H=J.pop();if(!H)continue;let W;try{W=Xh(H,{withFileTypes:!0})}catch{continue}for(let Q of W){let Z=`${H}/${Q.name}`;if(Q.isDirectory()){if(Q.name==="reports")continue;J.push(Z);continue}if(!Q.isFile())continue;if(!Q.name.endsWith(".md"))continue;$.push(Z)}}return $}class E5{store;cronDir;constructor(f){this.store=f.store,this.cronDir=Ah(f.specs??(f.workspaceRoot?{scope:"workspace",workspaceRoot:f.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let f={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},$=Fh(this.cronDir),J=new Set;for(let W of $){let Q=Rh(this.cronDir,W);J.add(Q),f.scanned+=1;let Z=await this.reconcileFile(Q,W);if(Z){if(f.changes.push(Z),f.upserted+=1,Z.parse.error)f.invalidParses+=1}}let H=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let W of H)if(!J.has(W.sourcePath))this.handleFileDeleted(W),f.removed+=1;return this.refreshScheduleNextRunAt(),f}async reconcileFile(f,$){let J=this.store.getSpecBySourcePath(f),H,W;try{H=Vh($,"utf8"),W=Yh($).mtimeMs}catch{return}let Z=$P({relativePath:f,raw:H}),j=this.store.upsertSpec({externalId:Z.externalId,sourcePath:f,triggerKind:Z.triggerKind,sourceMtimeMs:W,sourceHash:Z.contentHash,parseStatus:Z.error?"invalid":"valid",parseError:Z.error,spec:Z.spec});if(!Z.error&&Z.triggerKind==="schedule"&&j.record.enabled)this.applyScheduleNextRunAt(j.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==j.record.scheduleExpr||J.timezone!==j.record.timezone});return{relativePath:f,result:j,parse:Z}}handleFileDeleted(f){this.store.markSpecRemoved(f.specId),this.store.cancelQueuedRunsForSpec(f.specId)}refreshScheduleNextRunAt(){let f=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let $ of f)this.applyScheduleNextRunAt($,{forceReset:!1})}applyScheduleNextRunAt(f,$){if(!f.scheduleExpr)return;if(!$.forceReset&&f.nextRunAt)return;try{let J=Date.now(),H=f.lastRunAt?Math.max(J,new Date(f.lastRunAt).getTime()):J,W=Y$(f.scheduleExpr,H,f.timezone),Q=new Date(W).toISOString();if(f.nextRunAt!==Q)this.store.updateSpecNextRunAt(f.specId,Q)}catch{}}}import{existsSync as yh,mkdirSync as Kh,watch as Uh}from"node:fs";import{relative as Gh,resolve as hh}from"node:path";var Th=250;class S5{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor(f){this.reconciler=f.reconciler,this.debounceMs=Math.max(0,f.debounceMs??Th),this.onError=f.onError??(()=>{}),this.onReconciled=f.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let f=this.reconciler.getCronDir();try{Kh(f,{recursive:!0}),this.watcher=Uh(f,{recursive:!0},($,J)=>{if(!J)return;let H=String(J).replace(/\\/g,"/");if(!H.endsWith(".md"))return;if(H.startsWith("reports/"))return;this.scheduleReconcile(H)}),this.watcher.on("error",this.onError)}catch($){this.onError($)}}stop(){for(let f of this.pending.values())clearTimeout(f);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile(f){let $=this.pending.get(f);if($)clearTimeout($);let J=setTimeout(()=>{this.pending.delete(f),this.reconcileNow(f)},this.debounceMs);this.pending.set(f,J)}async reconcileNow(f){try{let $=hh(this.reconciler.getCronDir(),f);if(!yh($)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=Gh(this.reconciler.getCronDir(),$).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,$),await this.onReconciled()}catch($){this.onError($)}}}class $4{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new M2({dbPath:f.dbPath});let $=f.specs;this.reconciler=new E5({store:this.store,specs:$}),this.materializer=new y2({store:this.store}),this.eventIngress=new N5({store:this.store,logger:f.logger}),this.runner=new G2({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:f.workspaceRoot,specs:$,logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency}),this.watcher=new S5({reconciler:this.reconciler,debounceMs:f.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let H=f.logger;if(H)if(H.error)H.error("cron.watcher.failed",{error:J});else H.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs(f){return this.store.listSpecs(f)}getSpec(f){return this.store.getSpec(f)}listRuns(f){return this.store.listRuns(f)}getRun(f){return this.store.getRun(f)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns(f=20){return this.store.listRuns({status:"queued",limit:f})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent(f){return this.eventIngress.ingestEvent(f)}listEventLogs(f){return this.store.listEventLogs(f)}getEventLog(f){return this.store.getEventLog(f)}}var YP={};N(YP,{manifestToSessionRecord:()=>zJ,listSessionHistoryFromBackend:()=>I5,listSessionHistory:()=>OJ,hydrateSessionHistory:()=>VP});import{readdir as Lh,readFile as jP}from"node:fs/promises";import{join as PP}from"node:path";import{formatDisplayUserInput as zh,normalizeUserInput as Oh}from"@cline/shared";import{resolveSessionDataDir as XP}from"@cline/shared/storage";import{existsSync as Dh}from"node:fs";import{readFile as Mh}from"node:fs/promises";import{formatDisplayUserInput as JP}from"@cline/shared";class J4{listeners=new Set;subscribe(f,$){let J={listener:f,sessionId:$?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit(f){let $=f.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$)continue;J.listener(f)}}get size(){return this.listeners.size}}async function u$(f){let $=f?.trim();if(!$||!Dh($))return[];try{let J=(await Mh($,"utf8")).trim();if(!J)return[];let H=JSON.parse(J);if(Array.isArray(H))return HP(H);if(H&&typeof H==="object"&&!Array.isArray(H)){let W=H.messages;if(Array.isArray(W))return HP(W)}return[]}catch{return[]}}function _h(f){if(f.role!=="user")return f;if(typeof f.content==="string")return{...f,content:JP(f.content)};return{...f,content:f.content.map(($)=>{if($.type!=="text"||typeof $.text!=="string")return $;return{...$,text:JP($.text)}})}}function HP(f){return f.map(_h)}function WP(f){return f?{...f}:void 0}async function QP(f,$){if(!(f.hookName==="tool_call"||!!f.parent_agent_id))return;await $.queueSpawnRequest(f);let H=await $.upsertSubagentSessionFromHook(f);if(!H)return;await $.appendSubagentHookAudit(H,f),await $.applySubagentStatus(H,f)}function _J(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function Sf(f){let $=_J(f);if(!$)return;return $.toLowerCase()==="unknown"?void 0:$}function LJ(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function Nh(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return{...f}}function m5(f){let $=f??200;return Number.isFinite($)?Math.max(0,Math.floor($)):200}function qh(f){let $=f.match(/\d{13,}/g);if(!$||$.length===0)return 0;let J=0;for(let H of $){let W=Number.parseInt(H,10);if(Number.isFinite(W)&&W>J)J=W}return J}function zJ(f){return{sessionId:f.session_id,source:f.source,pid:f.pid,startedAt:f.started_at,endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspace_root,teamName:f.team_name,enableTools:f.enable_tools,enableSpawn:f.enable_spawn,enableTeams:f.enable_teams,isSubagent:!1,prompt:f.prompt,metadata:f.metadata,messagesPath:f.messages_path,updatedAt:f.ended_at??f.started_at}}async function bh(f){let $=m5(f);if($===0)return[];let J=XP(),W=(await Lh(J,{withFileTypes:!0}).catch(()=>[])).filter((Z)=>Z.isDirectory()).map((Z)=>({entry:Z,recency:qh(Z.name.trim())})).sort((Z,j)=>j.recency-Z.recency||j.entry.name.localeCompare(Z.entry.name));return(await Promise.all(W.map(async({entry:Z})=>{let j=Z.name.trim();if(!j)return;let P=PP(J,j,`${j}.json`),X=await jP(P,"utf8").catch(()=>{return});if(!X)return;let V;try{V=JSON.parse(X)}catch{return}let Y=Gf.safeParse(V);if(!Y.success)return;return zJ(Y.data)}))).filter((Z)=>Boolean(Z)).sort((Z,j)=>j.startedAt.localeCompare(Z.startedAt)).slice(0,$)}async function wh(f,$){let J=m5($);if(J===0)return await f.listSessions(0),[];return(await f.listSessions(J)).slice(0,J)}function Ch(f){if(typeof f==="string")return f.trim();let $=[];for(let J of f){if(!J||typeof J!=="object")continue;let H=J;if(H.type!=="text")continue;let W=H.text?.trim();if(W)$.push(W)}return $.join(`
473
- `).trim()}function ZP(f){return f.replace(/\s+/g," ").trim()}function Eh(f,$){if(f.length<=$)return f;return`${f.slice(0,Math.max(0,$-3)).trimEnd()}...`}function Sh(f){for(let $ of["user","assistant"])for(let J of f){if(J.role!==$)continue;let H=ZP(Ch(J.content));if(!H)continue;let W=$==="user"?ZP(zh(H)):H,Q=Oh(W.split(`
474
- `)[0]??W);return Eh(Q,50)}return}function kh(f){let $=0;for(let J of f)$+=LJ(J.metrics?.cost)??0;return $}function mh(f){let $,J;for(let H=f.length-1;H>=0;H-=1){let W=f[H];if(!$)$=Sf(W.modelInfo?.provider);if(!J)J=Sf(W.modelInfo?.id);if($&&J)break}return{provider:$,model:J}}function Ih(f){return Sf(f?.provider)??Sf(f?.provider&&typeof f.provider==="object"&&!Array.isArray(f.provider)?f.provider.id:void 0)}function xh(f){return Sf(f?.model)??Sf(f?.model&&typeof f.model==="object"&&!Array.isArray(f.model)?f.model.id:void 0)}function k5(f,$){let J=Nh(f.metadata),H=_J($?.title)??_J(J?.title),W=LJ($?.totalCost)??LJ(J?.totalCost),Q=J||H!==void 0||W!==void 0?{...J??{},...H!==void 0?{title:H}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...f,provider:Sf($?.provider)??Sf(f.provider)??Ih(J)??"",model:Sf($?.model)??Sf(f.model)??xh(J)??"",metadata:Q}}async function VP(f,$){return await Promise.all($.map(async(J)=>{let H=k5(J),W=Boolean(_J(H.metadata?.title)),Q=Boolean(Sf(H.provider)),Z=Boolean(Sf(H.model)),j=LJ(H.metadata?.totalCost),P=j!==void 0&&j>0;if(W&&Q&&Z&&P)return H;let X=await f.readSessionMessages(J.sessionId);if(X.length===0)return H;let V=mh(X),Y=kh(X);return k5(J,{title:W?void 0:Sh(X),provider:Q?void 0:V.provider,model:Z?void 0:V.model,totalCost:P||Y<=0?void 0:Y})}))}async function OJ(f,$={}){let J=m5($.limit),H=await wh(f,J),W=$.includeManifestFallback===!0&&H.length<J?await bh(Math.min(Math.max(J*2,100),500)):[],Q=new Map;for(let j of[...H,...W]){if(Q.has(j.sessionId))continue;Q.set(j.sessionId,j)}let Z=W.length===0?H:Array.from(Q.values()).sort((j,P)=>P.startedAt.localeCompare(j.startedAt)).slice(0,J);if($.hydrate===!1)return Z.map((j)=>k5(j));return await VP(f,Z)}async function gh(f){let $=f.trim();if(!$)return;let J=PP(XP(),$,`${$}.json`),H=await jP(J,"utf8").catch(()=>{return});if(!H)return;try{let W=Gf.safeParse(JSON.parse(H));return W.success?W.data.messages_path:void 0}catch{return}}async function I5(f,$={}){let J=new Map;return await OJ({listSessions:async(W)=>{let Q=await f.listSessions(W);J.clear();for(let Z of Q)J.set(Z.sessionId,Z);return Q.map(Y8)},readSessionMessages:async(W)=>{let Q=J.get(W)?.messagesPath??await gh(W);return await u$(Q)}},$)}var dP={};N(dP,{resolveSessionBackend:()=>J9,createRuntimeHost:()=>e1});var TP={};N(TP,{HubRuntimeHost:()=>_0});import{createSessionId as AP,HUB_CHECKPOINT_CAPABILITY as dh,HUB_COMPACTION_CAPABILITY as rh,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as lh,HUB_HOOK_CAPABILITY_PREFIX as ph,HUB_MISTAKE_LIMIT_CAPABILITY as ih,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as nh,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as ah,isHubToolExecutorName as th}from"@cline/shared";var BP={};N(BP,{createCoreSessionSnapshot:()=>J0,coreSessionSnapshotToRecord:()=>NJ});function vh(f){return f?JSON.parse(JSON.stringify(f)):void 0}function uh(f){return f?JSON.parse(JSON.stringify(f)):void 0}function ch(f){let $=f?.checkpoint&&typeof f.checkpoint==="object"&&!Array.isArray(f.checkpoint)?f.checkpoint:void 0,H=(Array.isArray($?.history)?$.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let j=typeof Z.ref==="string"?Z.ref.trim():"",P=Number(Z.createdAt),X=Number(Z.runCount);if(!j||!Number.isFinite(P)||!Number.isInteger(X))return[];return[{ref:j,createdAt:P,runCount:X,...Z.kind==="stash"||Z.kind==="commit"?{kind:Z.kind}:{}}]}),W=H.at(-1),Q=f?.checkpointEnabled===!0?!0:void 0;if(!Q&&H.length===0)return;return{...Q?{enabled:Q}:{},...W?{latest:W}:{},history:H}}function J0(f){let{session:$}=f,J=vh($.metadata);return{version:1,sessionId:$.sessionId,source:$.source,status:$.status,createdAt:$.startedAt,updatedAt:$.updatedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,interactive:$.interactive,workspace:{cwd:$.cwd,root:$.workspaceRoot},model:{providerId:$.provider,modelId:$.model},capabilities:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams},lineage:{...$.parentSessionId?{parentSessionId:$.parentSessionId}:{},...$.parentAgentId?{parentAgentId:$.parentAgentId}:{},...$.agentId?{agentId:$.agentId}:{},...$.conversationId?{conversationId:$.conversationId}:{},isSubagent:$.isSubagent},...$.teamName?{team:{name:$.teamName}}:{},...$.prompt?{prompt:$.prompt}:{},...J?{metadata:J}:{},...$.messagesPath?{artifacts:{messagesPath:$.messagesPath}}:{},...f.messages?{messages:uh(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...(()=>{let H=ch(J);return H?{checkpoint:H}:{}})()}}function NJ(f){return{sessionId:f.sessionId,parentSessionId:f.lineage.parentSessionId,agentId:f.lineage.agentId,parentAgentId:f.lineage.parentAgentId,conversationId:f.lineage.conversationId,isSubagent:f.lineage.isSubagent,source:f.source,startedAt:f.createdAt,endedAt:f.endedAt??void 0,exitCode:f.exitCode??void 0,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspaceRoot:f.workspace.root,teamName:f.team?.name,enableTools:f.capabilities.enableTools,enableSpawn:f.capabilities.enableSpawn,enableTeams:f.capabilities.enableTeams,prompt:f.prompt,metadata:f.metadata,updatedAt:f.updatedAt,messagesPath:f.artifacts?.messagesPath}}function i1(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var sh=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function RP(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function FP(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function yP(f){let $=f&&typeof f==="object"&&!Array.isArray(f)?f:{};return{agentId:typeof $.agentId==="string"?$.agentId:"",conversationId:typeof $.conversationId==="string"?$.conversationId:"",iteration:typeof $.iteration==="number"?$.iteration:0,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}}function c$(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function KP(f,$){let J={manifest:[],handlers:new Map};for(let W of Object.keys($.toolExecutors??{}).filter(th)){let Q=$.toolExecutors?.[W];if(typeof Q!=="function")continue;c$(J,{kind:"toolExecutor",executor:W,capabilityName:`${nh}${W}`},async({payload:Z,abortSignal:j})=>{let P=Array.isArray(Z.args)?[...Z.args]:[],X={...yP(Z.context),signal:j};return{result:await Q(...P,X)}})}for(let W of f?.extraTools??[])c$(J,{kind:"tool",name:W.name,description:W.description,inputSchema:i1(W.inputSchema)??{},...W.lifecycle?{lifecycle:i1(W.lifecycle)}:{},capabilityName:`${lh}${W.name}`},async({payload:Q,abortSignal:Z,progress:j})=>{let P={...yP(Q.context),signal:Z};return{result:await W.execute(Q.input,{...P,emitUpdate:(V)=>{j({update:V})}})}});let H=f?.hooks;if(H)for(let W of sh){let Q=H[W];if(typeof Q!=="function")continue;c$(J,{kind:"hook",name:W,capabilityName:`${ph}${W}`},async({payload:Z})=>({control:await Q(Z.context)}))}if(f?.compaction?.compact){let W=f.compaction.compact;c$(J,{kind:"compaction",capabilityName:rh,config:RP(f.compaction)},async({payload:Q})=>({result:await W(Q.context)}))}if(f?.checkpoint?.createCheckpoint){let W=f.checkpoint.createCheckpoint;c$(J,{kind:"checkpoint",capabilityName:dh,config:RP(f.checkpoint)},async({payload:Q})=>({result:await W(Q.context)}))}if(f?.onConsecutiveMistakeLimitReached){let W=f.onConsecutiveMistakeLimitReached;c$(J,{kind:"mistakeLimit",capabilityName:ih},async({payload:Q})=>({result:await W(Q.context)}))}if(f?.userInstructionService){let W=f.userInstructionService;c$(J,{kind:"userInstructionService",capabilityName:ah},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return J}function oh(f){if(typeof f==="string"&&f.trim())return f.trim();if(f instanceof Error)return f.message;if(f&&typeof f==="object"&&"message"in f){let $=f.message;if(typeof $==="string"&&$.trim())return $.trim()}return"Capability request was cancelled."}function eh(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function fT(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function $T(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=typeof $.inputTokens==="number"?$.inputTokens:void 0,H=typeof $.outputTokens==="number"?$.outputTokens:void 0;if(J===void 0||H===void 0)return;return{inputTokens:J,outputTokens:H,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function JT(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,H=fT(J)?J:J==="failed"?"error":"completed",W=$T(f?.usage??$?.usage);return{type:"done",reason:H,text:typeof f?.text==="string"?f.text:typeof $?.text==="string"?$.text:"",iterations:typeof f?.iterations==="number"?f.iterations:typeof $?.iterations==="number"?$.iterations:0,usage:W}}function x5(f,$){return f.error?.message??`hub command failed: ${$}`}function H4(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function hP(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):void 0;return{sessionId:f.sessionId,parentSessionId:typeof $?.parentSessionId==="string"?$.parentSessionId:void 0,agentId:f.runtimeSession?.agentId||(typeof $?.agentId==="string"?$.agentId:void 0),parentAgentId:typeof $?.parentAgentId==="string"?$.parentAgentId:void 0,conversationId:typeof $?.conversationId==="string"?$.conversationId:void 0,isSubagent:typeof $?.isSubagent==="boolean"?$.isSubagent:!1,source:typeof $?.source==="string"?$.source:Vf.CORE,pid:typeof $?.pid==="number"?$.pid:void 0,startedAt:new Date(f.createdAt).toISOString(),endedAt:H4(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:H4(f.status)==="completed"?0:H4(f.status)==="failed"?1:void 0,status:H4(f.status),interactive:$?.interactive===!0,provider:typeof $?.provider==="string"?$.provider:"hub",model:typeof $?.model==="string"?$.model:"hub",cwd:f.cwd?.trim()||f.workspaceRoot,workspaceRoot:f.workspaceRoot,teamName:typeof $?.teamName==="string"?$.teamName:void 0,enableTools:f.runtimeOptions?.enableTools??$?.enableTools===!0,enableSpawn:f.runtimeOptions?.enableSpawn??$?.enableSpawn===!0,enableTeams:f.runtimeOptions?.enableTeams??$?.enableTeams===!0,prompt:typeof $?.prompt==="string"?$.prompt:void 0,metadata:$,updatedAt:new Date(f.updatedAt).toISOString(),messagesPath:typeof $?.messagesPath==="string"?$.messagesPath:void 0,hookPath:typeof $?.hookPath==="string"?$.hookPath:void 0}}function d$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;return $.version===1&&typeof $.sessionId==="string"?JSON.parse(JSON.stringify($)):void 0}function HT(f){let $=d$(f?.snapshot);if($)return NJ($);let J=f?.session;return J?hP(J):void 0}function UP(f,$,J){let H=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return Gf.parse({version:1,session_id:f,source:$.source??Vf.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:H4(J?.status),interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:J?.cwd?.trim()||$.config.cwd,workspace_root:H,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,metadata:$.sessionMetadata&&Object.keys($.sessionMetadata).length>0?$.sessionMetadata:void 0})}function GP(f,$){return Gf.parse({version:1,session_id:f.sessionId,source:f.source,pid:process.pid,started_at:f.createdAt,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspace_root:f.workspace.root,team_name:f.team?.name,enable_tools:f.capabilities.enableTools,enable_spawn:f.capabilities.enableSpawn,enable_teams:f.capabilities.enableTeams,prompt:(f.prompt??$.prompt?.trim())||void 0,metadata:f.metadata,messages_path:f.artifacts?.messagesPath})}class _0{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new J4;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;constructor(f,$){this.clientContext=$,this.clientOptions={authToken:f.authToken,clientType:f.clientType??"core-hub-runtime",displayName:f.displayName??"core hub runtime",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd},this.defaultCapabilities=Bf(f.capabilities)??{},this.runtimeAddress=f.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient(f.url)}createClient(f){return new df({...this.clientOptions,url:f})}async replaceClient(f){let $=this.client;this.client=this.createClient(f),this.runtimeAddress=f,await Promise.resolve($.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock(f){if(!H6(f,"session.create"))return!1;let $=await W6({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!$)return!1;return await this.replaceClient($),!0}registerPlannedSession(f,$,J){if(this.sessionCapabilities.set(f,$),J.size>0)this.sessionClientContributionHandlers.set(f,J);this.ensureSessionSubscription(f)}cleanupPlannedSession(f){this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f)}async connect(){await this.client.connect()}async startSession(f){let $=this.resolveCapabilities(f),J=KP(f.localRuntime,$),H=f.config.sessionId?.trim()||AP(),W=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:i1({...f.config,sessionId:H}),metadata:{...f.sessionMetadata??{},source:f.source??Vf.CORE,provider:f.config.providerId,model:f.config.modelId,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,teamName:f.config.teamName,prompt:f.prompt,interactive:f.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...f.localRuntime?.configExtensions?{configExtensions:f.localRuntime.configExtensions}:{}},toolPolicies:i1(f.toolPolicies),initialMessages:f.initialMessages});this.registerPlannedSession(H,$,J.handlers);let Q;try{Q=await W()}catch(X){if(this.cleanupPlannedSession(H),await this.recoverLocalHubStartupDeadlock(X)){this.registerPlannedSession(H,$,J.handlers);try{Q=await W()}catch(V){throw this.cleanupPlannedSession(H),V}}else throw X}let Z=d$(Q.payload?.snapshot),j=Q.payload?.session,P=(Z?.sessionId??j?.sessionId)?.trim();if(!P)throw this.cleanupPlannedSession(H),Error("Hub runtime did not return a session id.");if(P!==H)this.cleanupPlannedSession(H),this.registerPlannedSession(P,$,J.handlers);return{sessionId:P,manifest:Z?GP(Z,f):UP(P,f,j),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.start)throw Error("start is required when restore.messages is true");let H=f.start,W=H?this.resolveCapabilities(H):void 0,Q=H?KP(H.localRuntime,W??{}):{manifest:[],handlers:new Map},Z=H?H.config.sessionId?.trim()||AP():void 0;if(Z&&W)this.sessionCapabilities.set(Z,W);if(Z&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(Z,Q.handlers),this.ensureSessionSubscription(Z);let j;try{j=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...H?{workspaceRoot:H.config.workspaceRoot?.trim()||H.config.cwd,cwd:H.config.cwd??f.cwd,sessionConfig:i1({...H.config,sessionId:Z}),metadata:{...H.sessionMetadata??{},source:H.source??Vf.CORE,provider:H.config.providerId,model:H.config.modelId,enableTools:H.config.enableTools,enableSpawn:H.config.enableSpawnAgent,enableTeams:H.config.enableAgentTeams,teamName:H.config.teamName,prompt:H.prompt,interactive:H.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...H.localRuntime?.configExtensions?{configExtensions:H.localRuntime.configExtensions}:{}},toolPolicies:i1(H.toolPolicies)}:{}},$)}catch(A){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw A}if(!j.ok){let A=typeof j.payload?.error==="string"?j.payload.error:"session.restore failed";if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error(A)}let P=d$(j.payload?.snapshot),X=j.payload?.session,V=(P?.sessionId??X?.sessionId)?.trim();if(J&&!V){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error("Hub checkpoint restore returned no session id")}if(V&&Z&&V!==Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);if(V&&W)this.sessionCapabilities.set(V,W);if(V&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(V,Q.handlers);if(V)this.ensureSessionSubscription(V);let Y=Array.isArray(j.payload?.messages)?j.payload.messages:void 0,B=j.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:V,startResult:V?{sessionId:V,manifest:P?GP(P,H??{}):UP(V,H??{},X),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:Y,checkpoint:B}}async runTurn(f){return this.ensureSessionSubscription(f.sessionId),(await this.client.command("run.start",{sessionId:f.sessionId,input:f.prompt,attachments:(f.userImages?.length??0)>0||(f.userFiles?.length??0)>0?{...f.userImages?.length?{userImages:f.userImages}:{},...f.userFiles?.length?{userFiles:f.userFiles}:{}}:void 0,delivery:f.delivery,timeoutMs:f.timeoutMs},f.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.pending_prompts",{sessionId:f.sessionId},f.sessionId);return Array.isArray($.payload?.prompts)?$.payload.prompts:[]}async requestPendingPromptUpdate(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.update_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,updated:$.payload?.updated===!0}}async requestPendingPromptDelete(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.remove_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,removed:$.payload?.removed===!0}}async getAccumulatedUsage(f){let $=await this.client.command("session.get",{includeSnapshot:!0},f),J=d$($.payload?.snapshot);if(J?.usage)return{...J.usage};let H=$.payload?.session;return H?.usage?{...H.usage}:void 0}async abort(f,$){await this.client.command("run.abort",{sessionId:f,reason:typeof $==="string"?$:void 0},f)}async stopSession(f){this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),await this.client.command("session.detach",{sessionId:f},f)}async dispose(){for(let[f,$]of this.sessionSubscriptions){$();try{await this.client.command("session.detach",{sessionId:f},f)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let f of this.activeCapabilityAbortControllers.values())f.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession(f){let $=await this.client.command("session.get",void 0,f);return HT($.payload)}async listSessions(f=100){let $=await this.client.command("session.list",{limit:f}),J=Array.isArray($.payload?.snapshots)?$.payload.snapshots.flatMap((W)=>{let Q=d$(W);return Q?[NJ(Q)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(hP)}async listSettings(f){let $=await this.client.command("settings.list",FP(f));if(!$.ok)throw Error(x5($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",FP(f));if(!$.ok)throw Error(x5($,"settings.toggle"));return{snapshot:$.payload?.snapshot,changedTypes:Array.isArray($.payload?.changedTypes)?$.payload.changedTypes:[]}}async deleteSession(f){return this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),(await this.client.command("session.delete",{sessionId:f})).payload?.deleted===!0}async updateSession(f,$){let J={...$.metadata??{}};if(typeof $.prompt==="string")J.prompt=$.prompt;if(typeof $.title==="string")J.title=$.title;return{updated:(await this.client.command("session.update",{sessionId:f,metadata:J})).ok}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(x5(J,"session.messages"));let H=J.payload?.messages;return Array.isArray(H)?H:[]}async dispatchHookEvent(f){await this.client.command("session.hook",{payload:f})}subscribe(f,$){return this.events.subscribe(f,$)}ensureSessionSubscription(f){let $=f.trim();if(!$||this.sessionSubscriptions.has($))return;let J=this.client.subscribe((H)=>{this.handleHubEvent(H)},{sessionId:$});this.sessionSubscriptions.set($,typeof J==="function"?J:()=>{})}disposeSessionSubscription(f){let $=f.trim();if(!$)return;this.sessionSubscriptions.get($)?.(),this.sessionSubscriptions.delete($),this.agentDoneEmittedForCurrentRunBySession.delete($)}resolveCapabilities(f){return Bf(this.defaultCapabilities,f.capabilities)??{}}emitToolCallContentStart(f){this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:f.toolCallId,toolName:f.toolName,input:f.toolInput}}})}emitAgentDoneIfNeeded(f){if(this.agentDoneEmittedForCurrentRunBySession.has(f.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add(f.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:JT(f.payload)}})}handleHubEvent(f){let $=f.sessionId?.trim();if(f.event==="capability.requested"){this.handleCapabilityRequest(f);return}if(f.event==="capability.resolved"){this.handleCapabilityResolved(f);return}if(f.event==="approval.requested"){this.handleApprovalRequested(f);return}if(!$)return;switch(f.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete($);let J=d$(f.payload?.snapshot),H=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:H?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_start",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_end",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,hadToolCalls:f.payload?.hadToolCalls===!0,toolCallCount:typeof f.payload?.toolCallCount==="number"?f.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"text",text:typeof f.payload?.text==="string"?f.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"",H=f.payload?.redacted===!0;if(!J&&!H)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:H}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"reasoning",reasoning:typeof f.payload?.reasoning==="string"?f.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:$,payload:f.payload});return}case"tool.started":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:$,toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,toolInput:f.payload?.input});return}case"tool.finished":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,output:f.payload?.output,error:typeof f.payload?.error==="string"?f.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=d$(f.payload?.snapshot),H=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:H?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:$,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=f.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:$,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=typeof f.payload?.reason==="string"?f.payload.reason:f.event==="run.aborted"?"aborted":f.event==="run.failed"?"error":"completed";this.emitAgentDoneIfNeeded({sessionId:$,payload:{...f.payload,reason:J}}),this.events.emit({type:"ended",payload:{sessionId:$,reason:J,ts:f.timestamp??Date.now()}});return}default:return}}async handleCapabilityRequest(f){let $=f.sessionId?.trim();if(!$)return;let J=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let H=typeof f.payload?.requestId==="string"?f.payload.requestId:"",W=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName:"";if(!H)return;let Q=this.sessionClientContributionHandlers.get($)?.get(W);if(!Q){await this.client.command("capability.respond",{requestId:H,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${$}.`},$).catch(()=>{});return}let Z=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=new AbortController;this.activeCapabilityAbortControllers.set(H,j);let P=(X)=>{this.client.command("capability.progress",{requestId:H,payload:X},$)};try{let X=await Q({payload:Z,abortSignal:j.signal,progress:P});if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:H,ok:!0,payload:X},$)}catch(X){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:H,ok:!1,error:X instanceof Error?X.message:String(X)},$)}finally{this.activeCapabilityAbortControllers.delete(H)}}handleCapabilityResolved(f){if(f.payload?.cancelled!==!0)return;let $=typeof f.payload.requestId==="string"?f.payload.requestId.trim():"";if(!$)return;let J=this.activeCapabilityAbortControllers.get($);if(!J)return;J.abort(oh(f.payload.error))}async handleApprovalRequested(f){let $=f.sessionId?.trim();if(!$)return;let J=this.sessionCapabilities.get($)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let H=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"",W=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:"",Q=typeof f.payload?.toolName==="string"?f.payload.toolName:"";if(!H||!W||!Q)return;let Z=f.payload?.policy&&typeof f.payload.policy==="object"&&!Array.isArray(f.payload.policy)?f.payload.policy:{autoApprove:!1},j=eh(f.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:$,toolCallId:W,toolName:Q,toolInput:j});let P=await Promise.resolve(J({sessionId:$,agentId:typeof f.payload?.agentId==="string"?f.payload.agentId:"",conversationId:typeof f.payload?.conversationId==="string"?f.payload.conversationId:$,iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,toolCallId:W,toolName:Q,input:j,policy:Z})).catch((X)=>({approved:!1,reason:X instanceof Error?X.message:`Tool approval request failed: ${String(X)}`}));await this.client.command("approval.respond",{approvalId:H,approved:P.approved,reason:P.reason},$).catch(()=>{})}}var DP={};N(DP,{RemoteRuntimeHost:()=>n1});class n1 extends _0{constructor(f){super({url:m0(f.endpoint),authToken:f.authToken,clientType:f.clientType??"core-remote-runtime",displayName:f.displayName??"core remote runtime",capabilities:f.capabilities},{workspaceRoot:f.workspaceRoot,cwd:f.cwd})}}var MP={};N(MP,{SqliteSessionStore:()=>W0});import{existsSync as WT,mkdirSync as QT}from"node:fs";import{join as ZT}from"node:path";import{asBool as W4,asOptionalString as H0,asString as L0,ensureSessionSchema as jT,loadSqliteDb as PT,nowIso as qJ,toBoolInt as Q4}from"@cline/shared/db";import{resolveDbDataDir as XT}from"@cline/shared/storage";class W0{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??XT()}init(){this.getRawDb()}ensureSessionsDir(){if(!WT(this.sessionsDirPath))QT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return ZT(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=PT(this.sessionDbPath());return jT(f,{includeLegacyMigrations:!0}),this.db=f,f}close(){this.db?.close?.(),this.db=void 0}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}create(f){let $=qJ();this.run(`INSERT OR REPLACE INTO sessions (
469
+ `))return{frontmatter:void 0,body:f};let J=$.slice(4),W=J.indexOf(`
470
+ ---`);if(W===-1)return{frontmatter:void 0,body:f};let H=J.slice(0,W),Q=J.slice(W+4);if(Q.startsWith(`
471
+ `))Q=Q.slice(1);return{frontmatter:H,body:Q}}function xf(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function NT(f){if(!Array.isArray(f))return;let $=f.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return $.length>0?$:void 0}function kH(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return f}function qT(f){let $=kH(f);if(!$)return;let J=xf($.providerId),W=xf($.modelId);if(J===void 0&&W===void 0)return;return{providerId:J,modelId:W}}function wT(f){if(typeof f!=="string")return;let $=f.trim().toLowerCase();if($==="act"||$==="plan"||$==="yolo")return $;return}function DX(f,$={}){let J=Array.isArray(f)?f:typeof f==="string"?f.split(","):void 0;if(!J)return;let W=[...new Set(J.map((H)=>typeof H==="string"?H.trim():"").filter((H)=>H.length>0))];if(Array.isArray(f)&&$.preserveEmptyArray)return W;return W.length>0?W:void 0}var bT=new Set(k0);function CT(f){let $=DX(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((W)=>!bT.has(W));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return $}var ET=new Set(["rules","skills","plugins"]);function ST(f){let $=DX(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((W)=>!ET.has(W));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return $}function EH(f){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return;return Math.floor(f)}function SH(f){if(typeof f!=="number"||!Number.isFinite(f)||f<0)return;return Math.floor(f)}function IH(f){if(f===null||typeof f!=="object")return JSON.stringify(f??null);if(Array.isArray(f))return`[${f.map((J)=>IH(J)).join(",")}]`;let $=Object.entries(f).filter(([,J])=>J!==void 0);return $.sort(([J],[W])=>J<W?-1:J>W?1:0),`{${$.map(([J,W])=>`${JSON.stringify(J)}:${IH(W)}`).join(",")}}`}function _X(f,$){let J=LT("sha256");return J.update(IH(f)),J.update(`
472
+ `),J.update($),J.digest("hex")}function kT(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var IT=["schedule","timezone"],mT=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],xT=["cwd"];function TX(f,$,J,W,H){return{externalId:f,relativePath:f,triggerKind:$,body:J,contentHash:_X(W,J),error:H}}function J0(f,$,J,W,H,Q){return{externalId:f,relativePath:$,triggerKind:J,body:W,contentHash:H,error:Q}}function MX(f){let $=f.relativePath.replace(/\\/g,"/"),J=OT($),{frontmatter:W,body:H}=zT(f.raw),Q={};if(W!==void 0&&W.trim().length>0)try{let y=hT.parse(W);if(y&&typeof y==="object"&&!Array.isArray(y))Q=y;else if(y!==null&&y!==void 0)return TX($,J,H,{},"frontmatter must be a YAML mapping")}catch(y){return TX($,J,H,{},y instanceof Error?`failed to parse frontmatter: ${y.message}`:"failed to parse frontmatter")}let Z=_X(Q,H),j=xf(Q.id),X=j??$;if(J!=="schedule"){for(let y of IT)if(Q[y]!==void 0)return J0(X,$,J,H,Z,`field "${y}" is only allowed on *.cron.md specs`)}for(let y of xT)if(Q[y]!==void 0)return J0(X,$,J,H,Z,`field "${y}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let y of mT)if(Q[y]!==void 0)return J0(X,$,J,H,Z,`field "${y}" is only allowed on .event.md specs`)}let A=xf(Q.prompt),P=H.trim(),B=A??(P.length>0?P:void 0);if(!B)return J0(X,$,J,H,Z,"prompt is required (frontmatter `prompt` or markdown body)");let Y=xf(Q.workspaceRoot);if(!Y)return J0(X,$,J,H,Z,"workspaceRoot is required");let V,R;try{V=CT(Q.tools),R=ST(Q.extensions)}catch(y){return J0(X,$,J,H,Z,y instanceof Error?y.message:String(y))}let U=wT(Q.mode);if(Q.mode!==void 0&&U===void 0)return J0(X,$,J,H,Z,"mode must be one of: act, plan, yolo");let K={id:j,title:xf(Q.title)??j??kT($),prompt:B,workspaceRoot:Y,mode:U??"yolo",systemPrompt:xf(Q.systemPrompt),modelSelection:qT(Q.modelSelection),maxIterations:EH(Q.maxIterations),timeoutSeconds:EH(Q.timeoutSeconds),tools:V,notesDirectory:xf(Q.notesDirectory),extensions:R,source:xf(Q.source)??"user",tags:NT(Q.tags),enabled:typeof Q.enabled==="boolean"?Q.enabled:!0,metadata:kH(Q.metadata)},F;if(J==="schedule"){let y=xf(Q.schedule);if(!y)return J0(X,$,J,H,Z,"schedule is required for *.cron.md specs");let D=xf(Q.timezone);try{I3(y,D)}catch(T){return J0(X,$,J,H,Z,T instanceof Error?T.message:String(T))}F={...K,triggerKind:"schedule",schedule:y,timezone:D}}else if(J==="event"){let y=xf(Q.event);if(!y)return J0(X,$,J,H,Z,"event is required for .event.md specs");F={...K,triggerKind:"event",event:y,filters:kH(Q.filters),debounceSeconds:SH(Q.debounceSeconds),dedupeWindowSeconds:SH(Q.dedupeWindowSeconds),cooldownSeconds:SH(Q.cooldownSeconds),maxParallel:EH(Q.maxParallel)}}else F={...K,triggerKind:"one_off"};return{externalId:X,relativePath:$,triggerKind:J,body:H,contentHash:Z,spec:F}}function lT(f,$){return dT(f,$).replace(/\\/g,"/")}function pT(f){if(!gT(f))return[];let $=[],J=[f];while(J.length>0){let W=J.pop();if(!W)continue;let H;try{H=vT(W,{withFileTypes:!0})}catch{continue}for(let Q of H){let Z=`${W}/${Q.name}`;if(Q.isDirectory()){if(Q.name==="reports")continue;J.push(Z);continue}if(!Q.isFile())continue;if(!Q.name.endsWith(".md"))continue;$.push(Z)}}return $}class mH{store;cronDir;constructor(f){this.store=f.store,this.cronDir=rT(f.specs??(f.workspaceRoot?{scope:"workspace",workspaceRoot:f.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let f={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},$=pT(this.cronDir),J=new Set;for(let H of $){let Q=lT(this.cronDir,H);J.add(Q),f.scanned+=1;let Z=await this.reconcileFile(Q,H);if(Z){if(f.changes.push(Z),f.upserted+=1,Z.parse.error)f.invalidParses+=1}}let W=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let H of W)if(!J.has(H.sourcePath))this.handleFileDeleted(H),f.removed+=1;return this.refreshScheduleNextRunAt(),f}async reconcileFile(f,$){let J=this.store.getSpecBySourcePath(f),W,H;try{W=uT($,"utf8"),H=cT($).mtimeMs}catch{return}let Z=MX({relativePath:f,raw:W}),j=this.store.upsertSpec({externalId:Z.externalId,sourcePath:f,triggerKind:Z.triggerKind,sourceMtimeMs:H,sourceHash:Z.contentHash,parseStatus:Z.error?"invalid":"valid",parseError:Z.error,spec:Z.spec});if(!Z.error&&Z.triggerKind==="schedule"&&j.record.enabled)this.applyScheduleNextRunAt(j.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==j.record.scheduleExpr||J.timezone!==j.record.timezone});return{relativePath:f,result:j,parse:Z}}handleFileDeleted(f){this.store.markSpecRemoved(f.specId),this.store.cancelQueuedRunsForSpec(f.specId)}refreshScheduleNextRunAt(){let f=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let $ of f)this.applyScheduleNextRunAt($,{forceReset:!1})}applyScheduleNextRunAt(f,$){if(!f.scheduleExpr)return;if(!$.forceReset&&f.nextRunAt)return;try{let J=Date.now(),W=f.lastRunAt?Math.max(J,new Date(f.lastRunAt).getTime()):J,H=F$(f.scheduleExpr,W,f.timezone),Q=new Date(H).toISOString();if(f.nextRunAt!==Q)this.store.updateSpecNextRunAt(f.specId,Q)}catch{}}}import{existsSync as iT,mkdirSync as nT,watch as aT}from"node:fs";import{relative as tT,resolve as sT}from"node:path";var oT=250;class xH{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor(f){this.reconciler=f.reconciler,this.debounceMs=Math.max(0,f.debounceMs??oT),this.onError=f.onError??(()=>{}),this.onReconciled=f.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let f=this.reconciler.getCronDir();try{nT(f,{recursive:!0}),this.watcher=aT(f,{recursive:!0},($,J)=>{if(!J)return;let W=String(J).replace(/\\/g,"/");if(!W.endsWith(".md"))return;if(W.startsWith("reports/"))return;this.scheduleReconcile(W)}),this.watcher.on("error",this.onError)}catch($){this.onError($)}}stop(){for(let f of this.pending.values())clearTimeout(f);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile(f){let $=this.pending.get(f);if($)clearTimeout($);let J=setTimeout(()=>{this.pending.delete(f),this.reconcileNow(f)},this.debounceMs);this.pending.set(f,J)}async reconcileNow(f){try{let $=sT(this.reconciler.getCronDir(),f);if(!iT($)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=tT(this.reconciler.getCronDir(),$).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,$),await this.onReconciled()}catch($){this.onError($)}}}class Z4{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new h2({dbPath:f.dbPath});let $=f.specs;this.reconciler=new mH({store:this.store,specs:$}),this.materializer=new U2({store:this.store}),this.eventIngress=new CH({store:this.store,logger:f.logger}),this.runner=new D2({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:f.workspaceRoot,specs:$,logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency}),this.watcher=new xH({reconciler:this.reconciler,debounceMs:f.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let W=f.logger;if(W)if(W.error)W.error("cron.watcher.failed",{error:J});else W.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs(f){return this.store.listSpecs(f)}getSpec(f){return this.store.getSpec(f)}listRuns(f){return this.store.listRuns(f)}getRun(f){return this.store.getRun(f)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns(f=20){return this.store.listRuns({status:"queued",limit:f})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent(f){return this.eventIngress.ingestEvent(f)}listEventLogs(f){return this.store.listEventLogs(f)}getEventLog(f){return this.store.getEventLog(f)}}var CX={};N(CX,{manifestToSessionRecord:()=>LJ,listSessionHistoryFromBackend:()=>cH,listSessionHistory:()=>hJ,hydrateSessionHistory:()=>bX});import{readdir as JD,readFile as NX}from"node:fs/promises";import{join as qX}from"node:path";import{formatDisplayUserInput as WD,normalizeUserInput as HD}from"@cline/shared";import{resolveSessionDataDir as wX}from"@cline/shared/storage";import{existsSync as eT}from"node:fs";import{readFile as fD}from"node:fs/promises";import{formatDisplayUserInput as LX}from"@cline/shared";class j4{listeners=new Set;subscribe(f,$){let J={listener:f,sessionId:$?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit(f){let $=f.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$)continue;J.listener(f)}}get size(){return this.listeners.size}}async function X$(f){let $=f?.trim();if(!$||!eT($))return[];try{let J=(await fD($,"utf8")).trim();if(!J)return[];let W=JSON.parse(J);if(Array.isArray(W))return hX(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let H=W.messages;if(Array.isArray(H))return hX(H)}return[]}catch{return[]}}function $D(f){if(f.role!=="user")return f;if(typeof f.content==="string")return{...f,content:LX(f.content)};return{...f,content:f.content.map(($)=>{if($.type!=="text"||typeof $.text!=="string")return $;return{...$,text:LX($.text)}})}}function hX(f){return f.map($D)}function gH(f){return f?{...f}:void 0}async function OX(f,$){if(!(f.hookName==="tool_call"||!!f.parent_agent_id))return;await $.queueSpawnRequest(f);let W=await $.upsertSubagentSessionFromHook(f);if(!W)return;await $.appendSubagentHookAudit(W,f),await $.applySubagentStatus(W,f)}function _J(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function gf(f){let $=_J(f);if(!$)return;return $.toLowerCase()==="unknown"?void 0:$}function MJ(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function QD(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return{...f}}function uH(f){let $=f??200;return Number.isFinite($)?Math.max(0,Math.floor($)):200}function ZD(f){let $=f.match(/\d{13,}/g);if(!$||$.length===0)return 0;let J=0;for(let W of $){let H=Number.parseInt(W,10);if(Number.isFinite(H)&&H>J)J=H}return J}function LJ(f){return{sessionId:f.session_id,source:f.source,pid:f.pid,startedAt:f.started_at,endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspace_root,teamName:f.team_name,enableTools:f.enable_tools,enableSpawn:f.enable_spawn,enableTeams:f.enable_teams,isSubagent:!1,prompt:f.prompt,metadata:f.metadata,messagesPath:f.messages_path,updatedAt:f.ended_at??f.started_at}}async function jD(f){let $=uH(f);if($===0)return[];let J=wX(),H=(await JD(J,{withFileTypes:!0}).catch(()=>[])).filter((Z)=>Z.isDirectory()).map((Z)=>({entry:Z,recency:ZD(Z.name.trim())})).sort((Z,j)=>j.recency-Z.recency||j.entry.name.localeCompare(Z.entry.name));return(await Promise.all(H.map(async({entry:Z})=>{let j=Z.name.trim();if(!j)return;let X=qX(J,j,`${j}.json`),A=await NX(X,"utf8").catch(()=>{return});if(!A)return;let P;try{P=JSON.parse(A)}catch{return}let B=Lf.safeParse(P);if(!B.success)return;return LJ(B.data)}))).filter((Z)=>Boolean(Z)).sort((Z,j)=>j.startedAt.localeCompare(Z.startedAt)).slice(0,$)}async function XD(f,$){let J=uH($);if(J===0)return await f.listSessions(0),[];return(await f.listSessions(J)).slice(0,J)}function AD(f){if(typeof f==="string")return f.trim();let $=[];for(let J of f){if(!J||typeof J!=="object")continue;let W=J;if(W.type!=="text")continue;let H=W.text?.trim();if(H)$.push(H)}return $.join(`
473
+ `).trim()}function zX(f){return f.replace(/\s+/g," ").trim()}function PD(f,$){if(f.length<=$)return f;return`${f.slice(0,Math.max(0,$-3)).trimEnd()}...`}function BD(f){for(let $ of["user","assistant"])for(let J of f){if(J.role!==$)continue;let W=zX(AD(J.content));if(!W)continue;let H=$==="user"?zX(WD(W)):W,Q=HD(H.split(`
474
+ `)[0]??H);return PD(Q,50)}return}function YD(f){let $=0;for(let J of f)$+=MJ(J.metrics?.cost)??0;return $}function VD(f){let $,J;for(let W=f.length-1;W>=0;W-=1){let H=f[W];if(!$)$=gf(H.modelInfo?.provider);if(!J)J=gf(H.modelInfo?.id);if($&&J)break}return{provider:$,model:J}}function RD(f){return gf(f?.provider)??gf(f?.provider&&typeof f.provider==="object"&&!Array.isArray(f.provider)?f.provider.id:void 0)}function FD(f){return gf(f?.model)??gf(f?.model&&typeof f.model==="object"&&!Array.isArray(f.model)?f.model.id:void 0)}function vH(f,$){let J=QD(f.metadata),W=_J($?.title)??_J(J?.title),H=MJ($?.totalCost)??MJ(J?.totalCost),Q=J||W!==void 0||H!==void 0?{...J??{},...W!==void 0?{title:W}:{},...H!==void 0?{totalCost:H}:{}}:void 0;return{...f,provider:gf($?.provider)??gf(f.provider)??RD(J)??"",model:gf($?.model)??gf(f.model)??FD(J)??"",metadata:Q}}async function bX(f,$){return await Promise.all($.map(async(J)=>{let W=vH(J),H=Boolean(_J(W.metadata?.title)),Q=Boolean(gf(W.provider)),Z=Boolean(gf(W.model)),j=MJ(W.metadata?.totalCost),X=j!==void 0&&j>0;if(H&&Q&&Z&&X)return W;let A=await f.readSessionMessages(J.sessionId);if(A.length===0)return W;let P=VD(A),B=YD(A);return vH(J,{title:H?void 0:BD(A),provider:Q?void 0:P.provider,model:Z?void 0:P.model,totalCost:X||B<=0?void 0:B})}))}async function hJ(f,$={}){let J=uH($.limit),W=await XD(f,J),H=$.includeManifestFallback===!0&&W.length<J?await jD(Math.min(Math.max(J*2,100),500)):[],Q=new Map;for(let j of[...W,...H]){if(Q.has(j.sessionId))continue;Q.set(j.sessionId,j)}let Z=H.length===0?W:Array.from(Q.values()).sort((j,X)=>X.startedAt.localeCompare(j.startedAt)).slice(0,J);if($.hydrate===!1)return Z.map((j)=>vH(j));return await bX(f,Z)}async function KD(f){let $=f.trim();if(!$)return;let J=qX(wX(),$,`${$}.json`),W=await NX(J,"utf8").catch(()=>{return});if(!W)return;try{let H=Lf.safeParse(JSON.parse(W));return H.success?H.data.messages_path:void 0}catch{return}}async function cH(f,$={}){let J=new Map;return await hJ({listSessions:async(H)=>{let Q=await f.listSessions(H);J.clear();for(let Z of Q)J.set(Z.sessionId,Z);return Q.map(V8)},readSessionMessages:async(H)=>{let Q=J.get(H)?.messagesPath??await KD(H);return await X$(Q)}},$)}var BA={};N(BA,{resolveSessionBackend:()=>X9,createRuntimeHost:()=>J2});var dX={};N(dX,{HubRuntimeHost:()=>q0});import{createSessionId as SX,HUB_CHECKPOINT_CAPABILITY as TD,HUB_COMPACTION_CAPABILITY as DD,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as _D,HUB_HOOK_CAPABILITY_PREFIX as MD,HUB_MISTAKE_LIMIT_CAPABILITY as LD,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as hD,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as OD,isHubToolExecutorName as zD}from"@cline/shared";var EX={};N(EX,{createCoreSessionSnapshot:()=>W0,coreSessionSnapshotToRecord:()=>OJ});function yD(f){return f?JSON.parse(JSON.stringify(f)):void 0}function UD(f){return f?JSON.parse(JSON.stringify(f)):void 0}function GD(f){let $=f?.checkpoint&&typeof f.checkpoint==="object"&&!Array.isArray(f.checkpoint)?f.checkpoint:void 0,W=(Array.isArray($?.history)?$.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let j=typeof Z.ref==="string"?Z.ref.trim():"",X=Number(Z.createdAt),A=Number(Z.runCount);if(!j||!Number.isFinite(X)||!Number.isInteger(A))return[];return[{ref:j,createdAt:X,runCount:A,...Z.kind==="stash"||Z.kind==="commit"?{kind:Z.kind}:{}}]}),H=W.at(-1),Q=f?.checkpointEnabled===!0?!0:void 0;if(!Q&&W.length===0)return;return{...Q?{enabled:Q}:{},...H?{latest:H}:{},history:W}}function W0(f){let{session:$}=f,J=yD($.metadata);return{version:1,sessionId:$.sessionId,source:$.source,status:$.status,createdAt:$.startedAt,updatedAt:$.updatedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,interactive:$.interactive,workspace:{cwd:$.cwd,root:$.workspaceRoot},model:{providerId:$.provider,modelId:$.model},capabilities:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams},lineage:{...$.parentSessionId?{parentSessionId:$.parentSessionId}:{},...$.parentAgentId?{parentAgentId:$.parentAgentId}:{},...$.agentId?{agentId:$.agentId}:{},...$.conversationId?{conversationId:$.conversationId}:{},isSubagent:$.isSubagent},...$.teamName?{team:{name:$.teamName}}:{},...$.prompt?{prompt:$.prompt}:{},...J?{metadata:J}:{},...$.messagesPath?{artifacts:{messagesPath:$.messagesPath}}:{},...f.messages?{messages:UD(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...f.aggregateUsage?{aggregateUsage:{...f.aggregateUsage}}:{},...(()=>{let W=GD(J);return W?{checkpoint:W}:{}})()}}function OJ(f){return{sessionId:f.sessionId,parentSessionId:f.lineage.parentSessionId,agentId:f.lineage.agentId,parentAgentId:f.lineage.parentAgentId,conversationId:f.lineage.conversationId,isSubagent:f.lineage.isSubagent,source:f.source,startedAt:f.createdAt,endedAt:f.endedAt??void 0,exitCode:f.exitCode??void 0,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspaceRoot:f.workspace.root,teamName:f.team?.name,enableTools:f.capabilities.enableTools,enableSpawn:f.capabilities.enableSpawn,enableTeams:f.capabilities.enableTeams,prompt:f.prompt,metadata:f.metadata,updatedAt:f.updatedAt,messagesPath:f.artifacts?.messagesPath}}function t1(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var ND=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function kX(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function IX(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function mX(f){let $=f&&typeof f==="object"&&!Array.isArray(f)?f:{};return{agentId:typeof $.agentId==="string"?$.agentId:"",conversationId:typeof $.conversationId==="string"?$.conversationId:"",iteration:typeof $.iteration==="number"?$.iteration:0,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}}function r$(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function xX(f,$){let J={manifest:[],handlers:new Map};for(let H of Object.keys($.toolExecutors??{}).filter(zD)){let Q=$.toolExecutors?.[H];if(typeof Q!=="function")continue;r$(J,{kind:"toolExecutor",executor:H,capabilityName:`${hD}${H}`},async({payload:Z,abortSignal:j})=>{let X=Array.isArray(Z.args)?[...Z.args]:[],A={...mX(Z.context),signal:j};return{result:await Q(...X,A)}})}for(let H of f?.extraTools??[])r$(J,{kind:"tool",name:H.name,description:H.description,inputSchema:t1(H.inputSchema)??{},...H.lifecycle?{lifecycle:t1(H.lifecycle)}:{},capabilityName:`${_D}${H.name}`},async({payload:Q,abortSignal:Z,progress:j})=>{let X={...mX(Q.context),signal:Z};return{result:await H.execute(Q.input,{...X,emitUpdate:(P)=>{j({update:P})}})}});let W=f?.hooks;if(W)for(let H of ND){let Q=W[H];if(typeof Q!=="function")continue;r$(J,{kind:"hook",name:H,capabilityName:`${MD}${H}`},async({payload:Z})=>({control:await Q(Z.context)}))}if(f?.compaction?.compact){let H=f.compaction.compact;r$(J,{kind:"compaction",capabilityName:DD,config:kX(f.compaction)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.checkpoint?.createCheckpoint){let H=f.checkpoint.createCheckpoint;r$(J,{kind:"checkpoint",capabilityName:TD,config:kX(f.checkpoint)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.onConsecutiveMistakeLimitReached){let H=f.onConsecutiveMistakeLimitReached;r$(J,{kind:"mistakeLimit",capabilityName:LD},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.userInstructionService){let H=f.userInstructionService;r$(J,{kind:"userInstructionService",capabilityName:OD},async()=>{return await H.start().catch(()=>{}),{snapshot:{records:{skill:H.listRecords("skill"),rule:H.listRecords("rule"),workflow:H.listRecords("workflow")},runtimeCommands:H.listRuntimeCommands()}}})}return J}function qD(f){if(typeof f==="string"&&f.trim())return f.trim();if(f instanceof Error)return f.message;if(f&&typeof f==="object"&&"message"in f){let $=f.message;if(typeof $==="string"&&$.trim())return $.trim()}return"Capability request was cancelled."}function wD(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function bD(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function CD(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=typeof $.inputTokens==="number"?$.inputTokens:void 0,W=typeof $.outputTokens==="number"?$.outputTokens:void 0;if(J===void 0||W===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function gX(f){if(!f)return;return{inputTokens:typeof f.inputTokens==="number"?f.inputTokens:0,outputTokens:typeof f.outputTokens==="number"?f.outputTokens:0,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function rH(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function A$(f,$){return rH(f?.[$])??0}function ED(f){let $=f?.delta&&typeof f.delta==="object"?f.delta:void 0,J=f?.totals&&typeof f.totals==="object"?f.totals:void 0,W=f?.agent&&typeof f.agent==="object"?f.agent:void 0,H=W?.teamRole==="teammate"||W?.teamRole==="lead"?W.teamRole:void 0;return{event:{type:"usage",agentId:typeof W?.agentId==="string"?W.agentId:void 0,conversationId:typeof W?.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W?.parentAgentId==="string"?W.parentAgentId:void 0,inputTokens:A$($,"inputTokens"),outputTokens:A$($,"outputTokens"),cacheReadTokens:A$($,"cacheReadTokens"),cacheWriteTokens:A$($,"cacheWriteTokens"),cost:rH($?.totalCost),totalInputTokens:A$(J,"inputTokens"),totalOutputTokens:A$(J,"outputTokens"),totalCacheReadTokens:A$(J,"cacheReadTokens"),totalCacheWriteTokens:A$(J,"cacheWriteTokens"),totalCost:rH(J?.totalCost)},teamAgentId:typeof W?.teamAgentId==="string"?W.teamAgentId:void 0,teamRole:H}}function SD(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,W=bD(J)?J:J==="failed"?"error":"completed",H=CD(f?.usage??$?.usage);return{type:"done",reason:W,text:typeof f?.text==="string"?f.text:typeof $?.text==="string"?$.text:"",iterations:typeof f?.iterations==="number"?f.iterations:typeof $?.iterations==="number"?$.iterations:0,usage:H}}function dH(f,$){return f.error?.message??`hub command failed: ${$}`}function X4(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function cX(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):void 0;return{sessionId:f.sessionId,parentSessionId:typeof $?.parentSessionId==="string"?$.parentSessionId:void 0,agentId:f.runtimeSession?.agentId||(typeof $?.agentId==="string"?$.agentId:void 0),parentAgentId:typeof $?.parentAgentId==="string"?$.parentAgentId:void 0,conversationId:typeof $?.conversationId==="string"?$.conversationId:void 0,isSubagent:typeof $?.isSubagent==="boolean"?$.isSubagent:!1,source:typeof $?.source==="string"?$.source:Ff.CORE,pid:typeof $?.pid==="number"?$.pid:void 0,startedAt:new Date(f.createdAt).toISOString(),endedAt:X4(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:X4(f.status)==="completed"?0:X4(f.status)==="failed"?1:void 0,status:X4(f.status),interactive:$?.interactive===!0,provider:typeof $?.provider==="string"?$.provider:"hub",model:typeof $?.model==="string"?$.model:"hub",cwd:f.cwd?.trim()||f.workspaceRoot,workspaceRoot:f.workspaceRoot,teamName:typeof $?.teamName==="string"?$.teamName:void 0,enableTools:f.runtimeOptions?.enableTools??$?.enableTools===!0,enableSpawn:f.runtimeOptions?.enableSpawn??$?.enableSpawn===!0,enableTeams:f.runtimeOptions?.enableTeams??$?.enableTeams===!0,prompt:typeof $?.prompt==="string"?$.prompt:void 0,metadata:$,updatedAt:new Date(f.updatedAt).toISOString(),messagesPath:typeof $?.messagesPath==="string"?$.messagesPath:void 0,hookPath:typeof $?.hookPath==="string"?$.hookPath:void 0}}function l$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;return $.version===1&&typeof $.sessionId==="string"?JSON.parse(JSON.stringify($)):void 0}function kD(f){let $=l$(f?.snapshot);if($)return OJ($);let J=f?.session;return J?cX(J):void 0}function vX(f,$,J){let W=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return Lf.parse({version:1,session_id:f,source:$.source??Ff.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:X4(J?.status),interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:J?.cwd?.trim()||$.config.cwd,workspace_root:W,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,metadata:$.sessionMetadata&&Object.keys($.sessionMetadata).length>0?$.sessionMetadata:void 0})}function uX(f,$){return Lf.parse({version:1,session_id:f.sessionId,source:f.source,pid:process.pid,started_at:f.createdAt,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspace_root:f.workspace.root,team_name:f.team?.name,enable_tools:f.capabilities.enableTools,enable_spawn:f.capabilities.enableSpawn,enable_teams:f.capabilities.enableTeams,prompt:(f.prompt??$.prompt?.trim())||void 0,metadata:f.metadata,messages_path:f.artifacts?.messagesPath})}class q0{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new j4;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;constructor(f,$){this.clientContext=$,this.clientOptions={authToken:f.authToken,clientType:f.clientType??"core-hub-runtime",displayName:f.displayName??"core hub runtime",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd},this.defaultCapabilities=Uf(f.capabilities)??{},this.runtimeAddress=f.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient(f.url)}createClient(f){return new pf({...this.clientOptions,url:f})}async replaceClient(f){let $=this.client;this.client=this.createClient(f),this.runtimeAddress=f,await Promise.resolve($.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock(f){if(!A6(f,"session.create"))return!1;let $=await P6({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!$)return!1;return await this.replaceClient($),!0}registerPlannedSession(f,$,J){if(this.sessionCapabilities.set(f,$),J.size>0)this.sessionClientContributionHandlers.set(f,J);this.ensureSessionSubscription(f)}cleanupPlannedSession(f){this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f)}async connect(){await this.client.connect()}async startSession(f){let $=this.resolveCapabilities(f),J=xX(f.localRuntime,$),W=f.config.sessionId?.trim()||SX(),H=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:t1({...f.config,sessionId:W}),metadata:{...f.sessionMetadata??{},source:f.source??Ff.CORE,provider:f.config.providerId,model:f.config.modelId,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,teamName:f.config.teamName,prompt:f.prompt,interactive:f.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...f.localRuntime?.configExtensions?{configExtensions:f.localRuntime.configExtensions}:{}},toolPolicies:t1(f.toolPolicies),initialMessages:f.initialMessages});this.registerPlannedSession(W,$,J.handlers);let Q;try{Q=await H()}catch(A){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(A)){this.registerPlannedSession(W,$,J.handlers);try{Q=await H()}catch(P){throw this.cleanupPlannedSession(W),P}}else throw A}let Z=l$(Q.payload?.snapshot),j=Q.payload?.session,X=(Z?.sessionId??j?.sessionId)?.trim();if(!X)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(X!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(X,$,J.handlers);return{sessionId:X,manifest:Z?uX(Z,f):vX(X,f,j),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.start)throw Error("start is required when restore.messages is true");let W=f.start,H=W?this.resolveCapabilities(W):void 0,Q=W?xX(W.localRuntime,H??{}):{manifest:[],handlers:new Map},Z=W?W.config.sessionId?.trim()||SX():void 0;if(Z&&H)this.sessionCapabilities.set(Z,H);if(Z&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(Z,Q.handlers),this.ensureSessionSubscription(Z);let j;try{j=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...W?{workspaceRoot:W.config.workspaceRoot?.trim()||W.config.cwd,cwd:W.config.cwd??f.cwd,sessionConfig:t1({...W.config,sessionId:Z}),metadata:{...W.sessionMetadata??{},source:W.source??Ff.CORE,provider:W.config.providerId,model:W.config.modelId,enableTools:W.config.enableTools,enableSpawn:W.config.enableSpawnAgent,enableTeams:W.config.enableAgentTeams,teamName:W.config.teamName,prompt:W.prompt,interactive:W.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...W.localRuntime?.configExtensions?{configExtensions:W.localRuntime.configExtensions}:{}},toolPolicies:t1(W.toolPolicies)}:{}},$)}catch(V){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw V}if(!j.ok){let V=typeof j.payload?.error==="string"?j.payload.error:"session.restore failed";if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error(V)}let X=l$(j.payload?.snapshot),A=j.payload?.session,P=(X?.sessionId??A?.sessionId)?.trim();if(J&&!P){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error("Hub checkpoint restore returned no session id")}if(P&&Z&&P!==Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);if(P&&H)this.sessionCapabilities.set(P,H);if(P&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(P,Q.handlers);if(P)this.ensureSessionSubscription(P);let B=Array.isArray(j.payload?.messages)?j.payload.messages:void 0,Y=j.payload?.checkpoint;if(!Y)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:P,startResult:P?{sessionId:P,manifest:X?uX(X,W??{}):vX(P,W??{},A),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:B,checkpoint:Y}}async runTurn(f){return this.ensureSessionSubscription(f.sessionId),(await this.client.command("run.start",{sessionId:f.sessionId,input:f.prompt,attachments:(f.userImages?.length??0)>0||(f.userFiles?.length??0)>0?{...f.userImages?.length?{userImages:f.userImages}:{},...f.userFiles?.length?{userFiles:f.userFiles}:{}}:void 0,delivery:f.delivery,timeoutMs:f.timeoutMs},f.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.pending_prompts",{sessionId:f.sessionId},f.sessionId);return Array.isArray($.payload?.prompts)?$.payload.prompts:[]}async requestPendingPromptUpdate(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.update_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,updated:$.payload?.updated===!0}}async requestPendingPromptDelete(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.remove_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,removed:$.payload?.removed===!0}}async getAccumulatedUsage(f){let $=await this.client.command("session.get",{includeSnapshot:!0},f),J=l$($.payload?.snapshot);if(J){let Z=J.usage?{...J.usage}:void 0,j=J.aggregateUsage?{...J.aggregateUsage}:void 0;return Z||j?{usage:Z,aggregateUsage:j}:void 0}let W=$.payload?.session,H=gX(W?.usage),Q=gX(W?.aggregateUsage);return H||Q?{usage:H,aggregateUsage:Q}:void 0}async abort(f,$){await this.client.command("run.abort",{sessionId:f,reason:typeof $==="string"?$:void 0},f)}async stopSession(f){this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),await this.client.command("session.detach",{sessionId:f},f)}async dispose(){for(let[f,$]of this.sessionSubscriptions){$();try{await this.client.command("session.detach",{sessionId:f},f)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let f of this.activeCapabilityAbortControllers.values())f.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession(f){let $=await this.client.command("session.get",void 0,f);return kD($.payload)}async listSessions(f=100){let $=await this.client.command("session.list",{limit:f}),J=Array.isArray($.payload?.snapshots)?$.payload.snapshots.flatMap((H)=>{let Q=l$(H);return Q?[OJ(Q)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(cX)}async listSettings(f){let $=await this.client.command("settings.list",IX(f));if(!$.ok)throw Error(dH($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",IX(f));if(!$.ok)throw Error(dH($,"settings.toggle"));return{snapshot:$.payload?.snapshot,changedTypes:Array.isArray($.payload?.changedTypes)?$.payload.changedTypes:[]}}async deleteSession(f){return this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),(await this.client.command("session.delete",{sessionId:f})).payload?.deleted===!0}async updateSession(f,$){let J={...$.metadata??{}};if(typeof $.prompt==="string")J.prompt=$.prompt;if(typeof $.title==="string")J.title=$.title;return{updated:(await this.client.command("session.update",{sessionId:f,metadata:J})).ok}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(dH(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async dispatchHookEvent(f){await this.client.command("session.hook",{payload:f})}subscribe(f,$){return this.events.subscribe(f,$)}ensureSessionSubscription(f){let $=f.trim();if(!$||this.sessionSubscriptions.has($))return;let J=this.client.subscribe((W)=>{this.handleHubEvent(W)},{sessionId:$});this.sessionSubscriptions.set($,typeof J==="function"?J:()=>{})}disposeSessionSubscription(f){let $=f.trim();if(!$)return;this.sessionSubscriptions.get($)?.(),this.sessionSubscriptions.delete($),this.agentDoneEmittedForCurrentRunBySession.delete($)}resolveCapabilities(f){return Uf(this.defaultCapabilities,f.capabilities)??{}}emitToolCallContentStart(f){this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:f.toolCallId,toolName:f.toolName,input:f.toolInput}}})}emitAgentDoneIfNeeded(f){if(this.agentDoneEmittedForCurrentRunBySession.has(f.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add(f.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:SD(f.payload)}})}handleHubEvent(f){let $=f.sessionId?.trim();if(f.event==="capability.requested"){this.handleCapabilityRequest(f);return}if(f.event==="capability.resolved"){this.handleCapabilityResolved(f);return}if(f.event==="approval.requested"){this.handleApprovalRequested(f);return}if(!$)return;switch(f.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete($);let J=l$(f.payload?.snapshot),W=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:W?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_start",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_end",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,hadToolCalls:f.payload?.hadToolCalls===!0,toolCallCount:typeof f.payload?.toolCallCount==="number"?f.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"text",text:typeof f.payload?.text==="string"?f.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"",W=f.payload?.redacted===!0;if(!J&&!W)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:W}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"reasoning",reasoning:typeof f.payload?.reasoning==="string"?f.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:$,payload:f.payload});return}case"usage.updated":{let J=ED(f.payload);this.events.emit({type:"agent_event",payload:{sessionId:$,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:$,toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,toolInput:f.payload?.input});return}case"tool.finished":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,output:f.payload?.output,error:typeof f.payload?.error==="string"?f.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=l$(f.payload?.snapshot),W=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:W?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:$,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=f.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:$,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=typeof f.payload?.reason==="string"?f.payload.reason:f.event==="run.aborted"?"aborted":f.event==="run.failed"?"error":"completed";this.emitAgentDoneIfNeeded({sessionId:$,payload:{...f.payload,reason:J}}),this.events.emit({type:"ended",payload:{sessionId:$,reason:J,ts:f.timestamp??Date.now()}});return}default:return}}async handleCapabilityRequest(f){let $=f.sessionId?.trim();if(!$)return;let J=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let W=typeof f.payload?.requestId==="string"?f.payload.requestId:"",H=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName:"";if(!W)return;let Q=this.sessionClientContributionHandlers.get($)?.get(H);if(!Q){await this.client.command("capability.respond",{requestId:W,ok:!1,error:`No client contribution handler registered for capability ${H} in session ${$}.`},$).catch(()=>{});return}let Z=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=new AbortController;this.activeCapabilityAbortControllers.set(W,j);let X=(A)=>{this.client.command("capability.progress",{requestId:W,payload:A},$)};try{let A=await Q({payload:Z,abortSignal:j.signal,progress:X});if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!0,payload:A},$)}catch(A){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:A instanceof Error?A.message:String(A)},$)}finally{this.activeCapabilityAbortControllers.delete(W)}}handleCapabilityResolved(f){if(f.payload?.cancelled!==!0)return;let $=typeof f.payload.requestId==="string"?f.payload.requestId.trim():"";if(!$)return;let J=this.activeCapabilityAbortControllers.get($);if(!J)return;J.abort(qD(f.payload.error))}async handleApprovalRequested(f){let $=f.sessionId?.trim();if(!$)return;let J=this.sessionCapabilities.get($)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let W=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"",H=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:"",Q=typeof f.payload?.toolName==="string"?f.payload.toolName:"";if(!W||!H||!Q)return;let Z=f.payload?.policy&&typeof f.payload.policy==="object"&&!Array.isArray(f.payload.policy)?f.payload.policy:{autoApprove:!1},j=wD(f.payload?.inputJson);this.pendingApprovalToolCallIds.add(H),this.emitToolCallContentStart({sessionId:$,toolCallId:H,toolName:Q,toolInput:j});let X=await Promise.resolve(J({sessionId:$,agentId:typeof f.payload?.agentId==="string"?f.payload.agentId:"",conversationId:typeof f.payload?.conversationId==="string"?f.payload.conversationId:$,iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,toolCallId:H,toolName:Q,input:j,policy:Z})).catch((A)=>({approved:!1,reason:A instanceof Error?A.message:`Tool approval request failed: ${String(A)}`}));await this.client.command("approval.respond",{approvalId:W,approved:X.approved,reason:X.reason},$).catch(()=>{})}}var rX={};N(rX,{RemoteRuntimeHost:()=>s1});class s1 extends q0{constructor(f){super({url:c0(f.endpoint),authToken:f.authToken,clientType:f.clientType??"core-remote-runtime",displayName:f.displayName??"core remote runtime",capabilities:f.capabilities},{workspaceRoot:f.workspaceRoot,cwd:f.cwd})}}var lX={};N(lX,{SqliteSessionStore:()=>Q0});import{existsSync as ID,mkdirSync as mD}from"node:fs";import{join as xD}from"node:path";import{asBool as A4,asOptionalString as H0,asString as w0,ensureSessionSchema as gD,loadSqliteDb as vD,nowIso as zJ,toBoolInt as P4}from"@cline/shared/db";import{resolveDbDataDir as uD}from"@cline/shared/storage";class Q0{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??uD()}init(){this.getRawDb()}ensureSessionsDir(){if(!ID(this.sessionsDirPath))mD(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return xD(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=vD(this.sessionDbPath());return gD(f,{includeLegacyMigrations:!0}),this.db=f,f}close(){this.db?.close?.(),this.db=void 0}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}create(f){let $=zJ();this.run(`INSERT OR REPLACE INTO sessions (
475
475
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
476
476
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
477
477
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
478
478
  metadata_json, transcript_path, hook_path, messages_path, updated_at
479
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,0,Q4(f.interactive),f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,Q4(f.enableTools),Q4(f.enableSpawn),Q4(f.enableTeams),f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,Q4(f.isSubagent),f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"",f.hookPath??"",f.messagesPath??null,$])}update(f){let $=[],J=[];if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(f.metadata?JSON.stringify(f.metadata):null);if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId);if($.length===0)return;$.push("updated_at = ?"),J.push(qJ()),J.push(f.sessionId),this.run(`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`,J)}updateStatus(f,$,J){this.update({sessionId:f,status:$,endedAt:$==="running"?null:qJ(),exitCode:$==="running"?null:J??($==="failed"?1:0)})}get(f){let $=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
479
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,0,P4(f.interactive),f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,P4(f.enableTools),P4(f.enableSpawn),P4(f.enableTeams),f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,P4(f.isSubagent),f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"",f.hookPath??"",f.messagesPath??null,$])}update(f){let $=[],J=[];if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(f.metadata?JSON.stringify(f.metadata):null);if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId);if($.length===0)return;$.push("updated_at = ?"),J.push(zJ()),J.push(f.sessionId),this.run(`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`,J)}updateStatus(f,$,J){this.update({sessionId:f,status:$,endedAt:$==="running"?null:zJ(),exitCode:$==="running"?null:J??($==="failed"?1:0)})}get(f){let $=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
480
480
  provider, model, cwd, workspace_root, team_name,
481
481
  enable_tools, enable_spawn, enable_teams,
482
482
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
483
483
  prompt, metadata_json, hook_path, messages_path, updated_at
484
- FROM sessions WHERE session_id = ?`,[f]);if(!$)return;return{sessionId:L0($.session_id),source:L0($.source),pid:Number($.pid??0),startedAt:L0($.started_at),endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:L0($.status),interactive:W4($.interactive),provider:L0($.provider),model:L0($.model),cwd:L0($.cwd),workspaceRoot:L0($.workspace_root),teamName:H0($.team_name),enableTools:W4($.enable_tools),enableSpawn:W4($.enable_spawn),enableTeams:W4($.enable_teams),parentSessionId:H0($.parent_session_id),parentAgentId:H0($.parent_agent_id),agentId:H0($.agent_id),conversationId:H0($.conversation_id),isSubagent:W4($.is_subagent),prompt:H0($.prompt),metadata:(()=>{let J=H0($.metadata_json);if(!J)return;try{let H=JSON.parse(J);if(H&&typeof H==="object"&&!Array.isArray(H))return H}catch{}return})(),hookPath:H0($.hook_path),messagesPath:H0($.messages_path),updatedAt:H0($.updated_at)??qJ()}}list(f=200){let $=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[f]),J=[];for(let H of $){let W=this.get(L0(H.session_id));if(W)J.push(W)}return J}delete(f,$=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}}s4();import{existsSync as t5,mkdirSync as NT,readFileSync as SP,renameSync as qT,writeFileSync as bT}from"node:fs";import{join as kP}from"node:path";import{resolveSessionDataDir as wT}from"@cline/shared/storage";import{dirname as zT}from"node:path";import{nanoid as OT}from"nanoid";import{appendFileSync as VT,existsSync as YT,mkdirSync as _P,readFileSync as BT,writeFileSync as LP}from"node:fs";import{dirname as zP,join as AT}from"node:path";import{ensureHookLogDir as RT}from"@cline/shared/storage";class g5{adapter;messagesArtifactUploader;artifacts;constructor(f,$){this.adapter=f;this.messagesArtifactUploader=$;this.artifacts=new Q5(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile(f,$,J){HZ($,J,MW(f))}writeSessionManifest(f,$){_P(zP(f),{recursive:!0}),LP(f,`${JSON.stringify(Gf.parse($),null,2)}
485
- `,"utf8")}readSessionManifest(f){return this.readManifestFile(f).manifest}readManifestFile(f){let $=this.artifacts.sessionManifestPath(f,!1);if(!YT($))return{path:$};try{return{path:$,manifest:Gf.parse(JSON.parse(BT($,"utf8")))}}catch{return{path:$}}}async resolveArtifactPath(f,$,J){let W=(await this.adapter.getSession(f))?.[$];return typeof W==="string"&&W.trim().length>0?W:J(f)}async persistSessionMessages(f,$,J){let H=await this.resolveArtifactPath(f,"messagesPath",(Z)=>this.artifacts.sessionMessagesPath(Z)),W=_W({updatedAt:s(),context:MW(f),messages:$,systemPrompt:J}),Q=`${JSON.stringify(W,null,2)}
486
- `;if(_P(zP(H),{recursive:!0}),LP(H,Q,"utf8"),!this.messagesArtifactUploader)return;try{let Z=await this.adapter.getSession(f);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:f,path:H,contents:Q,row:Z})}catch(Z){console.warn(`Failed to upload persisted session messages for ${f}`,Z)}}appendStaleSessionHookLog(f,$,J,H,W){let Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??AT(RT(),"hooks.jsonl");VT(Z,`${JSON.stringify({ts:f,hookName:"session_shutdown",reason:H,sessionId:$,pid:J,source:W})}
487
- `,"utf8")}}import{appendFileSync as FT}from"node:fs";import{join as yT}from"node:path";import{resolveRootSessionId as OP}from"@cline/shared";import{ensureHookLogDir as KT}from"@cline/shared/storage";import{z as v5}from"zod";var UT="subagent",GT=v5.looseObject({task:v5.string().optional(),systemPrompt:v5.string().optional()});class bJ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor(f,$,J,H){this.adapter=f;this.manifestStore=$;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=H}teamTaskQueueKey(f,$){return`${f}::${$}`}activeTeamTaskSessionId(f,$){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey(f,$))?.at(-1)}buildSubsessionRow(f,$){return{sessionId:$.sessionId,source:UT,pid:process.ppid,startedAt:$.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:$.parentSessionId,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId??null,isSubagent:!0,prompt:$.prompt,metadata:B8({prompt:$.prompt}),hookPath:"",messagesPath:$.messagesPath,updatedAt:$.startedAt}}async queueSpawnRequest(f){if(f.hookName!=="tool_call"||f.parent_agent_id!==null)return;if(f.tool_call?.name!=="spawn_agent")return;let $=OP(f.sessionContext);if(!$)return;let J=GT.safeParse(f.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:$,parentAgentId:f.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession(f){let $=f.rootSessionId;if(!$)return;let J=await this.adapter.getSession($);if(!J)return;let H=_1($,f.agentId),W=await this.adapter.getSession(H),Q=s(),Z=this.manifestStore.artifacts.subagentArtifactPaths(H,f.agentId,this.activeTeamTaskSessionId($,f.parentAgentId)),j=f.prompt??W?.prompt??void 0;if(!j)j=await this.adapter.claimSpawnRequest($,f.parentAgentId)??`Subagent run by ${f.parentAgentId}`;if(!W)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:H,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:j,startedAt:Q,...Z})),this.manifestStore.initializeMessagesFile(H,Z.messagesPath,Q),H;return await this.adapter.updateSession({sessionId:H,setRunning:!0,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:W.prompt??j??null,metadata:B8({metadata:W.metadata??void 0,prompt:W.prompt??j??null}),expectedStatusLock:W.statusLock}),H}async upsertSubagentSessionFromHook(f){if(!f.parent_agent_id)return;let $=OP(f.sessionContext);if(!$)return;if(f.hookName==="session_shutdown"){let J=_1($,f.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:f.agent_id,parentAgentId:f.parent_agent_id,conversationId:f.taskId,rootSessionId:$})}async applySubagentStatus(f,$){await this.applySubagentStatusBySessionId(f,X8($))}async applySubagentStatusBySessionId(f,$){let J=await this.adapter.getSession(f);if(!J)return;let H=$==="running"?null:s(),W=$==="running"?null:$==="failed"?1:0;await this.adapter.updateSession({sessionId:f,status:$,endedAt:H,exitCode:W,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions(f,$){if(!f)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:f,status:"running"});for(let H of J)await this.applySubagentStatusBySessionId(H.sessionId,$)}async onTeamTaskStart(f,$,J){let H=await this.adapter.getSession(f);if(!H)return;let W=j8(f,$),Q=s(),{messagesPath:Z}=this.manifestStore.artifacts.subagentArtifactPaths(W,$);await this.adapter.upsertSession(this.buildSubsessionRow(H,{sessionId:W,parentSessionId:f,parentAgentId:"lead",agentId:$,prompt:J||`Team task for ${$}`,startedAt:Q,messagesPath:Z})),this.manifestStore.initializeMessagesFile(W,Z,Q);let j=this.teamTaskQueueKey(f,$),P=this.teamTaskSessionsByAgent.get(j)??[];P.push(W),this.teamTaskSessionsByAgent.set(j,P)}async onTeamTaskEnd(f,$,J,H,W,Q){let Z=this.teamTaskQueueKey(f,$),j=this.teamTaskSessionsByAgent.get(Z);if(!j||j.length===0)return;let P=j.shift();if(j.length===0)this.teamTaskSessionsByAgent.delete(Z);if(!P)return;let X=W?.messages??Q,V=this.toPersistedMessages(X,W,Q);if(V)await this.manifestStore.persistSessionMessages(P,V);await this.applySubagentStatusBySessionId(P,J),this.teamTaskLastHeartbeatBySession.delete(P),this.teamTaskLastProgressLineBySession.delete(P)}async onTeamTaskProgress(f,$,J,H){let W=this.teamTaskQueueKey(f,$),Q=this.teamTaskSessionsByAgent.get(W)?.[0];if(!Q)return;let Z=J.trim();if(!Z)return;let j=H?.kind??"progress";if(j==="heartbeat"){let X=Date.now(),V=this.teamTaskLastHeartbeatBySession.get(Q)??0;if(X-V<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(Q,X)}let P=j==="heartbeat"?"[progress] heartbeat":j==="text"?`[progress] text: ${Z}`:`[progress] ${Z}`;if(this.teamTaskLastProgressLineBySession.get(Q)===P)return;this.teamTaskLastProgressLineBySession.set(Q,P)}async handleSubAgentStart(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;if($.error){await this.applySubagentStatusBySessionId(J,"failed");return}let H=$.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,H==="aborted"?"cancelled":"completed")}appendSubagentHookAudit(f){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??yT(KT(),"hooks.jsonl");FT(J,`${JSON.stringify({ts:s(),...f})}
488
- `,"utf8")}}import{formatUserInputBlock as LT}from"@cline/shared";var EP={};N(EP,{toTeamProgressLifecycleEvent:()=>t1,sanitizeTeamName:()=>K6,reviveTeamStateDates:()=>y6,createWorkerReviewerTeam:()=>CP,createSpawnAgentTool:()=>r0,createDelegatedAgentConfigProvider:()=>h1,createDelegatedAgent:()=>T1,createAgentTeamsTools:()=>z$,createAgentTeam:()=>c5,buildTeamProgressSummary:()=>a1,buildDelegatedAgentConfig:()=>_$,bootstrapAgentTeams:()=>M1,AgentTeamsRuntime:()=>r$,AgentTeam:()=>o1});function Q0(){return new Date().toISOString()}function NP(f,$){if($<=0)return 0;return Math.round(f/$*100)}function hT(f,$){let J=new Set;for(let W of $)if(W.status==="reviewed")J.add(`${W.outcomeId}:${W.section}`);let H=new Set;for(let W of f){if(W.status==="finalized")continue;for(let Q of W.requiredSections)if(!J.has(`${W.id}:${Q}`))H.add(`${W.id}:${Q}`)}return[...H].sort((W,Q)=>W.localeCompare(Q))}function a1(f,$){let J={idle:0,running:0,stopped:0},H={pending:0,in_progress:0,blocked:0,completed:0},W={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},Q={draft:0,in_review:0,finalized:0},Z={draft:0,reviewed:0,rejected:0},j=0,P=0;for(let y of $.members)if(J[y.status]+=1,y.role==="lead")j+=1;else P+=1;let X=[],V=[],Y=$.tasks.filter((y)=>y.status==="completed").length,B=new Map($.tasks.map((y)=>[y.id,y]));for(let y of $.tasks){if(H[y.status]+=1,y.status==="blocked"){X.push(y.id);continue}if(y.status!=="pending")continue;if(y.dependsOn.every((K)=>{return B.get(K)?.status==="completed"}))V.push(y.id)}let A=[],R,U=0;for(let y of $.runs){if(W[y.status]+=1,y.status==="queued"||y.status==="running")A.push(y.id);let F=y.startedAt.getTime();if(F>=U)U=F,R=y.id}for(let y of $.outcomes)Q[y.status]+=1;for(let y of $.outcomeFragments)Z[y.status]+=1;return{teamName:f,updatedAt:Q0(),members:{total:$.members.length,byStatus:J,leadCount:j,teammateCount:P},tasks:{total:$.tasks.length,byStatus:H,blockedTaskIds:X,readyTaskIds:V,completionPct:NP(Y,$.tasks.length)},runs:{total:$.runs.length,byStatus:W,activeRunIds:A,latestRunId:R},outcomes:{total:$.outcomes.length,byStatus:Q,finalizedPct:NP(Q.finalized,$.outcomes.length),missingRequiredSections:hT($.outcomes,$.outcomeFragments)},fragments:{total:$.outcomeFragments.length,byStatus:Z}}}function t1(f){let{event:$}=f;switch($.type){case"team_task_updated":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Q0(),taskId:$.task.id,agentId:$.task.assignee??$.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Q0(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.run.error};case"run_progress":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Q0(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.message};case"outcome_created":case"outcome_finalized":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Q0(),outcomeId:$.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Q0(),outcomeId:$.fragment.outcomeId,fragmentId:$.fragment.id,agentId:$.fragment.sourceAgentId};case"team_message":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Q0(),taskId:$.message.taskId,agentId:$.message.fromAgentId,message:$.message.subject};case"team_mission_log":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Q0(),taskId:$.entry.taskId,agentId:$.entry.agentId,message:$.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Q0(),agentId:$.agentId}}return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Q0()}}import{sanitizeFileName as TT,TeamMessageType as w}from"@cline/shared";import{nanoid as DT}from"nanoid";import{TeamMessageType as KS}from"@cline/shared";function u5(f){if(typeof DOMException<"u"&&f instanceof DOMException&&f.name==="AbortError")return!0;if(!(f instanceof Error))return!1;return f.name==="AbortError"||f.message.toLowerCase().includes("aborted")}function qP(f,$){return f?.status==="stopped"&&u5($)}var MT=600000,bP="recovered_queued";function _T(f){return`This is an automatic recovery of interrupted team run ${f.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
484
+ FROM sessions WHERE session_id = ?`,[f]);if(!$)return;return{sessionId:w0($.session_id),source:w0($.source),pid:Number($.pid??0),startedAt:w0($.started_at),endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:w0($.status),interactive:A4($.interactive),provider:w0($.provider),model:w0($.model),cwd:w0($.cwd),workspaceRoot:w0($.workspace_root),teamName:H0($.team_name),enableTools:A4($.enable_tools),enableSpawn:A4($.enable_spawn),enableTeams:A4($.enable_teams),parentSessionId:H0($.parent_session_id),parentAgentId:H0($.parent_agent_id),agentId:H0($.agent_id),conversationId:H0($.conversation_id),isSubagent:A4($.is_subagent),prompt:H0($.prompt),metadata:(()=>{let J=H0($.metadata_json);if(!J)return;try{let W=JSON.parse(J);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return})(),hookPath:H0($.hook_path),messagesPath:H0($.messages_path),updatedAt:H0($.updated_at)??zJ()}}list(f=200){let $=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[f]),J=[];for(let W of $){let H=this.get(w0(W.session_id));if(H)J.push(H)}return J}delete(f,$=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}}W6();import{existsSync as J9,mkdirSync as Z_,readFileSync as JA,renameSync as j_,writeFileSync as X_}from"node:fs";import{join as WA}from"node:path";import{resolveSessionDataDir as A_}from"@cline/shared/storage";import{dirname as H_}from"node:path";import{nanoid as Q_}from"nanoid";import{appendFileSync as cD,existsSync as dD,mkdirSync as pX,readFileSync as rD,writeFileSync as iX}from"node:fs";import{dirname as nX,join as lD}from"node:path";import{ensureHookLogDir as pD}from"@cline/shared/storage";class lH{adapter;messagesArtifactUploader;artifacts;constructor(f,$){this.adapter=f;this.messagesArtifactUploader=$;this.artifacts=new AH(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile(f,$,J){KZ($,J,hW(f))}writeSessionManifest(f,$){pX(nX(f),{recursive:!0}),iX(f,`${JSON.stringify(Lf.parse($),null,2)}
485
+ `,"utf8")}readSessionManifest(f){return this.readManifestFile(f).manifest}readManifestFile(f){let $=this.artifacts.sessionManifestPath(f,!1);if(!dD($))return{path:$};try{return{path:$,manifest:Lf.parse(JSON.parse(rD($,"utf8")))}}catch{return{path:$}}}async resolveArtifactPath(f,$,J){let H=(await this.adapter.getSession(f))?.[$];return typeof H==="string"&&H.trim().length>0?H:J(f)}async persistSessionMessages(f,$,J){let W=await this.resolveArtifactPath(f,"messagesPath",(Z)=>this.artifacts.sessionMessagesPath(Z)),H=OW({updatedAt:s(),context:hW(f),messages:$,systemPrompt:J}),Q=`${JSON.stringify(H,null,2)}
486
+ `;if(pX(nX(W),{recursive:!0}),iX(W,Q,"utf8"),!this.messagesArtifactUploader)return;try{let Z=await this.adapter.getSession(f);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:f,path:W,contents:Q,row:Z})}catch(Z){console.warn(`Failed to upload persisted session messages for ${f}`,Z)}}appendStaleSessionHookLog(f,$,J,W,H){let Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??lD(pD(),"hooks.jsonl");cD(Z,`${JSON.stringify({ts:f,hookName:"session_shutdown",reason:W,sessionId:$,pid:J,source:H})}
487
+ `,"utf8")}}import{appendFileSync as iD}from"node:fs";import{join as nD}from"node:path";import{resolveRootSessionId as aX}from"@cline/shared";import{ensureHookLogDir as aD}from"@cline/shared/storage";import{z as pH}from"zod";var tD="subagent",sD=pH.looseObject({task:pH.string().optional(),systemPrompt:pH.string().optional()});class NJ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor(f,$,J,W){this.adapter=f;this.manifestStore=$;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=W}teamTaskQueueKey(f,$){return`${f}::${$}`}activeTeamTaskSessionId(f,$){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey(f,$))?.at(-1)}buildSubsessionRow(f,$){return{sessionId:$.sessionId,source:tD,pid:process.ppid,startedAt:$.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:$.parentSessionId,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId??null,isSubagent:!0,prompt:$.prompt,metadata:R8({prompt:$.prompt}),hookPath:"",messagesPath:$.messagesPath,updatedAt:$.startedAt}}async queueSpawnRequest(f){if(f.hookName!=="tool_call"||f.parent_agent_id!==null)return;if(f.tool_call?.name!=="spawn_agent")return;let $=aX(f.sessionContext);if(!$)return;let J=sD.safeParse(f.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:$,parentAgentId:f.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession(f){let $=f.rootSessionId;if(!$)return;let J=await this.adapter.getSession($);if(!J)return;let W=O1($,f.agentId),H=await this.adapter.getSession(W),Q=s(),Z=this.manifestStore.artifacts.subagentArtifactPaths(W,f.agentId,this.activeTeamTaskSessionId($,f.parentAgentId)),j=f.prompt??H?.prompt??void 0;if(!j)j=await this.adapter.claimSpawnRequest($,f.parentAgentId)??`Subagent run by ${f.parentAgentId}`;if(!H)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:W,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:j,startedAt:Q,...Z})),this.manifestStore.initializeMessagesFile(W,Z.messagesPath,Q),W;return await this.adapter.updateSession({sessionId:W,setRunning:!0,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:H.prompt??j??null,metadata:R8({metadata:H.metadata??void 0,prompt:H.prompt??j??null}),expectedStatusLock:H.statusLock}),W}async upsertSubagentSessionFromHook(f){if(!f.parent_agent_id)return;let $=aX(f.sessionContext);if(!$)return;if(f.hookName==="session_shutdown"){let J=O1($,f.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:f.agent_id,parentAgentId:f.parent_agent_id,conversationId:f.taskId,rootSessionId:$})}async applySubagentStatus(f,$){await this.applySubagentStatusBySessionId(f,B8($))}async applySubagentStatusBySessionId(f,$){let J=await this.adapter.getSession(f);if(!J)return;let W=$==="running"?null:s(),H=$==="running"?null:$==="failed"?1:0;await this.adapter.updateSession({sessionId:f,status:$,endedAt:W,exitCode:H,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions(f,$){if(!f)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:f,status:"running"});for(let W of J)await this.applySubagentStatusBySessionId(W.sessionId,$)}async onTeamTaskStart(f,$,J){let W=await this.adapter.getSession(f);if(!W)return;let H=A8(f,$),Q=s(),{messagesPath:Z}=this.manifestStore.artifacts.subagentArtifactPaths(H,$);await this.adapter.upsertSession(this.buildSubsessionRow(W,{sessionId:H,parentSessionId:f,parentAgentId:"lead",agentId:$,prompt:J||`Team task for ${$}`,startedAt:Q,messagesPath:Z})),this.manifestStore.initializeMessagesFile(H,Z,Q);let j=this.teamTaskQueueKey(f,$),X=this.teamTaskSessionsByAgent.get(j)??[];X.push(H),this.teamTaskSessionsByAgent.set(j,X)}async onTeamTaskEnd(f,$,J,W,H,Q){let Z=this.teamTaskQueueKey(f,$),j=this.teamTaskSessionsByAgent.get(Z);if(!j||j.length===0)return;let X=j.shift();if(j.length===0)this.teamTaskSessionsByAgent.delete(Z);if(!X)return;let A=H?.messages??Q,P=this.toPersistedMessages(A,H,Q);if(P)await this.manifestStore.persistSessionMessages(X,P);await this.applySubagentStatusBySessionId(X,J),this.teamTaskLastHeartbeatBySession.delete(X),this.teamTaskLastProgressLineBySession.delete(X)}async onTeamTaskProgress(f,$,J,W){let H=this.teamTaskQueueKey(f,$),Q=this.teamTaskSessionsByAgent.get(H)?.[0];if(!Q)return;let Z=J.trim();if(!Z)return;let j=W?.kind??"progress";if(j==="heartbeat"){let A=Date.now(),P=this.teamTaskLastHeartbeatBySession.get(Q)??0;if(A-P<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(Q,A)}let X=j==="heartbeat"?"[progress] heartbeat":j==="text"?`[progress] text: ${Z}`:`[progress] ${Z}`;if(this.teamTaskLastProgressLineBySession.get(Q)===X)return;this.teamTaskLastProgressLineBySession.set(Q,X)}async handleSubAgentStart(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;if($.error){await this.applySubagentStatusBySessionId(J,"failed");return}let W=this.toPersistedMessages($.agentResult?.messages,$.agentResult);if(W)await this.manifestStore.persistSessionMessages(J,W);let H=$.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,H==="aborted"?"cancelled":"completed")}appendSubagentHookAudit(f){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??nD(aD(),"hooks.jsonl");iD(J,`${JSON.stringify({ts:s(),...f})}
488
+ `,"utf8")}}import{formatUserInputBlock as W_}from"@cline/shared";var $A={};N($A,{toTeamProgressLifecycleEvent:()=>e1,sanitizeTeamName:()=>XZ,reviveTeamStateDates:()=>_6,createWorkerReviewerTeam:()=>fA,createSpawnAgentTool:()=>t0,createDelegatedAgentConfigProvider:()=>_1,createDelegatedAgent:()=>M1,createAgentTeamsTools:()=>q$,createAgentTeam:()=>nH,buildTeamProgressSummary:()=>o1,buildDelegatedAgentConfig:()=>z$,bootstrapAgentTeams:()=>h1,AgentTeamsRuntime:()=>p$,AgentTeam:()=>$2});function Z0(){return new Date().toISOString()}function tX(f,$){if($<=0)return 0;return Math.round(f/$*100)}function oD(f,$){let J=new Set;for(let H of $)if(H.status==="reviewed")J.add(`${H.outcomeId}:${H.section}`);let W=new Set;for(let H of f){if(H.status==="finalized")continue;for(let Q of H.requiredSections)if(!J.has(`${H.id}:${Q}`))W.add(`${H.id}:${Q}`)}return[...W].sort((H,Q)=>H.localeCompare(Q))}function o1(f,$){let J={idle:0,running:0,stopped:0},W={pending:0,in_progress:0,blocked:0,completed:0},H={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},Q={draft:0,in_review:0,finalized:0},Z={draft:0,reviewed:0,rejected:0},j=0,X=0;for(let K of $.members)if(J[K.status]+=1,K.role==="lead")j+=1;else X+=1;let A=[],P=[],B=$.tasks.filter((K)=>K.status==="completed").length,Y=new Map($.tasks.map((K)=>[K.id,K]));for(let K of $.tasks){if(W[K.status]+=1,K.status==="blocked"){A.push(K.id);continue}if(K.status!=="pending")continue;if(K.dependsOn.every((y)=>{return Y.get(y)?.status==="completed"}))P.push(K.id)}let V=[],R,U=0;for(let K of $.runs){if(H[K.status]+=1,K.status==="queued"||K.status==="running")V.push(K.id);let F=K.startedAt.getTime();if(F>=U)U=F,R=K.id}for(let K of $.outcomes)Q[K.status]+=1;for(let K of $.outcomeFragments)Z[K.status]+=1;return{teamName:f,updatedAt:Z0(),members:{total:$.members.length,byStatus:J,leadCount:j,teammateCount:X},tasks:{total:$.tasks.length,byStatus:W,blockedTaskIds:A,readyTaskIds:P,completionPct:tX(B,$.tasks.length)},runs:{total:$.runs.length,byStatus:H,activeRunIds:V,latestRunId:R},outcomes:{total:$.outcomes.length,byStatus:Q,finalizedPct:tX(Q.finalized,$.outcomes.length),missingRequiredSections:oD($.outcomes,$.outcomeFragments)},fragments:{total:$.outcomeFragments.length,byStatus:Z}}}function e1(f){let{event:$}=f;switch($.type){case"team_task_updated":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Z0(),taskId:$.task.id,agentId:$.task.assignee??$.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Z0(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.run.error};case"run_progress":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Z0(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.message};case"outcome_created":case"outcome_finalized":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Z0(),outcomeId:$.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Z0(),outcomeId:$.fragment.outcomeId,fragmentId:$.fragment.id,agentId:$.fragment.sourceAgentId};case"team_message":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Z0(),taskId:$.message.taskId,agentId:$.message.fromAgentId,message:$.message.subject};case"team_mission_log":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Z0(),taskId:$.entry.taskId,agentId:$.entry.agentId,message:$.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Z0(),agentId:$.agentId}}return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:Z0()}}import{sanitizeFileName as eD,TeamMessageType as C}from"@cline/shared";import{nanoid as f_}from"nanoid";import{TeamMessageType as jk}from"@cline/shared";function iH(f){if(typeof DOMException<"u"&&f instanceof DOMException&&f.name==="AbortError")return!0;if(!(f instanceof Error))return!1;return f.name==="AbortError"||f.message.toLowerCase().includes("aborted")}function sX(f,$){return f?.status==="stopped"&&iH($)}var $_=600000,oX="recovered_queued";function J_(f){return`This is an automatic recovery of interrupted team run ${f.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
489
489
 
490
- ${f.message}`}class o1{agents=new Map;configs=new Map;onTeamEvent;constructor(f,$){if(this.onTeamEvent=$,f)for(let[J,H]of Object.entries(f))this.addAgent(J,H)}addAgent(f,$){if(this.agents.has(f))throw Error(`Agent with id "${f}" already exists in the team`);let J={...$,onEvent:(W)=>{$.onEvent?.(W),this.emitEvent({type:w.AgentEvent,agentId:f,event:W})}},H=new d0(J);if(J.onEvent)H.subscribeEvents(J.onEvent);this.agents.set(f,H),this.configs.set(f,$)}removeAgent(f){return this.configs.delete(f),this.agents.delete(f)}getAgent(f){return this.agents.get(f)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:w.TaskStart,agentId:f,message:$});try{let H=await J.run($);return this.emitEvent({type:w.TaskEnd,agentId:f,result:H}),H}catch(H){let W=H instanceof Error?H:Error(String(H));throw this.emitEvent({type:w.TaskEnd,agentId:f,error:W,messages:J.getMessages()}),H}}async continueTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:w.TaskStart,agentId:f,message:$});try{let H=await J.continue($);return this.emitEvent({type:w.TaskEnd,agentId:f,result:H}),H}catch(H){let W=H instanceof Error?H:Error(String(H));throw this.emitEvent({type:w.TaskEnd,agentId:f,error:W,messages:J.getMessages()}),H}}async runParallel(f){let $=f.map(async(J)=>{let H=this.agents.get(J.agentId);if(!H)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:w.TaskStart,agentId:J.agentId,message:J.message});try{let W=await H.run(J.message);return this.emitEvent({type:w.TaskEnd,agentId:J.agentId,result:W}),{agentId:J.agentId,result:W,metadata:J.metadata}}catch(W){let Q=W instanceof Error?W:Error(String(W));return this.emitEvent({type:w.TaskEnd,agentId:J.agentId,error:Q,messages:H.getMessages()}),{agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata}}});return Promise.all($)}async runSequential(f){let $=[];for(let J of f){let H=this.agents.get(J.agentId);if(!H){$.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:w.TaskStart,agentId:J.agentId,message:J.message});try{let W=await H.run(J.message);this.emitEvent({type:w.TaskEnd,agentId:J.agentId,result:W}),$.push({agentId:J.agentId,result:W,metadata:J.metadata})}catch(W){let Q=W instanceof Error?W:Error(String(W));this.emitEvent({type:w.TaskEnd,agentId:J.agentId,error:Q,messages:H.getMessages()}),$.push({agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata})}}return $}async runPipeline(f,$,J){let H=[],W=$;for(let Q of f){let Z=this.agents.get(Q);if(!Z){H.push({agentId:Q,result:void 0,error:Error(`Agent "${Q}" not found in team`)});break}this.emitEvent({type:w.TaskStart,agentId:Q,message:W});try{let j=await Z.run(W);this.emitEvent({type:w.TaskEnd,agentId:Q,result:j}),H.push({agentId:Q,result:j});let P=f.indexOf(Q)+1;if(P<f.length){let X=f[P];W=J?J(j,X):`Previous agent output:
490
+ ${f.message}`}class $2{agents=new Map;configs=new Map;onTeamEvent;constructor(f,$){if(this.onTeamEvent=$,f)for(let[J,W]of Object.entries(f))this.addAgent(J,W)}addAgent(f,$){if(this.agents.has(f))throw Error(`Agent with id "${f}" already exists in the team`);let J={...$,onEvent:(H)=>{$.onEvent?.(H),this.emitEvent({type:C.AgentEvent,agentId:f,event:H})}},W=new a0(J);if(J.onEvent)W.subscribeEvents(J.onEvent);this.agents.set(f,W),this.configs.set(f,$)}removeAgent(f){return this.configs.delete(f),this.agents.delete(f)}getAgent(f){return this.agents.get(f)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:C.TaskStart,agentId:f,message:$});try{let W=await J.run($);return this.emitEvent({type:C.TaskEnd,agentId:f,result:W}),W}catch(W){let H=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:C.TaskEnd,agentId:f,error:H,messages:J.getMessages()}),W}}async continueTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:C.TaskStart,agentId:f,message:$});try{let W=await J.continue($);return this.emitEvent({type:C.TaskEnd,agentId:f,result:W}),W}catch(W){let H=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:C.TaskEnd,agentId:f,error:H,messages:J.getMessages()}),W}}async runParallel(f){let $=f.map(async(J)=>{let W=this.agents.get(J.agentId);if(!W)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:C.TaskStart,agentId:J.agentId,message:J.message});try{let H=await W.run(J.message);return this.emitEvent({type:C.TaskEnd,agentId:J.agentId,result:H}),{agentId:J.agentId,result:H,metadata:J.metadata}}catch(H){let Q=H instanceof Error?H:Error(String(H));return this.emitEvent({type:C.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),{agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata}}});return Promise.all($)}async runSequential(f){let $=[];for(let J of f){let W=this.agents.get(J.agentId);if(!W){$.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:C.TaskStart,agentId:J.agentId,message:J.message});try{let H=await W.run(J.message);this.emitEvent({type:C.TaskEnd,agentId:J.agentId,result:H}),$.push({agentId:J.agentId,result:H,metadata:J.metadata})}catch(H){let Q=H instanceof Error?H:Error(String(H));this.emitEvent({type:C.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),$.push({agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata})}}return $}async runPipeline(f,$,J){let W=[],H=$;for(let Q of f){let Z=this.agents.get(Q);if(!Z){W.push({agentId:Q,result:void 0,error:Error(`Agent "${Q}" not found in team`)});break}this.emitEvent({type:C.TaskStart,agentId:Q,message:H});try{let j=await Z.run(H);this.emitEvent({type:C.TaskEnd,agentId:Q,result:j}),W.push({agentId:Q,result:j});let X=f.indexOf(Q)+1;if(X<f.length){let A=f[X];H=J?J(j,A):`Previous agent output:
491
491
  ${j.text}
492
492
 
493
- Please continue from here.`}}catch(j){let P=j instanceof Error?j:Error(String(j));this.emitEvent({type:w.TaskEnd,agentId:Q,error:P,messages:Z.getMessages()}),H.push({agentId:Q,result:void 0,error:P});break}}return H}abortAll(){for(let f of this.agents.values())f.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}function c5(f,$){return new o1(f,$)}function CP(f){let $=c5({worker:f.worker,reviewer:f.reviewer}),J=$;return J.doAndReview=async(H)=>{let W=await $.routeTo("worker",H),Q=await $.routeTo("reviewer",`Please review this work:
493
+ Please continue from here.`}}catch(j){let X=j instanceof Error?j:Error(String(j));this.emitEvent({type:C.TaskEnd,agentId:Q,error:X,messages:Z.getMessages()}),W.push({agentId:Q,result:void 0,error:X});break}}return W}abortAll(){for(let f of this.agents.values())f.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}function nH(f,$){return new $2(f,$)}function fA(f){let $=nH({worker:f.worker,reviewer:f.reviewer}),J=$;return J.doAndReview=async(W)=>{let H=await $.routeTo("worker",W),Q=await $.routeTo("reviewer",`Please review this work:
494
494
 
495
- ${W.text}`);return{workerResult:W,reviewResult:Q}},J}class r${teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor(f){this.teamName=f.teamName,this.teamId=`t_${TT(DT(10))}`,this.onTeamEvent=f.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,f.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,f.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,f.maxConcurrentRuns??2);let $=f.leadAgentId??"lead";this.members.set($,{agentId:$,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole(f){return this.members.get(f)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter((f)=>f.role==="teammate").map((f)=>f.agentId)}getTask(f){return this.tasks.get(f)}listTasks(){return Array.from(this.tasks.values())}listTaskItems(f){return Array.from(this.tasks.values()).map(($)=>{let J=this.getUnresolvedDependencies($);return{...$,blockedBy:J,isReady:$.status==="pending"&&!$.assignee&&J.length===0}}).filter(($)=>{if(f?.status&&$.status!==f.status)return!1;if(f?.assignee&&$.assignee!==f.assignee)return!1;return!0})}listMissionLog(f){if(!f||f<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-f))}listMailbox(f,$){let J=$?.unreadOnly??!0,H=$?.markRead??!0,W=$?.limit,Q=this.mailbox.filter((j)=>j.toAgentId===f&&(!J||!j.readAt)),Z=typeof W==="number"&&W>0?Q.slice(Math.max(0,Q.length-W)):Q;if(H){let j=new Date;for(let P of Z)if(!P.readAt)P.readAt=j}return Z.map((j)=>({...j}))}getSnapshot(){let f={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())f[J.status]++;let $={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())$[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:f,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:$}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((f)=>({agentId:f.agentId,role:f.role,description:f.description,status:f.status})),tasks:Array.from(this.tasks.values()).map((f)=>({...f})),mailbox:this.mailbox.map((f)=>({...f})),missionLog:this.missionLog.map((f)=>({...f})),runs:Array.from(this.runs.values()).map((f)=>({...f})),outcomes:Array.from(this.outcomes.values()).map((f)=>({...f})),outcomeFragments:Array.from(this.outcomeFragments.values()).map((f)=>({...f}))}}hydrateState(f){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of f.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...f.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...f.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of f.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of f.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of f.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let $=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of $)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of f.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,s1(f.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,s1(f.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,s1(f.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,s1((f.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,s1((f.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,s1((f.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive(f){let $=this.members.get(f);return!!$&&$.role==="teammate"&&!!$.agent}spawnTeammate({agentId:f,config:$}){let J=this.members.get(f);if(J&&J.role!=="teammate")throw Error(`Team member "${f}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${f}" is currently running and cannot be respawned`);let H={...$,apiTimeoutMs:MT,consumePendingUserMessage:()=>{let Z=this.members.get(f);if(!Z||!Z.pendingSteerMessage)return;let j=Z.pendingSteerMessage;return Z.pendingSteerMessage=void 0,j},onEvent:(Z)=>{$.onEvent?.(Z),this.emitEvent({type:w.AgentEvent,agentId:f,event:Z}),this.trackMeaningfulEvent(f,Z)}},W=new d0(H);if(H.onEvent)W.subscribeEvents(H.onEvent);let Q={agentId:f,role:"teammate",description:$.role,status:"idle",agent:W,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set(f,Q),this.emitEvent({type:w.TeammateSpawned,agentId:f,role:$.role,teammate:{rolePrompt:$.systemPrompt,modelId:$.modelId,maxIterations:$.maxIterations,runtimeAgentId:W.getAgentId(),conversationId:W.getConversationId(),parentAgentId:null}}),{agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status}}shutdownTeammate(f,$){let J=this.members.get(f);if(!J||J.role!=="teammate")throw Error(`Teammate "${f}" was not found`);try{J.agent?.abort()}catch(H){if(!u5(H))throw H}J.status="stopped",this.emitEvent({type:w.TeammateShutdown,agentId:f,reason:$})}updateTeammateConnections(f){for(let $ of this.members.values()){if($.role!=="teammate"||!$.agent)continue;$.agent.updateConnection(f)}}createTask(f){let $=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,H={id:$,title:f.title,description:f.description,status:f.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:f.createdBy,assignee:f.assignee,dependsOn:f.dependsOn??[]};return this.tasks.set($,H),this.emitEvent({type:w.TeamTaskUpdated,task:{...H}}),{...H}}claimTask(f,$){let J=this.requireTask(f);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=$,J.updatedAt=new Date,this.emitEvent({type:w.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:$,taskId:f,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask(f,$,J){let H=this.requireTask(f);return H.status="blocked",H.updatedAt=new Date,H.summary=J,this.emitEvent({type:w.TeamTaskUpdated,task:{...H}}),this.appendMissionLog({agentId:$,taskId:f,kind:"blocked",summary:J}),{...H}}completeTask(f,$,J){let H=this.requireTask(f);if(H.status="completed",H.updatedAt=new Date,H.summary=J,!H.assignee)H.assignee=$;return this.emitEvent({type:w.TeamTaskUpdated,task:{...H}}),this.appendMissionLog({agentId:$,taskId:f,kind:"done",summary:J}),{...H}}async routeToTeammate(f,$,J){let H=this.members.get(f);if(!H||H.role!=="teammate"||!H.agent)throw Error(`Teammate "${f}" was not found`);if(!H.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");H.runningCount++,H.status="running",this.emitEvent({type:w.TaskStart,agentId:f,message:$});try{let W=this.listMailbox(f,{unreadOnly:!0,markRead:!0}),Q=W.length>0?`${this.buildMailboxNotification(W)}
495
+ ${H.text}`);return{workerResult:H,reviewResult:Q}},J}class p${teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor(f){this.teamName=f.teamName,this.teamId=`t_${eD(f_(10))}`,this.onTeamEvent=f.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,f.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,f.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,f.maxConcurrentRuns??2);let $=f.leadAgentId??"lead";this.members.set($,{agentId:$,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole(f){return this.members.get(f)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter((f)=>f.role==="teammate").map((f)=>f.agentId)}getTask(f){return this.tasks.get(f)}listTasks(){return Array.from(this.tasks.values())}listTaskItems(f){return Array.from(this.tasks.values()).map(($)=>{let J=this.getUnresolvedDependencies($);return{...$,blockedBy:J,isReady:$.status==="pending"&&!$.assignee&&J.length===0}}).filter(($)=>{if(f?.status&&$.status!==f.status)return!1;if(f?.assignee&&$.assignee!==f.assignee)return!1;return!0})}listMissionLog(f){if(!f||f<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-f))}listMailbox(f,$){let J=$?.unreadOnly??!0,W=$?.markRead??!0,H=$?.limit,Q=this.mailbox.filter((j)=>j.toAgentId===f&&(!J||!j.readAt)),Z=typeof H==="number"&&H>0?Q.slice(Math.max(0,Q.length-H)):Q;if(W){let j=new Date;for(let X of Z)if(!X.readAt)X.readAt=j}return Z.map((j)=>({...j}))}getSnapshot(){let f={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())f[J.status]++;let $={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())$[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:f,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:$}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((f)=>({agentId:f.agentId,role:f.role,description:f.description,status:f.status})),tasks:Array.from(this.tasks.values()).map((f)=>({...f})),mailbox:this.mailbox.map((f)=>({...f})),missionLog:this.missionLog.map((f)=>({...f})),runs:Array.from(this.runs.values()).map((f)=>({...f})),outcomes:Array.from(this.outcomes.values()).map((f)=>({...f})),outcomeFragments:Array.from(this.outcomeFragments.values()).map((f)=>({...f}))}}hydrateState(f){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of f.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...f.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...f.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of f.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of f.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of f.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let $=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of $)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of f.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,f2(f.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,f2(f.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,f2(f.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,f2((f.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,f2((f.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,f2((f.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive(f){let $=this.members.get(f);return!!$&&$.role==="teammate"&&!!$.agent}spawnTeammate({agentId:f,config:$}){let J=this.members.get(f);if(J&&J.role!=="teammate")throw Error(`Team member "${f}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${f}" is currently running and cannot be respawned`);let W={...$,apiTimeoutMs:$_,consumePendingUserMessage:()=>{let Z=this.members.get(f);if(!Z||!Z.pendingSteerMessage)return;let j=Z.pendingSteerMessage;return Z.pendingSteerMessage=void 0,j},onEvent:(Z)=>{$.onEvent?.(Z),this.emitEvent({type:C.AgentEvent,agentId:f,event:Z}),this.trackMeaningfulEvent(f,Z)}},H=new a0(W);if(W.onEvent)H.subscribeEvents(W.onEvent);let Q={agentId:f,role:"teammate",description:$.role,status:"idle",agent:H,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set(f,Q),this.emitEvent({type:C.TeammateSpawned,agentId:f,role:$.role,teammate:{rolePrompt:$.systemPrompt,modelId:$.modelId,maxIterations:$.maxIterations,runtimeAgentId:H.getAgentId(),conversationId:H.getConversationId(),parentAgentId:null}}),{agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status}}shutdownTeammate(f,$){let J=this.members.get(f);if(!J||J.role!=="teammate")throw Error(`Teammate "${f}" was not found`);try{J.agent?.abort()}catch(W){if(!iH(W))throw W}J.status="stopped",this.emitEvent({type:C.TeammateShutdown,agentId:f,reason:$})}updateTeammateConnections(f){for(let $ of this.members.values()){if($.role!=="teammate"||!$.agent)continue;$.agent.updateConnection(f)}}createTask(f){let $=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,W={id:$,title:f.title,description:f.description,status:f.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:f.createdBy,assignee:f.assignee,dependsOn:f.dependsOn??[]};return this.tasks.set($,W),this.emitEvent({type:C.TeamTaskUpdated,task:{...W}}),{...W}}claimTask(f,$){let J=this.requireTask(f);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=$,J.updatedAt=new Date,this.emitEvent({type:C.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:$,taskId:f,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask(f,$,J){let W=this.requireTask(f);return W.status="blocked",W.updatedAt=new Date,W.summary=J,this.emitEvent({type:C.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:$,taskId:f,kind:"blocked",summary:J}),{...W}}completeTask(f,$,J){let W=this.requireTask(f);if(W.status="completed",W.updatedAt=new Date,W.summary=J,!W.assignee)W.assignee=$;return this.emitEvent({type:C.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:$,taskId:f,kind:"done",summary:J}),{...W}}async routeToTeammate(f,$,J){let W=this.members.get(f);if(!W||W.role!=="teammate"||!W.agent)throw Error(`Teammate "${f}" was not found`);if(!W.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");W.runningCount++,W.status="running",this.emitEvent({type:C.TaskStart,agentId:f,message:$});try{let H=this.listMailbox(f,{unreadOnly:!0,markRead:!0}),Q=H.length>0?`${this.buildMailboxNotification(H)}
496
496
 
497
- ${$}`:$,Z=J?.continueConversation?await H.agent.continue(Q):await H.agent.run(Q);return this.emitEvent({type:w.TaskEnd,agentId:f,result:Z}),this.recordProgressStep(f,`Completed a delegated run (${Z.iterations} iterations)`,J?.taskId,!0),Z}catch(W){let Q=W instanceof Error?W:Error(String(W));if(this.emitEvent({type:w.TaskEnd,agentId:f,error:Q,messages:H.agent.getMessages()}),!qP(H,Q))this.appendMissionLog({agentId:f,taskId:J?.taskId,kind:"error",summary:Q.message});throw Q}finally{if(H.runningCount--,H.runningCount<=0&&this.members.get(f)?.status!=="stopped")H.status="idle"}}startTeammateRun(f,$,J){let H=`run_${String(++this.runCounter).padStart(5,"0")}`,W={id:H,agentId:f,taskId:J?.taskId,status:"queued",message:$,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(H,W),this.runQueue.push(H),this.emitEvent({type:w.RunQueued,run:{...W}}),this.dispatchQueuedRuns(),{...W}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let f;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let $=this.selectNextDispatchableQueuedRun();f=$.nextDelayedAttemptAt;let J=$.index;if(J<0){this.scheduleQueuedRunDispatch(f);return}let[H]=this.runQueue.splice(J,1),W=H?this.runs.get(H):void 0;if(!W||W.status!=="queued")continue;this.executeQueuedRun(W)}this.scheduleQueuedRunDispatch(f)}selectNextDispatchableQueuedRun(){let f=-1,$=Number.NEGATIVE_INFINITY,J,H=Date.now();for(let W=0;W<this.runQueue.length;W++){let Q=this.runs.get(this.runQueue[W]);if(!Q||Q.status!=="queued")continue;if(Q.nextAttemptAt&&Q.nextAttemptAt.getTime()>H){if(!J||Q.nextAttemptAt<J)J=Q.nextAttemptAt;continue}if(Q.priority>$)$=Q.priority,f=W}return{index:f,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch(f){if(!f)return;let $=Math.max(0,f.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},$)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let f=0;for(let $ of this.runs.values())if($.status==="running")f++;return f}async executeQueuedRun(f){let $=f.currentActivity===bP;f.nextAttemptAt=void 0,f.status="running",f.startedAt=new Date,f.heartbeatAt=new Date,f.currentActivity="run_started",this.emitEvent({type:w.RunStarted,run:{...f}});let J=setInterval(()=>{if(f.status!=="running")return;this.recordRunProgress(f,"heartbeat")},2000);try{let H=$?_T(f):f.message,W=await this.routeToTeammate(f.agentId,H,{taskId:f.taskId,continueConversation:f.continueConversation});f.status="completed",f.result=W,f.endedAt=new Date,f.currentActivity="completed",this.emitEvent({type:w.RunCompleted,run:{...f}})}catch(H){let W=H instanceof Error?H.message:String(H??"Unknown error");f.error=W,f.endedAt=new Date;let Q=this.members.get(f.agentId);if(qP(Q,H))f.status="cancelled",f.currentActivity="cancelled",this.emitEvent({type:w.RunCancelled,run:{...f},reason:W});else if(f.retryCount<f.maxRetries)f.retryCount++,f.status="queued",f.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**f.retryCount)),this.runQueue.push(f.id),this.recordRunProgress(f,`retry_scheduled_${f.retryCount}`);else f.status="failed",f.currentActivity="failed",this.emitEvent({type:w.RunFailed,run:{...f}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns(f){let $=f?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!$&&!["running","queued"].includes(J.status))return!1;if(f?.status&&J.status!==f.status)return!1;if(f?.agentId&&J.agentId!==f.agentId)return!1;return!0}).map((J)=>({...J}))}getRun(f){let $=this.runs.get(f);return $?{...$}:void 0}async awaitRun(f,$=250){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);while(J.status==="queued"||J.status==="running")await wP($);return{...J}}async awaitAllRuns(f=250){while(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))await wP(f);return this.listRuns()}cancelRun(f,$){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=$,J.endedAt=new Date,J.currentActivity="cancelled";let H=this.runQueue.indexOf(f);if(H>=0)this.runQueue.splice(H,1);return this.emitEvent({type:w.RunCancelled,run:{...J},reason:$}),{...J}}recoverActiveRuns(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let H=this.members.get(J.agentId);if(!H||H.role!=="teammate"||!H.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:w.RunInterrupted,run:{...J},reason:J.error});continue}let W=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=W,J.lastProgressAt=W,J.lastProgressMessage=f,J.currentActivity=bP,!this.runQueue.includes(J.id))this.runQueue.push(J.id);$.push({...J}),this.emitEvent({type:w.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),$}markStaleRunsInterrupted(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=f,J.endedAt=new Date,J.currentActivity="interrupted",$.push({...J}),this.emitEvent({type:w.RunInterrupted,run:{...J},reason:f})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),$}sendMessage(f,$,J,H,W){if(!this.members.has(f))throw Error(`Unknown sender "${f}"`);let Q=this.members.get($);if(!Q)throw Error(`Unknown recipient "${$}"`);let Z={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:f,toAgentId:$,subject:J,body:H,taskId:W,sentAt:new Date};if(this.mailbox.push(Z),this.emitEvent({type:w.TeamMessage,message:{...Z}}),Q.role==="teammate"&&Q.runningCount>0&&Q.agent)Q.pendingSteerMessage=`[MAILBOX] You got a message from ${f}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...Z}}broadcast(f,$,J,H){let W=[];for(let Q of this.members.values()){if(Q.agentId===f)continue;if(Q.role==="lead")continue;W.push(this.sendMessage(f,Q.agentId,$,J,H?.taskId))}return W}appendMissionLog(f){if(!this.members.has(f.agentId))throw Error(`Unknown team member "${f.agentId}"`);let $={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:f.agentId,taskId:f.taskId,kind:f.kind,summary:f.summary,evidence:f.evidence,nextAction:f.nextAction};this.missionLog.push($);let J=this.members.get(f.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:w.TeamMissionLog,entry:{...$}}),{...$}}createOutcome(f){let $={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:f.title,status:"draft",requiredSections:[...new Set(f.requiredSections)],createdBy:f.createdBy,createdAt:new Date};return this.outcomes.set($.id,$),this.emitEvent({type:w.OutcomeCreated,outcome:{...$}}),{...$}}listOutcomes(){return Array.from(this.outcomes.values()).map((f)=>({...f}))}attachOutcomeFragment(f){let $=this.outcomes.get(f.outcomeId);if(!$)throw Error(`Outcome "${f.outcomeId}" was not found`);if(!$.requiredSections.includes(f.section))throw Error(`Section "${f.section}" is not part of outcome "${f.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:f.outcomeId,section:f.section,sourceAgentId:f.sourceAgentId,sourceRunId:f.sourceRunId,content:f.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),$.status==="draft")$.status="in_review";return this.emitEvent({type:w.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment(f){let $=this.outcomeFragments.get(f.fragmentId);if(!$)throw Error(`Fragment "${f.fragmentId}" was not found`);return $.status=f.approved?"reviewed":"rejected",$.reviewedBy=f.reviewedBy,$.reviewedAt=new Date,this.emitEvent({type:w.OutcomeFragmentReviewed,fragment:{...$}}),{...$}}listOutcomeFragments(f){return Array.from(this.outcomeFragments.values()).filter(($)=>$.outcomeId===f).map(($)=>({...$}))}finalizeOutcome(f){let $=this.outcomes.get(f);if(!$)throw Error(`Outcome "${f}" was not found`);let J=this.listOutcomeFragments(f);for(let H of $.requiredSections)if(!J.some((Q)=>Q.section===H&&Q.status==="reviewed"))throw Error(`Outcome "${f}" cannot be finalized. Section "${H}" is missing a reviewed fragment.`);return $.status="finalized",$.finalizedAt=new Date,this.emitEvent({type:w.OutcomeFinalized,outcome:{...$}}),{...$}}cleanup(){for(let f of this.members.values())if(f.role==="teammate"&&f.runningCount>0)throw Error(`Cannot cleanup team while teammate "${f.agentId}" is still running`);if(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let f of this.members.values())if(f.role==="teammate")try{f.agent?.abort()}catch($){if(!u5($))throw $}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[f,$]of this.members.entries())if($.role==="teammate")this.members.delete(f)}requireTask(f){let $=this.tasks.get(f);if(!$)throw Error(`Task "${f}" was not found`);return $}assertDependenciesResolved(f){let $=this.getUnresolvedDependencies(f);if($.length>0)throw Error(`Task "${f.id}" is blocked by "${$[0]}"`)}getUnresolvedDependencies(f){return f.dependsOn.filter(($)=>{let J=this.tasks.get($);return!J||J.status!=="completed"})}trackMeaningfulEvent(f,$){if(this.recordRunActivityFromAgentEvent(f,$),$.type==="iteration_end"&&$.hadToolCalls){this.recordProgressStep(f,`Completed iteration ${$.iteration} with ${$.toolCallCount} tool call(s)`);return}if($.type==="content_end"&&$.contentType==="tool"&&!$.error){this.recordProgressStep(f,`Finished tool "${$.toolName??"unknown"}"`);return}if($.type==="done"){this.appendMissionLog({agentId:f,kind:"done",summary:`Completed a delegated run (${$.iterations} iterations)`});return}if($.type==="error")this.appendMissionLog({agentId:f,kind:"error",summary:$.error.message})}recordRunActivityFromAgentEvent(f,$){let J;switch($.type){case"iteration_start":J=`iteration_${$.iteration}_started`;break;case"content_start":if($.contentType==="tool")J=`running_tool_${$.toolName??"unknown"}`;break;case"content_end":if($.contentType==="tool")J=$.error?this.formatProgressErrorActivity(`tool_${$.toolName??"unknown"}_error`,$.error):`finished_tool_${$.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",$.error.message);break;default:break}if(!J)return;for(let H of this.runs.values()){if(H.agentId!==f||H.status!=="running")continue;this.recordRunProgress(H,J)}}recordRunProgress(f,$){let J=new Date;f.heartbeatAt=J,f.lastProgressAt=J,f.lastProgressMessage=$,f.currentActivity=$,this.emitEvent({type:w.RunProgress,run:{...f},message:$})}formatProgressErrorActivity(f,$){let J=$.replace(/\s+/g," ").trim();if(J.length===0)return f;let H=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${f}: ${H}`}recordProgressStep(f,$,J,H=!1){this.missionStepCounter++;let W=this.members.get(f);if(!W)return;let Q=this.missionStepCounter-W.lastMissionStep,Z=Date.now()-W.lastMissionAt;if(!H&&Q<this.missionLogIntervalSteps&&Z<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:f,taskId:J,kind:"progress",summary:$})}buildMailboxNotification(f){if(f.length===0)return"";let $=[`[MAILBOX] You have ${f.length} unread message(s):`];for(let J of f)$.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),$.push(J.body);return $.push("---"),$.join(`
498
- `)}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}function wP(f){return new Promise(($)=>setTimeout($,f))}function s1(f,$){let J=0;for(let H of f){if(!H.startsWith($))continue;let W=Number.parseInt(H.slice($.length),10);if(Number.isFinite(W))J=Math.max(J,W)}return J}function d5(f,$){switch($.type){case"run_queued":case"run_started":f.activeTeamRunIds.add($.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if($.type==="run_failed")J=$.run.error;else if($.type==="run_cancelled"||$.type==="run_interrupted")J=$.run.error??$.reason;f.activeTeamRunIds.delete($.run.id),f.pendingTeamRunUpdates.push({runId:$.run.id,agentId:$.run.agentId,taskId:$.run.taskId,status:$.type.replace("run_",""),error:J,iterations:$.run.result?.iterations}),wJ(f);break}default:break}}async function r5(f,$,J){switch($.type){case"run_progress":await J("onTeamTaskProgress",f,$.run.agentId,$.message,{kind:$.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if($.event.type==="content_start"&&$.event.contentType==="text"&&typeof $.event.text==="string"){let H=$.event.text.replace(/\s+/g," ").trim().slice(0,120);if(H)await J("onTeamTaskProgress",f,$.agentId,H,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",f,$.agentId,$.message);break;case"task_end":{if($.error)await J("onTeamTaskEnd",f,$.agentId,"failed",`[error] ${$.error.message}`,void 0,$.messages);else if($.result?.finishReason==="aborted")await J("onTeamTaskEnd",f,$.agentId,"cancelled","[done] aborted",$.result,$.result.messages);else await J("onTeamTaskEnd",f,$.agentId,"completed",`[done] ${$.result?.finishReason??"completed"}`,$.result,$.result?.messages);break}default:break}}function l5(f,$,J,H){if(!f.runtime.teamRuntime)return;let W=f.runtime.teamRuntime.getTeamName();H({type:"team_progress",payload:{sessionId:$,teamName:W,lifecycle:t1({teamName:W,sessionId:$,event:J}),summary:a1(W,f.runtime.teamRuntime.exportState())}})}function Z4(f){return f.activeTeamRunIds.size>0||f.pendingTeamRunUpdates.length>0}function p5(f,$){if(f.aborting)return!1;if(!($==="completed"||$==="max_iterations"))return!1;return f.config.enableAgentTeams===!0&&Z4(f)}function wJ(f){let $=f.teamRunWaiters.splice(0);for(let J of $)J()}async function i5(f){while(!0){if(f.aborting)return[];if(f.pendingTeamRunUpdates.length>0){let $=[...f.pendingTeamRunUpdates];return f.pendingTeamRunUpdates.length=0,$}if(f.activeTeamRunIds.size===0)return[];await new Promise(($)=>{f.teamRunWaiters.push($)})}}function n5(f,$){let J=$.map((Q)=>{let Z=[`- ${Q.runId} (${Q.agentId}) -> ${Q.status}`];if(Q.taskId)Z.push(` task=${Q.taskId}`);if(typeof Q.iterations==="number")Z.push(` iterations=${Q.iterations}`);if(Q.error)Z.push(` error=${Q.error}`);return Z.join("")}),H=f.activeTeamRunIds.size,W=H>0?`There are still ${H} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return j4(`System-delivered teammate async run updates:
497
+ ${$}`:$,Z=J?.continueConversation?await W.agent.continue(Q):await W.agent.run(Q);return this.emitEvent({type:C.TaskEnd,agentId:f,result:Z}),this.recordProgressStep(f,`Completed a delegated run (${Z.iterations} iterations)`,J?.taskId,!0),Z}catch(H){let Q=H instanceof Error?H:Error(String(H));if(this.emitEvent({type:C.TaskEnd,agentId:f,error:Q,messages:W.agent.getMessages()}),!sX(W,Q))this.appendMissionLog({agentId:f,taskId:J?.taskId,kind:"error",summary:Q.message});throw Q}finally{if(W.runningCount--,W.runningCount<=0&&this.members.get(f)?.status!=="stopped")W.status="idle"}}startTeammateRun(f,$,J){let W=`run_${String(++this.runCounter).padStart(5,"0")}`,H={id:W,agentId:f,taskId:J?.taskId,status:"queued",message:$,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(W,H),this.runQueue.push(W),this.emitEvent({type:C.RunQueued,run:{...H}}),this.dispatchQueuedRuns(),{...H}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let f;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let $=this.selectNextDispatchableQueuedRun();f=$.nextDelayedAttemptAt;let J=$.index;if(J<0){this.scheduleQueuedRunDispatch(f);return}let[W]=this.runQueue.splice(J,1),H=W?this.runs.get(W):void 0;if(!H||H.status!=="queued")continue;this.executeQueuedRun(H)}this.scheduleQueuedRunDispatch(f)}selectNextDispatchableQueuedRun(){let f=-1,$=Number.NEGATIVE_INFINITY,J,W=Date.now();for(let H=0;H<this.runQueue.length;H++){let Q=this.runs.get(this.runQueue[H]);if(!Q||Q.status!=="queued")continue;if(Q.nextAttemptAt&&Q.nextAttemptAt.getTime()>W){if(!J||Q.nextAttemptAt<J)J=Q.nextAttemptAt;continue}if(Q.priority>$)$=Q.priority,f=H}return{index:f,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch(f){if(!f)return;let $=Math.max(0,f.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},$)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let f=0;for(let $ of this.runs.values())if($.status==="running")f++;return f}async executeQueuedRun(f){let $=f.currentActivity===oX;f.nextAttemptAt=void 0,f.status="running",f.startedAt=new Date,f.heartbeatAt=new Date,f.currentActivity="run_started",this.emitEvent({type:C.RunStarted,run:{...f}});let J=setInterval(()=>{if(f.status!=="running")return;this.recordRunProgress(f,"heartbeat")},2000);try{let W=$?J_(f):f.message,H=await this.routeToTeammate(f.agentId,W,{taskId:f.taskId,continueConversation:f.continueConversation});f.status="completed",f.result=H,f.endedAt=new Date,f.currentActivity="completed",this.emitEvent({type:C.RunCompleted,run:{...f}})}catch(W){let H=W instanceof Error?W.message:String(W??"Unknown error");f.error=H,f.endedAt=new Date;let Q=this.members.get(f.agentId);if(sX(Q,W))f.status="cancelled",f.currentActivity="cancelled",this.emitEvent({type:C.RunCancelled,run:{...f},reason:H});else if(f.retryCount<f.maxRetries)f.retryCount++,f.status="queued",f.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**f.retryCount)),this.runQueue.push(f.id),this.recordRunProgress(f,`retry_scheduled_${f.retryCount}`);else f.status="failed",f.currentActivity="failed",this.emitEvent({type:C.RunFailed,run:{...f}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns(f){let $=f?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!$&&!["running","queued"].includes(J.status))return!1;if(f?.status&&J.status!==f.status)return!1;if(f?.agentId&&J.agentId!==f.agentId)return!1;return!0}).map((J)=>({...J}))}getRun(f){let $=this.runs.get(f);return $?{...$}:void 0}async awaitRun(f,$=250){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);while(J.status==="queued"||J.status==="running")await eX($);return{...J}}async awaitAllRuns(f=250){while(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))await eX(f);return this.listRuns()}cancelRun(f,$){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=$,J.endedAt=new Date,J.currentActivity="cancelled";let W=this.runQueue.indexOf(f);if(W>=0)this.runQueue.splice(W,1);return this.emitEvent({type:C.RunCancelled,run:{...J},reason:$}),{...J}}recoverActiveRuns(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let W=this.members.get(J.agentId);if(!W||W.role!=="teammate"||!W.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:C.RunInterrupted,run:{...J},reason:J.error});continue}let H=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=H,J.lastProgressAt=H,J.lastProgressMessage=f,J.currentActivity=oX,!this.runQueue.includes(J.id))this.runQueue.push(J.id);$.push({...J}),this.emitEvent({type:C.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),$}markStaleRunsInterrupted(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=f,J.endedAt=new Date,J.currentActivity="interrupted",$.push({...J}),this.emitEvent({type:C.RunInterrupted,run:{...J},reason:f})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),$}sendMessage(f,$,J,W,H){if(!this.members.has(f))throw Error(`Unknown sender "${f}"`);let Q=this.members.get($);if(!Q)throw Error(`Unknown recipient "${$}"`);let Z={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:f,toAgentId:$,subject:J,body:W,taskId:H,sentAt:new Date};if(this.mailbox.push(Z),this.emitEvent({type:C.TeamMessage,message:{...Z}}),Q.role==="teammate"&&Q.runningCount>0&&Q.agent)Q.pendingSteerMessage=`[MAILBOX] You got a message from ${f}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...Z}}broadcast(f,$,J,W){let H=[];for(let Q of this.members.values()){if(Q.agentId===f)continue;if(Q.role==="lead")continue;H.push(this.sendMessage(f,Q.agentId,$,J,W?.taskId))}return H}appendMissionLog(f){if(!this.members.has(f.agentId))throw Error(`Unknown team member "${f.agentId}"`);let $={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:f.agentId,taskId:f.taskId,kind:f.kind,summary:f.summary,evidence:f.evidence,nextAction:f.nextAction};this.missionLog.push($);let J=this.members.get(f.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:C.TeamMissionLog,entry:{...$}}),{...$}}createOutcome(f){let $={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:f.title,status:"draft",requiredSections:[...new Set(f.requiredSections)],createdBy:f.createdBy,createdAt:new Date};return this.outcomes.set($.id,$),this.emitEvent({type:C.OutcomeCreated,outcome:{...$}}),{...$}}listOutcomes(){return Array.from(this.outcomes.values()).map((f)=>({...f}))}attachOutcomeFragment(f){let $=this.outcomes.get(f.outcomeId);if(!$)throw Error(`Outcome "${f.outcomeId}" was not found`);if(!$.requiredSections.includes(f.section))throw Error(`Section "${f.section}" is not part of outcome "${f.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:f.outcomeId,section:f.section,sourceAgentId:f.sourceAgentId,sourceRunId:f.sourceRunId,content:f.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),$.status==="draft")$.status="in_review";return this.emitEvent({type:C.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment(f){let $=this.outcomeFragments.get(f.fragmentId);if(!$)throw Error(`Fragment "${f.fragmentId}" was not found`);return $.status=f.approved?"reviewed":"rejected",$.reviewedBy=f.reviewedBy,$.reviewedAt=new Date,this.emitEvent({type:C.OutcomeFragmentReviewed,fragment:{...$}}),{...$}}listOutcomeFragments(f){return Array.from(this.outcomeFragments.values()).filter(($)=>$.outcomeId===f).map(($)=>({...$}))}finalizeOutcome(f){let $=this.outcomes.get(f);if(!$)throw Error(`Outcome "${f}" was not found`);let J=this.listOutcomeFragments(f);for(let W of $.requiredSections)if(!J.some((Q)=>Q.section===W&&Q.status==="reviewed"))throw Error(`Outcome "${f}" cannot be finalized. Section "${W}" is missing a reviewed fragment.`);return $.status="finalized",$.finalizedAt=new Date,this.emitEvent({type:C.OutcomeFinalized,outcome:{...$}}),{...$}}cleanup(){for(let f of this.members.values())if(f.role==="teammate"&&f.runningCount>0)throw Error(`Cannot cleanup team while teammate "${f.agentId}" is still running`);if(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let f of this.members.values())if(f.role==="teammate")try{f.agent?.abort()}catch($){if(!iH($))throw $}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[f,$]of this.members.entries())if($.role==="teammate")this.members.delete(f)}requireTask(f){let $=this.tasks.get(f);if(!$)throw Error(`Task "${f}" was not found`);return $}assertDependenciesResolved(f){let $=this.getUnresolvedDependencies(f);if($.length>0)throw Error(`Task "${f.id}" is blocked by "${$[0]}"`)}getUnresolvedDependencies(f){return f.dependsOn.filter(($)=>{let J=this.tasks.get($);return!J||J.status!=="completed"})}trackMeaningfulEvent(f,$){if(this.recordRunActivityFromAgentEvent(f,$),$.type==="iteration_end"&&$.hadToolCalls){this.recordProgressStep(f,`Completed iteration ${$.iteration} with ${$.toolCallCount} tool call(s)`);return}if($.type==="content_end"&&$.contentType==="tool"&&!$.error){this.recordProgressStep(f,`Finished tool "${$.toolName??"unknown"}"`);return}if($.type==="done"){this.appendMissionLog({agentId:f,kind:"done",summary:`Completed a delegated run (${$.iterations} iterations)`});return}if($.type==="error")this.appendMissionLog({agentId:f,kind:"error",summary:$.error.message})}recordRunActivityFromAgentEvent(f,$){let J;switch($.type){case"iteration_start":J=`iteration_${$.iteration}_started`;break;case"content_start":if($.contentType==="tool")J=`running_tool_${$.toolName??"unknown"}`;break;case"content_end":if($.contentType==="tool")J=$.error?this.formatProgressErrorActivity(`tool_${$.toolName??"unknown"}_error`,$.error):`finished_tool_${$.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",$.error.message);break;default:break}if(!J)return;for(let W of this.runs.values()){if(W.agentId!==f||W.status!=="running")continue;this.recordRunProgress(W,J)}}recordRunProgress(f,$){let J=new Date;f.heartbeatAt=J,f.lastProgressAt=J,f.lastProgressMessage=$,f.currentActivity=$,this.emitEvent({type:C.RunProgress,run:{...f},message:$})}formatProgressErrorActivity(f,$){let J=$.replace(/\s+/g," ").trim();if(J.length===0)return f;let W=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${f}: ${W}`}recordProgressStep(f,$,J,W=!1){this.missionStepCounter++;let H=this.members.get(f);if(!H)return;let Q=this.missionStepCounter-H.lastMissionStep,Z=Date.now()-H.lastMissionAt;if(!W&&Q<this.missionLogIntervalSteps&&Z<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:f,taskId:J,kind:"progress",summary:$})}buildMailboxNotification(f){if(f.length===0)return"";let $=[`[MAILBOX] You have ${f.length} unread message(s):`];for(let J of f)$.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),$.push(J.body);return $.push("---"),$.join(`
498
+ `)}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}function eX(f){return new Promise(($)=>setTimeout($,f))}function f2(f,$){let J=0;for(let W of f){if(!W.startsWith($))continue;let H=Number.parseInt(W.slice($.length),10);if(Number.isFinite(H))J=Math.max(J,H)}return J}function aH(f,$){switch($.type){case"run_queued":case"run_started":f.activeTeamRunIds.add($.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if($.type==="run_failed")J=$.run.error;else if($.type==="run_cancelled"||$.type==="run_interrupted")J=$.run.error??$.reason;f.activeTeamRunIds.delete($.run.id),f.pendingTeamRunUpdates.push({runId:$.run.id,agentId:$.run.agentId,taskId:$.run.taskId,status:$.type.replace("run_",""),error:J,iterations:$.run.result?.iterations}),qJ(f);break}default:break}}async function tH(f,$,J){switch($.type){case"run_progress":await J("onTeamTaskProgress",f,$.run.agentId,$.message,{kind:$.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if($.event.type==="content_start"&&$.event.contentType==="text"&&typeof $.event.text==="string"){let W=$.event.text.replace(/\s+/g," ").trim().slice(0,120);if(W)await J("onTeamTaskProgress",f,$.agentId,W,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",f,$.agentId,$.message);break;case"task_end":{if($.error)await J("onTeamTaskEnd",f,$.agentId,"failed",`[error] ${$.error.message}`,void 0,$.messages);else if($.result?.finishReason==="aborted")await J("onTeamTaskEnd",f,$.agentId,"cancelled","[done] aborted",$.result,$.result.messages);else await J("onTeamTaskEnd",f,$.agentId,"completed",`[done] ${$.result?.finishReason??"completed"}`,$.result,$.result?.messages);break}default:break}}function sH(f,$,J,W){if(!f.runtime.teamRuntime)return;let H=f.runtime.teamRuntime.getTeamName();W({type:"team_progress",payload:{sessionId:$,teamName:H,lifecycle:e1({teamName:H,sessionId:$,event:J}),summary:o1(H,f.runtime.teamRuntime.exportState())}})}function B4(f){return f.activeTeamRunIds.size>0||f.pendingTeamRunUpdates.length>0}function oH(f,$){if(f.aborting)return!1;if(!($==="completed"||$==="max_iterations"))return!1;return f.config.enableAgentTeams===!0&&B4(f)}function qJ(f){let $=f.teamRunWaiters.splice(0);for(let J of $)J()}async function eH(f){while(!0){if(f.aborting)return[];if(f.pendingTeamRunUpdates.length>0){let $=[...f.pendingTeamRunUpdates];return f.pendingTeamRunUpdates.length=0,$}if(f.activeTeamRunIds.size===0)return[];await new Promise(($)=>{f.teamRunWaiters.push($)})}}function f9(f,$){let J=$.map((Q)=>{let Z=[`- ${Q.runId} (${Q.agentId}) -> ${Q.status}`];if(Q.taskId)Z.push(` task=${Q.taskId}`);if(typeof Q.iterations==="number")Z.push(` iterations=${Q.iterations}`);if(Q.error)Z.push(` error=${Q.error}`);return Z.join("")}),W=f.activeTeamRunIds.size,H=W>0?`There are still ${W} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return Y4(`System-delivered teammate async run updates:
499
499
  ${J.join(`
500
500
  `)}
501
501
 
502
- ${W}`,f.config.mode)}function j4(f,$){return LT(f,$==="plan"?"plan":$==="yolo"?"yolo":"act")}var a5=4;class z0{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor(f,$={}){this.adapter=f;this.manifestStore=new g5(f,$.messagesArtifactUploader),this.teamChildren=new bJ(f,this.manifestStore,(J,H,W)=>this.toPersistedMessages(J,H,W),z0.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages(f,$,J){if(!f)return;return $?D6($.messages,$,J):T6(f)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest(f,$){this.manifestStore.writeSessionManifest(f,$)}readSessionManifest(f){return this.manifestStore.readSessionManifest(f)}async createRootSessionWithArtifacts(f){let $=f.startedAt??s(),J=f.sessionId.trim(),H=J.length>0?J:`${Date.now()}_${OT(5)}`,W=this.manifestStore.artifacts.sessionMessagesPath(H),Q=this.manifestStore.artifacts.sessionManifestPath(H),Z=B8({metadata:f.metadata,prompt:f.prompt}),j={version:1,session_id:H,source:f.source,pid:f.pid,started_at:$,status:"running",interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt?.trim()||void 0,metadata:Z,messages_path:W};return await this.adapter.upsertSession({sessionId:H,source:f.source,pid:f.pid,startedAt:$,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:j.prompt??null,metadata:l0(j.metadata),hookPath:"",messagesPath:W,updatedAt:s()}),this.manifestStore.initializeMessagesFile(H,W,$),this.manifestStore.writeSessionManifest(Q,j),{manifestPath:Q,messagesPath:W,manifest:j}}async updateSessionStatus(f,$,J){let H;if((await QZ(()=>this.adapter.getSession(f),async(Q)=>{return H=$==="running"?void 0:s(),this.adapter.updateSession({sessionId:f,status:$,endedAt:H??null,exitCode:$==="running"?null:typeof J==="number"?J:null,expectedStatusLock:Q.statusLock})},a5)).updated){if($==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions(f,"cancelled");return{updated:!0,endedAt:H}}return{updated:!1}}async updateSession(f){for(let $=0;$<a5;$++){let J=await this.adapter.getSession(f.sessionId);if(!J)return{updated:!1};let H=J.metadata??void 0,W=f.metadata!==void 0?l0(f.metadata)??{}:l0(H)??{},Q=b$(typeof H?.title==="string"?H.title:void 0),Z=f.title!==void 0?b$(f.title):Q??DW(f.prompt);if(Z)W.title=Z;else delete W.title;let j=f.metadata!==void 0||f.prompt!==void 0||f.title!==void 0;if(!(await this.adapter.updateSession({sessionId:f.sessionId,prompt:f.prompt,metadata:j?Object.keys(W).length>0?W:null:void 0,title:Z,expectedStatusLock:J.statusLock})).updated)continue;let{path:X,manifest:V}=this.manifestStore.readManifestFile(f.sessionId);if(V){if(f.prompt!==void 0)V.prompt=f.prompt??void 0;let Y=f.metadata!==void 0?l0(f.metadata)??{}:l0(V.metadata)??{};if(Z)Y.title=Z;V.metadata=Object.keys(Y).length>0?Y:void 0,this.manifestStore.writeSessionManifest(X,V)}return{updated:!0}}return{updated:!1}}queueSpawnRequest(f){return this.teamChildren.queueSpawnRequest(f)}upsertSubagentSession(f){return this.teamChildren.upsertSubagentSession(f)}upsertSubagentSessionFromHook(f){return this.teamChildren.upsertSubagentSessionFromHook(f)}appendSubagentHookAudit(f,$){return this.teamChildren.appendSubagentHookAudit($),Promise.resolve()}persistSessionMessages(f,$,J){let H=T6($);return this.manifestStore.persistSessionMessages(f,H,J)}applySubagentStatus(f,$){return this.teamChildren.applySubagentStatus(f,$)}applySubagentStatusBySessionId(f,$){return this.teamChildren.applySubagentStatusBySessionId(f,$)}applyStatusToRunningChildSessions(f,$){return this.teamChildren.applyStatusToRunningChildSessions(f,$)}onTeamTaskStart(f,$,J){return this.teamChildren.onTeamTaskStart(f,$,J)}onTeamTaskEnd(f,$,J,H,W,Q){return this.teamChildren.onTeamTaskEnd(f,$,J,H,W,Q)}onTeamTaskProgress(f,$,J,H){return this.teamChildren.onTeamTaskProgress(f,$,J,H)}handleSubAgentStart(f,$){return this.teamChildren.handleSubAgentStart(f,$)}handleSubAgentEnd(f,$){return this.teamChildren.handleSubAgentEnd(f,$)}isPidAlive(f){if(!Number.isFinite(f)||f<=0)return!1;try{return process.kill(Math.floor(f),0),!0}catch($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="EPERM"}}async reconcileDeadRunningSession(f){if(f.status!=="running"||this.isPidAlive(f.pid))return f;let $=s(),J=z0.STALE_REASON;for(let H=0;H<a5;H++){let W=await this.adapter.getSession(f.sessionId);if(!W)return;if(W.status!=="running")return W;let Q={...W.metadata??{},terminal_marker:J,terminal_marker_at:$,terminal_marker_pid:W.pid,terminal_marker_source:z0.STALE_SOURCE},Z=await this.adapter.updateSession({sessionId:W.sessionId,status:"failed",endedAt:$,exitCode:1,metadata:Q,expectedStatusLock:W.statusLock});if(!Z.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(W.sessionId,"failed");let j=WZ(W,{status:"failed",endedAt:$,exitCode:1,metadata:Q}),{path:P}=this.manifestStore.readManifestFile(W.sessionId);return this.manifestStore.writeSessionManifest(P,j),this.manifestStore.appendStaleSessionHookLog($,W.sessionId,W.pid,J,z0.STALE_SOURCE),{...W,status:"failed",endedAt:$,exitCode:1,metadata:Q,statusLock:Z.statusLock,updatedAt:$}}return await this.adapter.getSession(f.sessionId)}async listSessions(f=200){let $=Math.max(1,Math.floor(f)),J=Math.min($*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,$).map((W)=>{let Q=l0(W.metadata??void 0),Z=this.manifestStore.readSessionManifest(W.sessionId),j=b$(typeof Z?.metadata?.title==="string"?Z.metadata.title:void 0),P=j?{...Q??{},title:j}:Q;return{...W,metadata:P}})}async reconcileDeadSessions(f=2000){let $=await this.adapter.listSessions({limit:Math.max(1,Math.floor(f)),status:"running"}),J=0;for(let H of $){let W=await this.reconcileDeadRunningSession(H);if(W&&W.status!==H.status)J++}return J}async deleteSession(f){let $=f.trim();if(!$)throw Error("session id is required");let J=await this.adapter.getSession($);if(!J)return{deleted:!1};if(await this.adapter.deleteSession($,!1),!J.isSubagent){let H=await this.adapter.listSessions({limit:2000,parentSessionId:$});await this.adapter.deleteSession($,!0),await Promise.allSettled(H.map(async(W)=>{await IW(W.cwd,W.sessionId),b8(W.messagesPath),b8(this.manifestStore.artifacts.sessionManifestPath(W.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(W.sessionId)}))}if(await IW(J.cwd,$),b8(J.messagesPath),b8(this.manifestStore.artifacts.sessionManifestPath($,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty($);else{let H=new Set([this.manifestStore.artifacts.sessionArtifactsDir($)]);for(let W of[J.messagesPath])if(typeof W==="string"&&W.trim().length>0)H.add(zT(W));for(let W of H)this.manifestStore.artifacts.removeDir(W)}return{deleted:!0}}}function s5(){return new Date().toISOString()}function mP(f,$){let J=`${f}.tmp`;bT(J,`${JSON.stringify($,null,2)}
503
- `,"utf8"),qT(J,f)}class IP{sessionsDirPath;constructor(f=wT()){this.sessionsDirPath=f}ensureSessionsDir(){if(!t5(this.sessionsDirPath))NT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return kP(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return kP(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let f=this.indexPath();if(!t5(f))return{version:1,sessions:{}};try{let $=JSON.parse(SP(f,"utf8"));if($?.version===1&&$.sessions)return $}catch{}return{version:1,sessions:{}}}writeIndex(f){mP(this.indexPath(),f)}readQueue(){let f=this.spawnQueuePath();if(!t5(f))return{version:1,nextId:1,requests:[]};try{let $=JSON.parse(SP(f,"utf8"));if($?.version===1&&typeof $.nextId==="number"&&Array.isArray($.requests))return $}catch{}return{version:1,nextId:1,requests:[]}}writeQueue(f){mP(this.spawnQueuePath(),f)}async upsertSession(f){let $=this.readIndex();$.sessions[f.sessionId]=f,this.writeIndex($)}async getSession(f){return this.readIndex().sessions[f]}async listSessions(f){return Object.values(this.readIndex().sessions).filter(($)=>f.parentSessionId!==void 0?$.parentSessionId===f.parentSessionId:!0).filter(($)=>f.status!==void 0?$.status===f.status:!0).sort(($,J)=>J.startedAt.localeCompare($.startedAt)).slice(0,f.limit)}async updateSession(f){let $=this.readIndex(),J=$.sessions[f.sessionId];if(!J)return{updated:!1,statusLock:0};if(f.expectedStatusLock!==void 0&&J.statusLock!==f.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let H=f.expectedStatusLock!==void 0?f.expectedStatusLock+1:J.statusLock,W={...J,status:f.status??J.status,endedAt:f.endedAt!==void 0?f.endedAt:J.endedAt??null,exitCode:f.exitCode!==void 0?f.exitCode:J.exitCode??null,prompt:f.prompt!==void 0?f.prompt:J.prompt??null,metadata:f.metadata!==void 0?f.metadata??null:J.metadata??null,parentSessionId:f.parentSessionId!==void 0?f.parentSessionId??null:J.parentSessionId??null,parentAgentId:f.parentAgentId!==void 0?f.parentAgentId??null:J.parentAgentId??null,agentId:f.agentId!==void 0?f.agentId??null:J.agentId??null,conversationId:f.conversationId!==void 0?f.conversationId??null:J.conversationId??null,statusLock:H,isSubagent:f.setRunning||f.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:s5()};if(f.setRunning)W.status="running",W.endedAt=null,W.exitCode=null;return $.sessions[f.sessionId]=W,this.writeIndex($),{updated:!0,statusLock:W.statusLock}}async deleteSession(f,$){let J=this.readIndex();if(!J.sessions[f])return!1;if(delete J.sessions[f],$){for(let W of Object.values(J.sessions))if(W.parentSessionId===f)delete J.sessions[W.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest(f){let $=this.readQueue();$.requests.push({id:$.nextId,rootSessionId:f.rootSessionId,parentAgentId:f.parentAgentId,task:f.task,systemPrompt:f.systemPrompt,createdAt:s5()}),$.nextId+=1,this.writeQueue($)}async claimSpawnRequest(f,$){let J=this.readQueue(),H=J.requests.find((W)=>W.rootSessionId===f&&W.parentAgentId===$&&!W.consumedAt);if(!H)return;return H.consumedAt=s5(),this.writeQueue(J),H.task}}class o5 extends z0{constructor(f,$={}){super(new IP(f),$)}ensureSessionsDir(){return super.ensureSessionsDir()}}var vP={};N(vP,{CoreSessionService:()=>Z0});import{existsSync as CT,mkdirSync as ET}from"node:fs";import{resolveSessionDataDir as ST}from"@cline/shared/storage";var e5=`
502
+ ${H}`,f.config.mode)}function Y4(f,$){return W_(f,$==="plan"?"plan":$==="yolo"?"yolo":"act")}var $9=4;class b0{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor(f,$={}){this.adapter=f;this.manifestStore=new lH(f,$.messagesArtifactUploader),this.teamChildren=new NJ(f,this.manifestStore,(J,W,H)=>this.toPersistedMessages(J,W,H),b0.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages(f,$,J){if(!f)return;return $?z6($.messages,$,J):O6(f)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest(f,$){this.manifestStore.writeSessionManifest(f,$)}readSessionManifest(f){return this.manifestStore.readSessionManifest(f)}async createRootSessionWithArtifacts(f){let $=f.startedAt??s(),J=f.sessionId.trim(),W=J.length>0?J:`${Date.now()}_${Q_(5)}`,H=this.manifestStore.artifacts.sessionMessagesPath(W),Q=this.manifestStore.artifacts.sessionManifestPath(W),Z=R8({metadata:f.metadata,prompt:f.prompt}),j={version:1,session_id:W,source:f.source,pid:f.pid,started_at:$,status:"running",interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt?.trim()||void 0,metadata:Z,messages_path:H};return await this.adapter.upsertSession({sessionId:W,source:f.source,pid:f.pid,startedAt:$,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:j.prompt??null,metadata:s0(j.metadata),hookPath:"",messagesPath:H,updatedAt:s()}),this.manifestStore.initializeMessagesFile(W,H,$),this.manifestStore.writeSessionManifest(Q,j),{manifestPath:Q,messagesPath:H,manifest:j}}async updateSessionStatus(f,$,J){let W;if((await UZ(()=>this.adapter.getSession(f),async(Q)=>{return W=$==="running"?void 0:s(),this.adapter.updateSession({sessionId:f,status:$,endedAt:W??null,exitCode:$==="running"?null:typeof J==="number"?J:null,expectedStatusLock:Q.statusLock})},$9)).updated){if($==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions(f,"cancelled");return{updated:!0,endedAt:W}}return{updated:!1}}async updateSession(f){for(let $=0;$<$9;$++){let J=await this.adapter.getSession(f.sessionId);if(!J)return{updated:!1};let W=J.metadata??void 0,H=f.metadata!==void 0?s0(f.metadata)??{}:s0(W)??{},Q=E$(typeof W?.title==="string"?W.title:void 0),Z=f.title!==void 0?E$(f.title):Q??LW(f.prompt);if(Z)H.title=Z;else delete H.title;let j=f.metadata!==void 0||f.prompt!==void 0||f.title!==void 0;if(!(await this.adapter.updateSession({sessionId:f.sessionId,prompt:f.prompt,metadata:j?Object.keys(H).length>0?H:null:void 0,title:Z,expectedStatusLock:J.statusLock})).updated)continue;let{path:A,manifest:P}=this.manifestStore.readManifestFile(f.sessionId);if(P){if(f.prompt!==void 0)P.prompt=f.prompt??void 0;let B=f.metadata!==void 0?s0(f.metadata)??{}:s0(P.metadata)??{};if(Z)B.title=Z;P.metadata=Object.keys(B).length>0?B:void 0,this.manifestStore.writeSessionManifest(A,P)}return{updated:!0}}return{updated:!1}}queueSpawnRequest(f){return this.teamChildren.queueSpawnRequest(f)}upsertSubagentSession(f){return this.teamChildren.upsertSubagentSession(f)}upsertSubagentSessionFromHook(f){return this.teamChildren.upsertSubagentSessionFromHook(f)}appendSubagentHookAudit(f,$){return this.teamChildren.appendSubagentHookAudit($),Promise.resolve()}persistSessionMessages(f,$,J){let W=O6($);return this.manifestStore.persistSessionMessages(f,W,J)}applySubagentStatus(f,$){return this.teamChildren.applySubagentStatus(f,$)}applySubagentStatusBySessionId(f,$){return this.teamChildren.applySubagentStatusBySessionId(f,$)}applyStatusToRunningChildSessions(f,$){return this.teamChildren.applyStatusToRunningChildSessions(f,$)}onTeamTaskStart(f,$,J){return this.teamChildren.onTeamTaskStart(f,$,J)}onTeamTaskEnd(f,$,J,W,H,Q){return this.teamChildren.onTeamTaskEnd(f,$,J,W,H,Q)}onTeamTaskProgress(f,$,J,W){return this.teamChildren.onTeamTaskProgress(f,$,J,W)}handleSubAgentStart(f,$){return this.teamChildren.handleSubAgentStart(f,$)}handleSubAgentEnd(f,$){return this.teamChildren.handleSubAgentEnd(f,$)}isPidAlive(f){if(!Number.isFinite(f)||f<=0)return!1;try{return process.kill(Math.floor(f),0),!0}catch($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="EPERM"}}async reconcileDeadRunningSession(f){if(f.status!=="running"||this.isPidAlive(f.pid))return f;let $=s(),J=b0.STALE_REASON;for(let W=0;W<$9;W++){let H=await this.adapter.getSession(f.sessionId);if(!H)return;if(H.status!=="running")return H;let Q={...H.metadata??{},terminal_marker:J,terminal_marker_at:$,terminal_marker_pid:H.pid,terminal_marker_source:b0.STALE_SOURCE},Z=await this.adapter.updateSession({sessionId:H.sessionId,status:"failed",endedAt:$,exitCode:1,metadata:Q,expectedStatusLock:H.statusLock});if(!Z.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(H.sessionId,"failed");let j=yZ(H,{status:"failed",endedAt:$,exitCode:1,metadata:Q}),{path:X}=this.manifestStore.readManifestFile(H.sessionId);return this.manifestStore.writeSessionManifest(X,j),this.manifestStore.appendStaleSessionHookLog($,H.sessionId,H.pid,J,b0.STALE_SOURCE),{...H,status:"failed",endedAt:$,exitCode:1,metadata:Q,statusLock:Z.statusLock,updatedAt:$}}return await this.adapter.getSession(f.sessionId)}async listSessions(f=200){let $=Math.max(1,Math.floor(f)),J=Math.min($*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,$).map((H)=>{let Q=s0(H.metadata??void 0),Z=this.manifestStore.readSessionManifest(H.sessionId),j=E$(typeof Z?.metadata?.title==="string"?Z.metadata.title:void 0),X=j?{...Q??{},title:j}:Q;return{...H,metadata:X}})}async reconcileDeadSessions(f=2000){let $=await this.adapter.listSessions({limit:Math.max(1,Math.floor(f)),status:"running"}),J=0;for(let W of $){let H=await this.reconcileDeadRunningSession(W);if(H&&H.status!==W.status)J++}return J}async deleteSession(f){let $=f.trim();if(!$)throw Error("session id is required");let J=await this.adapter.getSession($);if(!J)return{deleted:!1};if(await this.adapter.deleteSession($,!1),!J.isSubagent){let W=await this.adapter.listSessions({limit:2000,parentSessionId:$});await this.adapter.deleteSession($,!0),await Promise.allSettled(W.map(async(H)=>{await uW(H.cwd,H.sessionId),k8(H.messagesPath),k8(this.manifestStore.artifacts.sessionManifestPath(H.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(H.sessionId)}))}if(await uW(J.cwd,$),k8(J.messagesPath),k8(this.manifestStore.artifacts.sessionManifestPath($,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty($);else{let W=new Set([this.manifestStore.artifacts.sessionArtifactsDir($)]);for(let H of[J.messagesPath])if(typeof H==="string"&&H.trim().length>0)W.add(H_(H));for(let H of W)this.manifestStore.artifacts.removeDir(H)}return{deleted:!0}}}function W9(){return new Date().toISOString()}function HA(f,$){let J=`${f}.tmp`;X_(J,`${JSON.stringify($,null,2)}
503
+ `,"utf8"),j_(J,f)}class QA{sessionsDirPath;constructor(f=A_()){this.sessionsDirPath=f}ensureSessionsDir(){if(!J9(this.sessionsDirPath))Z_(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return WA(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return WA(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let f=this.indexPath();if(!J9(f))return{version:1,sessions:{}};try{let $=JSON.parse(JA(f,"utf8"));if($?.version===1&&$.sessions)return $}catch{}return{version:1,sessions:{}}}writeIndex(f){HA(this.indexPath(),f)}readQueue(){let f=this.spawnQueuePath();if(!J9(f))return{version:1,nextId:1,requests:[]};try{let $=JSON.parse(JA(f,"utf8"));if($?.version===1&&typeof $.nextId==="number"&&Array.isArray($.requests))return $}catch{}return{version:1,nextId:1,requests:[]}}writeQueue(f){HA(this.spawnQueuePath(),f)}async upsertSession(f){let $=this.readIndex();$.sessions[f.sessionId]=f,this.writeIndex($)}async getSession(f){return this.readIndex().sessions[f]}async listSessions(f){return Object.values(this.readIndex().sessions).filter(($)=>f.parentSessionId!==void 0?$.parentSessionId===f.parentSessionId:!0).filter(($)=>f.status!==void 0?$.status===f.status:!0).sort(($,J)=>J.startedAt.localeCompare($.startedAt)).slice(0,f.limit)}async updateSession(f){let $=this.readIndex(),J=$.sessions[f.sessionId];if(!J)return{updated:!1,statusLock:0};if(f.expectedStatusLock!==void 0&&J.statusLock!==f.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let W=f.expectedStatusLock!==void 0?f.expectedStatusLock+1:J.statusLock,H={...J,status:f.status??J.status,endedAt:f.endedAt!==void 0?f.endedAt:J.endedAt??null,exitCode:f.exitCode!==void 0?f.exitCode:J.exitCode??null,prompt:f.prompt!==void 0?f.prompt:J.prompt??null,metadata:f.metadata!==void 0?f.metadata??null:J.metadata??null,parentSessionId:f.parentSessionId!==void 0?f.parentSessionId??null:J.parentSessionId??null,parentAgentId:f.parentAgentId!==void 0?f.parentAgentId??null:J.parentAgentId??null,agentId:f.agentId!==void 0?f.agentId??null:J.agentId??null,conversationId:f.conversationId!==void 0?f.conversationId??null:J.conversationId??null,statusLock:W,isSubagent:f.setRunning||f.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:W9()};if(f.setRunning)H.status="running",H.endedAt=null,H.exitCode=null;return $.sessions[f.sessionId]=H,this.writeIndex($),{updated:!0,statusLock:H.statusLock}}async deleteSession(f,$){let J=this.readIndex();if(!J.sessions[f])return!1;if(delete J.sessions[f],$){for(let H of Object.values(J.sessions))if(H.parentSessionId===f)delete J.sessions[H.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest(f){let $=this.readQueue();$.requests.push({id:$.nextId,rootSessionId:f.rootSessionId,parentAgentId:f.parentAgentId,task:f.task,systemPrompt:f.systemPrompt,createdAt:W9()}),$.nextId+=1,this.writeQueue($)}async claimSpawnRequest(f,$){let J=this.readQueue(),W=J.requests.find((H)=>H.rootSessionId===f&&H.parentAgentId===$&&!H.consumedAt);if(!W)return;return W.consumedAt=W9(),this.writeQueue(J),W.task}}class H9 extends b0{constructor(f,$={}){super(new QA(f),$)}ensureSessionsDir(){return super.ensureSessionsDir()}}var XA={};N(XA,{CoreSessionService:()=>j0});import{existsSync as P_,mkdirSync as B_}from"node:fs";import{resolveSessionDataDir as Y_}from"@cline/shared/storage";var Q9=`
504
504
  session_id AS sessionId,
505
505
  source,
506
506
  pid,
@@ -527,38 +527,38 @@ ${W}`,f.config.mode)}function j4(f,$){return LT(f,$==="plan"?"plan":$==="yolo"?"
527
527
  metadata_json AS metadata,
528
528
  hook_path AS hookPath,
529
529
  messages_path AS messagesPath,
530
- updated_at AS updatedAt`;function f9(f){f.interactive=f.interactive===1,f.enableTools=f.enableTools===1,f.enableSpawn=f.enableSpawn===1,f.enableTeams=f.enableTeams===1,f.isSubagent=f.isSubagent===1;let $=f.metadata;if(typeof $==="string"&&$.trim())try{let J=JSON.parse($);f.metadata=J&&typeof J==="object"&&!Array.isArray(J)?J:null}catch{f.metadata=null}else f.metadata=null;return f}function $9(f){if(!f||Object.keys(f).length===0)return null;return JSON.stringify(f)}function xP(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class gP{store;sessionsDirPath;constructor(f,$=ST()){this.store=f;this.sessionsDirPath=$}ensureSessionsDir(){if(!CT(this.sessionsDirPath))ET(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession(f){this.store.run(`INSERT OR REPLACE INTO sessions (
530
+ updated_at AS updatedAt`;function Z9(f){f.interactive=f.interactive===1,f.enableTools=f.enableTools===1,f.enableSpawn=f.enableSpawn===1,f.enableTeams=f.enableTeams===1,f.isSubagent=f.isSubagent===1;let $=f.metadata;if(typeof $==="string"&&$.trim())try{let J=JSON.parse($);f.metadata=J&&typeof J==="object"&&!Array.isArray(J)?J:null}catch{f.metadata=null}else f.metadata=null;return f}function j9(f){if(!f||Object.keys(f).length===0)return null;return JSON.stringify(f)}function ZA(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class jA{store;sessionsDirPath;constructor(f,$=Y_()){this.store=f;this.sessionsDirPath=$}ensureSessionsDir(){if(!P_(this.sessionsDirPath))B_(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession(f){this.store.run(`INSERT OR REPLACE INTO sessions (
531
531
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
532
532
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
533
533
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
534
534
  metadata_json, transcript_path, hook_path, messages_path, updated_at
535
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,f.statusLock,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.isSubagent?1:0,f.prompt??null,$9(f.metadata),"",f.hookPath??"",f.messagesPath??null,f.updatedAt])}async getSession(f){let $=this.store.queryOne(`SELECT ${e5} FROM sessions WHERE session_id = ?`,[f]);return $?f9($):void 0}async listSessions(f){let $=[],J=[];if(f.parentSessionId)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.status)$.push("status = ?"),J.push(f.status);let H=$.length>0?`WHERE ${$.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${e5}
535
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,f.statusLock,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.isSubagent?1:0,f.prompt??null,j9(f.metadata),"",f.hookPath??"",f.messagesPath??null,f.updatedAt])}async getSession(f){let $=this.store.queryOne(`SELECT ${Q9} FROM sessions WHERE session_id = ?`,[f]);return $?Z9($):void 0}async listSessions(f){let $=[],J=[];if(f.parentSessionId)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.status)$.push("status = ?"),J.push(f.status);let W=$.length>0?`WHERE ${$.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${Q9}
536
536
  FROM sessions
537
- ${H}
537
+ ${W}
538
538
  ORDER BY started_at DESC
539
- LIMIT ?`,[...J,f.limit]).map(f9)}async updateSession(f){if(f.setRunning){if(f.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
539
+ LIMIT ?`,[...J,f.limit]).map(Z9)}async updateSession(f){if(f.setRunning){if(f.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
540
540
  SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
541
541
  parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
542
542
  prompt = COALESCE(prompt, ?)
543
- WHERE session_id = ? AND status_lock = ?`,[s(),f.expectedStatusLock+1,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.prompt??null,f.sessionId,f.expectedStatusLock]).changes??0)>0,statusLock:f.expectedStatusLock+1}}let $=[],J=[];if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt??null);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push($9(f.metadata));if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId??null);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId??null);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId??null);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId??null);if($.length===0){let Z=await this.getSession(f.sessionId);return{updated:!!Z,statusLock:Z?.statusLock??0}}let H=0;if(f.expectedStatusLock!==void 0)H=f.expectedStatusLock+1,$.push("status_lock = ?"),J.push(H);$.push("updated_at = ?"),J.push(s());let W=`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`;if(J.push(f.sessionId),f.expectedStatusLock!==void 0)W+=" AND status_lock = ?",J.push(f.expectedStatusLock);if((this.store.run(W,J).changes??0)===0)return{updated:!1,statusLock:0};if(f.expectedStatusLock===void 0)H=(await this.getSession(f.sessionId))?.statusLock??0;return{updated:!0,statusLock:H}}async deleteSession(f,$){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}async enqueueSpawnRequest(f){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
543
+ WHERE session_id = ? AND status_lock = ?`,[s(),f.expectedStatusLock+1,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.prompt??null,f.sessionId,f.expectedStatusLock]).changes??0)>0,statusLock:f.expectedStatusLock+1}}let $=[],J=[];if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt??null);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(j9(f.metadata));if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId??null);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId??null);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId??null);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId??null);if($.length===0){let Z=await this.getSession(f.sessionId);return{updated:!!Z,statusLock:Z?.statusLock??0}}let W=0;if(f.expectedStatusLock!==void 0)W=f.expectedStatusLock+1,$.push("status_lock = ?"),J.push(W);$.push("updated_at = ?"),J.push(s());let H=`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`;if(J.push(f.sessionId),f.expectedStatusLock!==void 0)H+=" AND status_lock = ?",J.push(f.expectedStatusLock);if((this.store.run(H,J).changes??0)===0)return{updated:!1,statusLock:0};if(f.expectedStatusLock===void 0)W=(await this.getSession(f.sessionId))?.statusLock??0;return{updated:!0,statusLock:W}}async deleteSession(f,$){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}async enqueueSpawnRequest(f){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
544
544
  VALUES (?, ?, ?, ?, ?, NULL)`,[f.rootSessionId,f.parentAgentId,f.task??null,f.systemPrompt??null,s()])}async claimSpawnRequest(f,$){let J=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
545
545
  WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
546
- ORDER BY id ASC LIMIT 1`,[f,$]);if(!J||typeof J.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[s(),J.id]),J.task??void 0}}class Z0 extends z0{store;constructor(f,$={}){super(new gP(f,$.sessionArtifactsDir),$);this.store=f}createRootSession(f){this.store.run(`INSERT OR REPLACE INTO sessions (
546
+ ORDER BY id ASC LIMIT 1`,[f,$]);if(!J||typeof J.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[s(),J.id]),J.task??void 0}}class j0 extends b0{store;constructor(f,$={}){super(new jA(f,$.sessionArtifactsDir),$);this.store=f}createRootSession(f){this.store.run(`INSERT OR REPLACE INTO sessions (
547
547
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
548
548
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
549
549
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
550
550
  metadata_json, transcript_path, hook_path, messages_path, updated_at
551
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,null,null,"running",0,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,null,null,null,null,0,f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"","",f.messagesPath,s()])}}function kT(f){if(f.backendMode)return f.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let $=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if($==="local"||$==="hub"||$==="remote")return $;return"auto"}var P4,X4;function mT(f,$){if(f!=="auto"&&f!=="hub")return;if($.hub?.endpoint?.trim())return;J6($.hub?.workspaceRoot?.trim()||$.hub?.cwd?.trim()||process.cwd())}async function IT(f){await f.reconcileDeadSessions?.().catch(()=>{})}function cP(f){try{let $=new W0;return $.init(),new Z0($,{messagesArtifactUploader:f.messagesArtifactUploader})}catch{return f.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new o5(void 0,{messagesArtifactUploader:f.messagesArtifactUploader})}}function uP(f,$,J){return new j0({sessionService:J??f.sessionService??cP(f),capabilities:f.capabilities,telemetry:f.telemetry,toolPolicies:f.toolPolicies,distinctId:$,fetch:f.fetch})}async function J9(f){if(P4)return P4;if(X4)return await X4;return X4=(async()=>{return P4=cP(f),await IT(P4),P4})().finally(()=>{X4=void 0}),await X4}async function e1(f){let $=F$(f.distinctId);f.telemetry?.setDistinctId($);let J=kT(f);if(mT(J,f),J==="remote"){let H=f.remote?.endpoint?.trim();if(!H)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return f.logger?.log("Using remote runtime host",{endpoint:H}),new n1({endpoint:H,authToken:f.remote?.authToken,clientType:f.remote?.clientType,displayName:f.remote?.displayName,workspaceRoot:f.remote?.workspaceRoot,cwd:f.remote?.cwd,capabilities:f.capabilities})}if(J==="hub"){let H=f.hub?.endpoint?.trim(),W=H||await K$({strategy:f.hub?.strategy??"require-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(!W)throw Error("No compatible hub runtime is available.");return f.logger?.log("Using hub runtime host",{url:W,explicitEndpoint:H||void 0}),new _0({url:W,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd})}if(J==="auto"){let H=await x2({endpoint:f.hub?.endpoint,strategy:f.hub?.strategy??"prefer-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(H){f.logger?.log("Using discovered local hub runtime host",{url:H});let W=new _0({url:H,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});try{return await W.connect(),W}catch(Q){f.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:Q})}}return f.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),uP(f,$)}return uP(f,$)}class V4{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor(f,$,J,H,W,Q,Z,j,P){this.clientName=$,this.runtimeAddress=J,this.host=f,this.prepare=H,this.capabilities=W,this.logger=Q,this.telemetry=Z,this.distinctId=j,this.settings=lj(f),this.pendingPrompts=pj(f),this.automation=new K5(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=P?new $4({workspaceRoot:P.workspaceRoot??process.cwd(),specs:{cronSpecsDir:P.cronSpecsDir??P.cronDir,scope:Mj(P.cronScope),workspaceRoot:P.workspaceRoot},runtimeHandlers:_j({host:f,getExtensionContext:()=>FJ({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:P.dbPath,logger:P.logger,pollIntervalMs:P.pollIntervalMs,claimLeaseSeconds:P.claimLeaseSeconds,globalMaxConcurrency:P.globalMaxConcurrency,watcherDebounceMs:P.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((X)=>{if(X.type!=="ended")return;this.disposeSessionBootstrap(X.payload.sessionId)})}static async create(f={}){let $=Bf(f.capabilities),J=await e1({...f,capabilities:$}),H=Dj(f.automation),W=new V4(J,f.clientName,J.runtimeAddress,f.prepare,$,f.logger,f.telemetry,f.distinctId,H?{...H,logger:f.logger}:void 0);if(H&&H.autoStart!==!1)await W.automation.start();return W}async disposeSessionBootstrap(f){let $=this.activeSessionBootstraps.get(f);if(!$)return;this.activeSessionBootstraps.delete(f),await Promise.resolve($.dispose?.())}async start(f){let $=nj(f),J=await this.prepare?.($);try{let H=J?await J.applyToStartSessionInput($):$,W=await this.host.startSession(L5(H,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>FJ({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(W.sessionId))this.activeSessionBootstraps.set(W.sessionId,J);else await Promise.resolve(J.dispose?.());return aj({input:H,sessionId:W.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),W}catch(H){throw await Promise.resolve(J?.dispose?.()),H}}send=(...f)=>this.host.runTurn(...f);getAccumulatedUsage=(...f)=>{return this.host.getAccumulatedUsage?.(...f)??Promise.resolve(void 0)};abort=(...f)=>this.host.abort(...f);stop=async(f)=>{await this.host.stopSession(f),await this.disposeSessionBootstrap(f)};dispose=async(...f)=>{try{await this.automationService?.dispose(),await this.host.dispose(...f)}finally{this.unsubscribeBootstrapCleanup();let $=[...this.activeSessionBootstraps.keys()];await Promise.allSettled($.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...f)=>this.host.getSession(...f);listHistory=async(f={})=>await OJ(this.host,f);list=async(f=200,$={})=>await this.listHistory({...$,limit:f});delete=async(f)=>{let $=await this.host.deleteSession(f);if($)await this.disposeSessionBootstrap(f);return $};update=(...f)=>this.host.updateSession(...f);readMessages=(...f)=>this.host.readSessionMessages(...f);async restore(f){let $=f.start?L5(f.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>FJ({automationService:this.automationService,automation:this.automation,context:J,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:f.sessionId,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restore:f.restore,start:$})}ingestHookEvent=(...f)=>this.host.dispatchHookEvent(...f);subscribe(f,$){return this.host.subscribe(f,$)}updateSessionModel=(...f)=>{return this.host.updateSessionModel?.(...f)??Promise.resolve()}}var lP={};N(lP,{resolvePluginConfigSearchPaths:()=>F8,resolveAndLoadAgentPlugins:()=>w1,resolveAgentPluginPaths:()=>E$,loadAgentPluginsFromPathsWithDiagnostics:()=>D0,loadAgentPluginsFromPaths:()=>O6,loadAgentPluginFromPath:()=>R8,discoverPluginModulePaths:()=>y8});var $X={};N($X,{resolveMcpServerRegistrations:()=>A4,resolveDefaultMcpSettingsPath:()=>Q$,registerMcpServersFromSettingsFile:()=>J2,loadMcpSettingsFile:()=>B4,hasMcpSettingsFile:()=>$2,createMcpTools:()=>H2,createDisabledMcpToolPolicy:()=>R4,createDisabledMcpToolPolicies:()=>EJ,createDefaultMcpServerClientFactory:()=>f2,InMemoryMcpManager:()=>l$});import{spawn as xT}from"node:child_process";import{StringDecoder as aP}from"node:string_decoder";var gT="2024-11-05",vT=5000,uT=1500;function pP(f){return f instanceof Error?f.message:String(f)}function iP(f){let $=Buffer.from(JSON.stringify(f),"utf8"),J=Buffer.from(`Content-Length: ${$.byteLength}\r
551
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,null,null,"running",0,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,null,null,null,null,0,f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"","",f.messagesPath,s()])}}function V_(f){if(f.backendMode)return f.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let $=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if($==="local"||$==="hub"||$==="remote")return $;return"auto"}var V4,R4;function R_(f,$){if(f!=="auto"&&f!=="hub")return;if($.hub?.endpoint?.trim())return;X6($.hub?.workspaceRoot?.trim()||$.hub?.cwd?.trim()||process.cwd())}async function F_(f){await f.reconcileDeadSessions?.().catch(()=>{})}function PA(f){try{let $=new Q0;return $.init(),new j0($,{messagesArtifactUploader:f.messagesArtifactUploader})}catch{return f.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new H9(void 0,{messagesArtifactUploader:f.messagesArtifactUploader})}}function AA(f,$,J){return new X0({sessionService:J??f.sessionService??PA(f),capabilities:f.capabilities,telemetry:f.telemetry,toolPolicies:f.toolPolicies,distinctId:$,fetch:f.fetch})}async function X9(f){if(V4)return V4;if(R4)return await R4;return R4=(async()=>{return V4=PA(f),await F_(V4),V4})().finally(()=>{R4=void 0}),await R4}async function J2(f){let $=G$(f.distinctId);f.telemetry?.setDistinctId($);let J=V_(f);if(R_(J,f),J==="remote"){let W=f.remote?.endpoint?.trim();if(!W)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return f.logger?.log("Using remote runtime host",{endpoint:W}),new s1({endpoint:W,authToken:f.remote?.authToken,clientType:f.remote?.clientType,displayName:f.remote?.displayName,workspaceRoot:f.remote?.workspaceRoot,cwd:f.remote?.cwd,capabilities:f.capabilities})}if(J==="hub"){let W=f.hub?.endpoint?.trim(),H=W||await T$({strategy:f.hub?.strategy??"require-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(!H)throw Error("No compatible hub runtime is available.");return f.logger?.log("Using hub runtime host",{url:H,explicitEndpoint:W||void 0}),new q0({url:H,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd})}if(J==="auto"){let W=await v2({endpoint:f.hub?.endpoint,strategy:f.hub?.strategy??"prefer-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(W){f.logger?.log("Using discovered local hub runtime host",{url:W});let H=new q0({url:W,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});try{return await H.connect(),H}catch(Q){f.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:Q})}}return f.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),AA(f,$)}return AA(f,$)}class F4{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor(f,$,J,W,H,Q,Z,j,X){this.clientName=$,this.runtimeAddress=J,this.host=f,this.prepare=W,this.capabilities=H,this.logger=Q,this.telemetry=Z,this.distinctId=j,this.settings=VX(f),this.pendingPrompts=RX(f),this.automation=new DH(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=X?new Z4({workspaceRoot:X.workspaceRoot??process.cwd(),specs:{cronSpecsDir:X.cronSpecsDir??X.cronDir,scope:lj(X.cronScope),workspaceRoot:X.workspaceRoot},runtimeHandlers:pj({host:f,getExtensionContext:()=>VJ({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:X.dbPath,logger:X.logger,pollIntervalMs:X.pollIntervalMs,claimLeaseSeconds:X.claimLeaseSeconds,globalMaxConcurrency:X.globalMaxConcurrency,watcherDebounceMs:X.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((A)=>{if(A.type!=="ended")return;this.disposeSessionBootstrap(A.payload.sessionId)})}static async create(f={}){let $=Uf(f.capabilities),J=await J2({...f,capabilities:$}),W=rj(f.automation),H=new F4(J,f.clientName,J.runtimeAddress,f.prepare,$,f.logger,f.telemetry,f.distinctId,W?{...W,logger:f.logger}:void 0);if(W&&W.autoStart!==!1)await H.automation.start();return H}async disposeSessionBootstrap(f){let $=this.activeSessionBootstraps.get(f);if(!$)return;this.activeSessionBootstraps.delete(f),await Promise.resolve($.dispose?.())}async start(f){let $=KX(f),J=await this.prepare?.($);try{let W=J?await J.applyToStartSessionInput($):$,H=await this.host.startSession(qH(W,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>VJ({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(H.sessionId))this.activeSessionBootstraps.set(H.sessionId,J);else await Promise.resolve(J.dispose?.());return yX({input:W,sessionId:H.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),H}catch(W){throw await Promise.resolve(J?.dispose?.()),W}}send=(...f)=>this.host.runTurn(...f);getAccumulatedUsage=(...f)=>{return this.host.getAccumulatedUsage?.(...f)??Promise.resolve(void 0)};abort=(...f)=>this.host.abort(...f);stop=async(f)=>{await this.host.stopSession(f),await this.disposeSessionBootstrap(f)};dispose=async(...f)=>{try{await this.automationService?.dispose(),await this.host.dispose(...f)}finally{this.unsubscribeBootstrapCleanup();let $=[...this.activeSessionBootstraps.keys()];await Promise.allSettled($.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...f)=>this.host.getSession(...f);listHistory=async(f={})=>await hJ(this.host,f);list=async(f=200,$={})=>await this.listHistory({...$,limit:f});delete=async(f)=>{let $=await this.host.deleteSession(f);if($)await this.disposeSessionBootstrap(f);return $};update=(...f)=>this.host.updateSession(...f);readMessages=(...f)=>this.host.readSessionMessages(...f);async restore(f){let $=f.start?qH(f.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>VJ({automationService:this.automationService,automation:this.automation,context:J,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:f.sessionId,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restore:f.restore,start:$})}ingestHookEvent=(...f)=>this.host.dispatchHookEvent(...f);subscribe(f,$){return this.host.subscribe(f,$)}updateSessionModel=(...f)=>{return this.host.updateSessionModel?.(...f)??Promise.resolve()}}var VA={};N(VA,{resolvePluginConfigSearchPaths:()=>G8,resolveAndLoadAgentPlugins:()=>I1,resolveAgentPluginPaths:()=>I$,loadAgentPluginsFromPathsWithDiagnostics:()=>z0,loadAgentPluginsFromPaths:()=>b6,loadAgentPluginFromPath:()=>U8,discoverPluginModulePaths:()=>T8});var MA={};N(MA,{resolveMcpServerRegistrations:()=>U4,resolveDefaultMcpSettingsPath:()=>P$,registerMcpServersFromSettingsFile:()=>Q2,loadMcpSettingsFile:()=>y4,hasMcpSettingsFile:()=>H2,createMcpTools:()=>Z2,createDisabledMcpToolPolicy:()=>G4,createDisabledMcpToolPolicies:()=>bJ,createDefaultMcpServerClientFactory:()=>W2,InMemoryMcpManager:()=>i$});import{spawn as K_}from"node:child_process";import{StringDecoder as yA}from"node:string_decoder";var y_="2024-11-05",U_=5000,G_=1500;function RA(f){return f instanceof Error?f.message:String(f)}function FA(f){let $=Buffer.from(JSON.stringify(f),"utf8"),J=Buffer.from(`Content-Length: ${$.byteLength}\r
552
552
  \r
553
- `,"utf8");return Buffer.concat([J,$])}function nP(f){return Buffer.from(`${JSON.stringify(f)}
554
- `,"utf8")}class H9{buffer="";decoder=new aP("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];while(!0){let J=this.buffer.indexOf(`\r
553
+ `,"utf8");return Buffer.concat([J,$])}function KA(f){return Buffer.from(`${JSON.stringify(f)}
554
+ `,"utf8")}class A9{buffer="";decoder=new yA("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];while(!0){let J=this.buffer.indexOf(`\r
555
555
  \r
556
- `);if(J<0)break;let W=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!W)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let Q=Number.parseInt(W[1],10),Z=J+4,j=Z+Q;if(this.buffer.length<j)break;$.push(this.buffer.slice(Z,j)),this.buffer=this.buffer.slice(j)}return $}}class W9{buffer="";decoder=new aP("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];while(!0){let J=this.buffer.indexOf(`
557
- `);if(J<0)break;let H=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),H.length>0)$.push(H)}return $}}class tP{registration;process;nextRequestId=1;pending=new Map;framedParser=new H9;newlineParser=new W9;stderrBuffer="";connected=!1;protocolMode="newline";constructor(f){this.registration=f}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let f=["newline","framed"],$;for(let J of f){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:gT,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},uT),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(H){$=H instanceof Error?H:Error(String(H))}}throw $??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let f=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!f)return;f.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter(($)=>typeof $?.name==="string"&&typeof $.inputSchema==="object"&&$.inputSchema!==null).map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}async callTool(f){return this.request("tools/call",{name:f.name,arguments:f.arguments??{}})}spawnProcess(f){let $=this.registration.transport;if($.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${$.type}`);this.framedParser=new H9,this.newlineParser=new W9,this.stderrBuffer="",this.protocolMode=f;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},H=xT($.command,$.args??[],{cwd:$.cwd,env:{...process.env,...$.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=H,H.stdout.on("data",(W)=>this.handleStdout(W)),H.stderr.on("data",(W)=>{if(this.process!==H)return;if(this.stderrBuffer+=W.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),H.once("error",(W)=>{if(this.process!==H)return;this.failAllPending(Error(`MCP process error: ${pP(W)}`))}),H.once("exit",(W,Q)=>{if(this.process!==H)return;this.connected=!1,this.process=void 0;let Z=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${W??"null"}, signal=${Q??"null"}).${Z}`))})}handleStdout(f){try{let $=this.protocolMode==="framed"?this.framedParser.push(f):this.newlineParser.push(f);for(let J of $){let H=JSON.parse(J);if(typeof H.id!=="number")continue;let W=this.pending.get(H.id);if(!W)continue;if(this.pending.delete(H.id),clearTimeout(W.timeout),H.error){let Q=H.error.message||`MCP request failed with code ${H.error.code??"unknown"}`;W.reject(Error(Q));continue}W.resolve(H.result)}}catch($){this.handleProtocolFailure($)}}handleProtocolFailure(f){let $=this.process;if(!$)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${pP(f)}.${J}`)),$.kill()}async request(f,$,J=vT){let H=this.process;if(!H?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let W=this.nextRequestId++,Q={jsonrpc:"2.0",id:W,method:f,...$?{params:$}:{}},Z=new Promise((j,P)=>{let X=setTimeout(()=>{this.pending.delete(W),P(Error(`MCP request timed out for "${this.registration.name}" (${f}).`))},J);this.pending.set(W,{resolve:j,reject:P,timeout:X})});try{H.stdin.write(this.protocolMode==="framed"?iP(Q):nP(Q))}catch(j){let P=this.pending.get(W);if(P)clearTimeout(P.timeout),this.pending.delete(W);throw j}return Z}notify(f,$){let J=this.process;if(!J?.stdin.writable)return;let H={jsonrpc:"2.0",method:f,...$?{params:$}:{}};J.stdin.write(this.protocolMode==="framed"?iP(H):nP(H))}failAllPending(f){for(let[$,J]of this.pending)clearTimeout(J.timeout),this.pending.delete($),J.reject(f)}}function f2(){return(f)=>new tP(f)}import{existsSync as cT,readFileSync as dT}from"node:fs";import{resolveMcpSettingsPath as rT}from"@cline/shared/storage";import{z as k}from"zod";var Y4=k.record(k.string(),k.string()),sP=k.record(k.string(),k.unknown()),lT=k.object({type:k.literal("stdio"),command:k.string().min(1),args:k.array(k.string()).optional(),cwd:k.string().min(1).optional(),env:Y4.optional()}),pT=k.object({type:k.literal("sse"),url:k.string().url(),headers:Y4.optional()}),iT=k.object({type:k.literal("streamableHttp"),url:k.string().url(),headers:Y4.optional()}),nT=k.discriminatedUnion("type",[lT,pT,iT]),aT=k.object({transport:nT,disabled:k.boolean().optional(),metadata:sP.optional()}),tT=k.enum(["stdio","sse","http","streamableHttp"]).optional(),oP=k.object({type:k.enum(["stdio","sse","streamableHttp"]).optional(),transportType:tT,disabled:k.boolean().optional(),metadata:sP.optional()});function Q9(f){if(!f)return;if(f==="http")return"streamableHttp";return f}var sT=oP.extend({command:k.string().min(1),args:k.array(k.string()).optional(),cwd:k.string().min(1).optional(),env:Y4.optional()}).superRefine((f,$)=>{let J=f.type??Q9(f.transportType);if(J&&J!=="stdio")$.addIssue({code:k.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform((f)=>({transport:{type:"stdio",command:f.command,args:f.args,cwd:f.cwd,env:f.env},disabled:f.disabled,metadata:f.metadata})),oT=oP.extend({url:k.string().url(),headers:Y4.optional()}).superRefine((f,$)=>{let J=f.type??Q9(f.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")$.addIssue({code:k.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform((f)=>{if((f.type??Q9(f.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata};return{transport:{type:"sse",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata}}),eT=k.union([aT,sT,oT]),fD=k.object({mcpServers:k.record(k.string(),eT)}).strict();function Q$(){return rT()}function B4(f={}){let $=f.filePath??Q$(),J=dT($,"utf8"),H;try{H=JSON.parse(J)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}let W=fD.safeParse(H);if(!W.success){let Q=W.error.issues.map((Z)=>{let j=Z.path.join(".");return j?`${j}: ${Z.message}`:Z.message}).join("; ");throw Error(`Invalid MCP settings at "${$}": ${Q}`)}return W.data}function $2(f={}){let $=f.filePath??Q$();return cT($)}function A4(f={}){let $=B4(f);return Object.entries($.mcpServers).map(([J,H])=>({name:J,transport:H.transport,disabled:H.disabled,metadata:H.metadata}))}async function J2(f,$={}){let J=A4($);for(let H of J)await f.registerServer(H);return J}function kf(){return Date.now()}function $D(f){return f.map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}class l${toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor(f){this.clientFactory=f.clientFactory,this.toolsCacheTtlMs=f.toolsCacheTtlMs??5000}async registerServer(f){await this.runExclusive(f.name,async()=>{let $=this.servers.get(f.name);if(!$){this.servers.set(f.name,{registration:{...f},status:"disconnected",updatedAt:kf()});return}let J=JSON.stringify($.registration.transport)!==JSON.stringify(f.transport);if($.registration={...f},$.updatedAt=kf(),J)await this.disconnectState($),$.client=void 0,$.toolCache=void 0,$.toolCacheUpdatedAt=void 0})}async unregisterServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($),this.servers.delete(f)})}async connectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.connectState($)})}async disconnectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($)})}async setServerDisabled(f,$){await this.runExclusive(f,async()=>{let J=this.requireServer(f);if(J.registration={...J.registration,disabled:$},J.updatedAt=kf(),$)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map((f)=>({name:f.registration.name,status:f.status,disabled:f.registration.disabled===!0,lastError:f.lastError,toolCount:f.toolCache?.length??0,updatedAt:f.updatedAt,metadata:f.registration.metadata})).sort((f,$)=>f.name.localeCompare($.name))}async listTools(f){let $=this.requireServer(f),J=$.toolCacheUpdatedAt??0;if($.toolCache&&kf()-J<=this.toolsCacheTtlMs)return $.toolCache;return this.refreshTools(f)}async refreshTools(f){return this.runExclusive(f,async()=>{let $=this.requireServer(f),H=await(await this.ensureConnectedClient($)).listTools(),W=$D(H);return $.toolCache=W,$.toolCacheUpdatedAt=kf(),$.updatedAt=kf(),W})}async callTool(f){return this.runExclusive(f.serverName,async()=>{let $=this.requireServer(f.serverName),J=await this.ensureConnectedClient($);return $.updatedAt=kf(),J.callTool({name:f.toolName,arguments:f.arguments,context:f.context})})}async dispose(){let f=[...this.servers.keys()];for(let $ of f)await this.unregisterServer($)}async ensureConnectedClient(f){if(await this.connectState(f),!f.client)throw Error(`MCP server "${f.registration.name}" does not have an initialized client.`);return f.client}async connectState(f){if(f.registration.disabled)throw Error(`MCP server "${f.registration.name}" is disabled and cannot be connected.`);if(f.status==="connected"&&f.client)return;f.status="connecting",f.updatedAt=kf();try{let $=f.client??await this.clientFactory(f.registration);await $.connect(),f.client=$,f.status="connected",f.lastError=void 0,f.updatedAt=kf()}catch($){throw f.status="disconnected",f.lastError=$ instanceof Error?$.message:String($),f.updatedAt=kf(),$}}async disconnectState(f){if(!f.client){f.status="disconnected",f.updatedAt=kf();return}try{await f.client.disconnect()}finally{f.status="disconnected",f.updatedAt=kf()}}requireServer(f){let $=this.servers.get(f);if(!$)throw Error(`Unknown MCP server: ${f}`);return $}async runExclusive(f,$){let J=this.operationLocks.get(f)??Promise.resolve(),H,W=new Promise((Z)=>{H=Z}),Q=J.catch(()=>{return}).then(()=>W);this.operationLocks.set(f,Q),await J.catch(()=>{return});try{return await $()}finally{if(H?.(),this.operationLocks.get(f)===Q)this.operationLocks.delete(f)}}}import{createHash as JD}from"node:crypto";var eP=128,HD=/[^a-zA-Z0-9_-]+/g,fX=8,WD=1,QD="mcp_tool";function ZD(f){return JD("sha1").update(f).digest("hex").slice(0,fX)}function jD(f){return f.replace(HD,"_")}var CJ=({serverName:f,toolName:$})=>{let J=`${f}__${$}`,H=jD(J);if(H===J&&J.length<=eP)return J;let W=ZD(J),Q=eP-WD-fX;return`${H.slice(0,Q)||QD}_${W}`};function R4(f){return{[(f.nameTransform??CJ)({serverName:f.serverName,toolName:f.toolName})]:{enabled:!1}}}function EJ(f){let $={};for(let J of f.toolNames)Object.assign($,R4({serverName:f.serverName,toolName:J,nameTransform:f.nameTransform}));return $}import{createTool as PD}from"@cline/shared";function XD(f,$){let J=$.description?.trim();if(J)return J;return`Execute MCP tool "${$.name}" from server "${f}".`}async function H2(f){let $=await f.provider.listTools(f.serverName),J=f.nameTransform??CJ;return $.map((H)=>{let W=J({serverName:f.serverName,toolName:H.name});return PD({name:W,description:XD(f.serverName,H),inputSchema:H.inputSchema,timeoutMs:f.timeoutMs,retryable:f.retryable,maxRetries:f.maxRetries,execute:async(Q,Z)=>f.provider.callTool({serverName:f.serverName,toolName:H.name,arguments:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:void 0,context:Z})})})}var WX={};N(WX,{toHookConfigFileName:()=>G8,runSubprocessEvent:()=>W2,runHook:()=>Z2,resolveHooksConfigSearchPaths:()=>K8,parseHookEventPayload:()=>Q2,mergeAgentHooks:()=>I$,listHookConfigFiles:()=>t0,createSubprocessHooks:()=>mJ,createHookConfigFileHooks:()=>h8,createHookConfigFileExtension:()=>k1,createHookAuditHooks:()=>S1,createAgentHooksExtension:()=>C1,HookEventPayloadSchema:()=>kJ,HookEventNameSchema:()=>SJ,HookConfigFileName:()=>E1,HOOK_CONFIG_FILE_EVENT_MAP:()=>U8,HOOKS_CONFIG_DIRECTORY_NAME:()=>b6});import{HookEventNameSchema as SJ,HookEventPayloadSchema as kJ,parseHookEventPayload as Q2,resolveHookSessionContext as yD}from"@cline/shared";import{z as p$}from"zod";import{spawn as VD}from"node:child_process";import{augmentNodeCommandForDebug as YD,withResolvedClineBuildEnv as BD}from"@cline/shared";function AD(f){let $=f.trim();if(!$)return{};let H=$.split(`
558
- `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),W=H.length>0?H[H.length-1]:$;try{return{parsedJson:JSON.parse(W)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse subprocess stdout JSON"}}}function RD(f,$){let J=f instanceof Error?f:Error(String(f)),H=J,W=$.join(" ");if(H.code==="EACCES")return Error(`Failed to execute hook command "${W}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${W}": ${J.message}`)}async function FD(f,$){let J=f.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((H,W)=>{let Q=(Z)=>{J.off("error",Q);let j=Z.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){H();return}W(Z)};J.once("error",Q),J.end($,(Z)=>{if(J.off("error",Q),Z){let j=Z.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){H();return}W(Z);return}H()})})}async function W2(f,$){let J=YD($.command,{env:$.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let H=!!$.detached,W=VD(J[0],J.slice(1),{cwd:$.cwd,env:BD($.env),stdio:H?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:H}),Q=new Promise((B)=>{W.once("spawn",()=>{try{$.onSpawn?.({command:J,pid:W.pid??void 0,detached:H})}catch{}B()})}),Z=new Promise((B,A)=>{W.once("error",(R)=>{A(RD(R,J))})});if(await FD(W,JSON.stringify(f)),H){await Promise.race([Q,Z]),W.unref();return}if(!W.stdout||!W.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let j="",P="",X=!1,V;W.stdout.on("data",(B)=>{j+=B.toString()}),W.stderr.on("data",(B)=>{P+=B.toString()});let Y=new Promise((B)=>{if(($.timeoutMs??0)>0)V=setTimeout(()=>{X=!0,W.kill("SIGKILL")},$.timeoutMs);W.once("close",(A)=>{if(V)clearTimeout(V);let{parsedJson:R,parseError:U}=AD(j);B({exitCode:A,stdout:j,stderr:P,parsedJson:R,parseError:U,timedOut:X})})});return await Promise.race([Y,Z])}var KD=p$.object({contextModification:p$.string().optional(),cancel:p$.boolean().optional(),review:p$.boolean().optional(),errorMessage:p$.string().optional(),context:p$.string().optional(),overrideInput:p$.unknown().optional()}).passthrough();var UD=["agent","hook"];async function Z2(f,$={}){let J=$.command??UD;return await W2(f,{command:J,cwd:$.cwd,env:$.env,detached:$.detached,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn})}function HX(f){return f instanceof Error?f:Error(String(f))}function GD(f){if(!f||typeof f!=="object")return;let $=KD.safeParse(f);if(!$.success)return;let J=$.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let W=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:W,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function JX(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,H]of Object.entries(f))if(typeof H==="string")$[J]=H;else $[J]=JSON.stringify(H);return $}function O0(f,$,J){let H=J.env??process.env,W=H.CLINE_USER_ID?.trim()||H.USER?.trim()||"unknown",Q=J.cwd||process.cwd();return{clineVersion:H.CLINE_VERSION?.trim()||"",hookName:f,timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:yD(J.sessionContext,{hookName:f,conversationId:$.conversationId,agentId:$.agentId,parentAgentId:$.parentAgentId}),workspaceRoots:Q?[Q]:[],workspaceInfo:J.workspaceInfo,userId:W,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function hD(f){return{name:f.name,message:f.message,stack:f.stack}}function TD(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function DD(f){return{agentId:f.snapshot.agentId,conversationId:f.snapshot.conversationId??f.snapshot.runId??f.snapshot.agentId,parentAgentId:f.snapshot.parentAgentId??null}}function MD(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function _D(f){return{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}function LD(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}async function i$(f,$){try{let J=await Z2(f,{command:$.command,cwd:$.cwd,env:$.env,detached:!0,onSpawn:$.onSpawn});$.onDispatch?.({payload:f,result:J,detached:!0})}catch(J){$.onDispatchError?.(HX(J),f)}}function mJ(f={}){return{hooks:{beforeRun:async(j)=>{let P=DD(j);if((f.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let V={...O0("agent_resume",P,f),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await i$(V,f)}else{let V={...O0("agent_start",P,f),hookName:"agent_start",taskStart:{taskMetadata:{}}};await i$(V,f)}return},beforeTool:async(j)=>{let P={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},X={...O0("tool_call",P,f),hookName:"tool_call",iteration:j.snapshot.iteration,tool_call:{id:j.toolCall.toolCallId,name:j.toolCall.toolName,input:j.input},preToolUse:{toolName:j.toolCall.toolName,parameters:JX(j.input)}};try{let V=await Z2(X,{command:f.command,cwd:f.cwd,env:f.env,detached:!1,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn});if(f.onDispatch?.({payload:X,result:V,detached:!1}),V?.timedOut)throw Error("tool_call hook command timed out");if(V?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${V.parseError}`);return LD(GD(V?.parsedJson))}catch(V){f.onDispatchError?.(HX(V),X);return}},afterTool:async(j)=>{let P=_D(j),X={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},V={...O0("tool_result",X,f),hookName:"tool_result",iteration:j.snapshot.iteration,tool_result:P,postToolUse:{toolName:P.name,parameters:JX(P.input),result:typeof P.output==="string"?P.output:JSON.stringify(P.output),success:!P.error,executionTimeMs:P.durationMs}};await i$(V,f);return},afterRun:async({snapshot:j,result:P})=>{let X={agentId:j.agentId,conversationId:j.conversationId??j.runId??j.agentId,parentAgentId:j.parentAgentId??null};if(P.status==="completed"){let B={...O0("agent_end",X,f),hookName:"agent_end",iteration:P.iterations,turn:{outputText:P.outputText,status:P.status},taskComplete:{taskMetadata:{}}};await i$(B,f);return}let V=P.status==="aborted"||TD(P.error?.message)?"agent_abort":"agent_error",Y=V==="agent_error"?{...O0(V,X,f),hookName:V,iteration:P.iterations,error:hD(P.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...O0(V,X,f),hookName:V,reason:P.error?.message,taskCancel:{taskMetadata:{}}};await i$(Y,f)},onEvent:async(j)=>{if(j.type!=="message-added"||j.message.role!=="user")return;let P={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},X={...O0("prompt_submit",P,f),hookName:"prompt_submit",userPromptSubmit:{prompt:MD(j.message.content),attachments:[]}};await i$(X,f)}},shutdown:async({agentId:j,conversationId:P,parentAgentId:X,reason:V})=>{let Y={...O0("session_shutdown",{agentId:j,conversationId:P,parentAgentId:X},f),hookName:"session_shutdown",reason:V};await i$(Y,f)}}}var BX={};N(BX,{createTeamName:()=>IJ,DefaultRuntimeBuilder:()=>X2});import{hasRuntimeConfigExtension as gD}from"@cline/shared";import{nanoid as vD}from"nanoid";F0();var VX={};N(VX,{createLocalTeamStore:()=>X9,SqliteTeamStore:()=>n$,FileTeamStore:()=>F4});import{appendFileSync as zD,existsSync as j2,mkdirSync as QX,readdirSync as OD,readFileSync as ZX,renameSync as ND,writeFileSync as qD}from"node:fs";import{join as Z9}from"node:path";import{resolveTeamDataDir as bD}from"@cline/shared/storage";function jX(){return new Date().toISOString()}function j9(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function PX(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class F4{teamDirPath;constructor(f={}){this.teamDirPath=f.teamDir??bD()}init(){this.ensureTeamDir()}listTeamNames(){if(!j2(this.teamDirPath))return[];return OD(this.teamDirPath,{withFileTypes:!0}).filter((f)=>f.isDirectory()).filter((f)=>j2(this.statePath(f.name))).map((f)=>f.name).sort()}readState(f){let $=this.readEnvelope(f);return $?.teamState?PX($.teamState):void 0}readHistory(f,$=200){let J=this.historyPath(f);if(!j2(J))return[];return ZX(J,"utf8").split(`
559
- `).map((H)=>H.trim()).filter(Boolean).map((H)=>{try{return JSON.parse(H)}catch{return}}).filter((H)=>H!==void 0).reverse().slice(0,$)}loadRuntime(f){let $=this.readEnvelope(f);return{state:$?.teamState?PX($.teamState):void 0,teammates:$?.teammates??[],interruptedRunIds:[]}}handleTeamEvent(f,$){this.ensureTeamSubdir(f),zD(this.historyPath(f),`${JSON.stringify({ts:jX(),eventType:$.type,payload:$})}
560
- `,"utf8")}persistRuntime(f,$,J){this.ensureTeamSubdir(f);let H={version:1,updatedAt:jX(),teamState:$,teammates:J},W=this.statePath(f),Q=`${W}.tmp`;qD(Q,`${JSON.stringify(H,null,2)}
561
- `,"utf8"),ND(Q,W)}markInProgressRunsInterrupted(f,$){let J=this.readEnvelope(f);if(!J?.teamState?.runs?.length)return[];let H=J.teamState.runs.filter((Q)=>Q.status==="queued"||Q.status==="running").map((Q)=>Q.id);if(H.length===0)return[];let W=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((Q)=>Q.status==="queued"||Q.status==="running"?{...Q,status:"interrupted",error:$,endedAt:W}:Q)},this.persistRuntime(f,J.teamState,J.teammates),H}ensureTeamDir(){if(!j2(this.teamDirPath))QX(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir(f){let $=Z9(this.ensureTeamDir(),j9(f));if(!j2($))QX($,{recursive:!0});return $}statePath(f){return Z9(this.ensureTeamDir(),j9(f),"state.json")}historyPath(f){return Z9(this.ensureTeamDir(),j9(f),"task-history.jsonl")}readEnvelope(f){let $=this.statePath(f);if(!j2($))return;try{let J=JSON.parse(ZX($,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as wD,mkdirSync as CD}from"node:fs";import{join as ED}from"node:path";import{safeJsonParse as XX}from"@cline/shared";import{loadSqliteDb as SD,nowIso as P9}from"@cline/shared/db";import{resolveDbDataDir as kD}from"@cline/shared/storage";function mD(){return kD()}function P2(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function ID(f){let $=XX(f);if(!Array.isArray($))return[];let J=[];for(let H of $){if(!H||typeof H!=="object")continue;let W=H,Q=W.agentId,Z=W.rolePrompt;if(typeof Q!=="string"||!Q.trim())continue;if(typeof Z!=="string"||!Z.trim())continue;let j={agentId:Q.trim(),rolePrompt:Z};if(typeof W.modelId==="string"&&W.modelId.trim())j.modelId=W.modelId.trim();if(typeof W.maxIterations==="number"&&Number.isFinite(W.maxIterations))j.maxIterations=Math.max(1,Math.floor(W.maxIterations));J.push(j)}return J}function xD(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class n${teamDirPath;db;constructor(f={}){this.teamDirPath=f.teamDir??mD()}init(){this.getRawDb()}ensureTeamDir(){if(!wD(this.teamDirPath))CD(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return ED(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let f=SD(this.dbPath());return this.ensureSchema(f),this.db=f,f}ensureSchema(f){if(f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec(`
556
+ `);if(J<0)break;let H=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!H)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let Q=Number.parseInt(H[1],10),Z=J+4,j=Z+Q;if(this.buffer.length<j)break;$.push(this.buffer.slice(Z,j)),this.buffer=this.buffer.slice(j)}return $}}class P9{buffer="";decoder=new yA("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];while(!0){let J=this.buffer.indexOf(`
557
+ `);if(J<0)break;let W=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),W.length>0)$.push(W)}return $}}class UA{registration;process;nextRequestId=1;pending=new Map;framedParser=new A9;newlineParser=new P9;stderrBuffer="";connected=!1;protocolMode="newline";constructor(f){this.registration=f}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let f=["newline","framed"],$;for(let J of f){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:y_,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},G_),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(W){$=W instanceof Error?W:Error(String(W))}}throw $??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let f=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!f)return;f.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter(($)=>typeof $?.name==="string"&&typeof $.inputSchema==="object"&&$.inputSchema!==null).map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}async callTool(f){return this.request("tools/call",{name:f.name,arguments:f.arguments??{}})}spawnProcess(f){let $=this.registration.transport;if($.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${$.type}`);this.framedParser=new A9,this.newlineParser=new P9,this.stderrBuffer="",this.protocolMode=f;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=K_($.command,$.args??[],{cwd:$.cwd,env:{...process.env,...$.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=W,W.stdout.on("data",(H)=>this.handleStdout(H)),W.stderr.on("data",(H)=>{if(this.process!==W)return;if(this.stderrBuffer+=H.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),W.once("error",(H)=>{if(this.process!==W)return;this.failAllPending(Error(`MCP process error: ${RA(H)}`))}),W.once("exit",(H,Q)=>{if(this.process!==W)return;this.connected=!1,this.process=void 0;let Z=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${H??"null"}, signal=${Q??"null"}).${Z}`))})}handleStdout(f){try{let $=this.protocolMode==="framed"?this.framedParser.push(f):this.newlineParser.push(f);for(let J of $){let W=JSON.parse(J);if(typeof W.id!=="number")continue;let H=this.pending.get(W.id);if(!H)continue;if(this.pending.delete(W.id),clearTimeout(H.timeout),W.error){let Q=W.error.message||`MCP request failed with code ${W.error.code??"unknown"}`;H.reject(Error(Q));continue}H.resolve(W.result)}}catch($){this.handleProtocolFailure($)}}handleProtocolFailure(f){let $=this.process;if(!$)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${RA(f)}.${J}`)),$.kill()}async request(f,$,J=U_){let W=this.process;if(!W?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let H=this.nextRequestId++,Q={jsonrpc:"2.0",id:H,method:f,...$?{params:$}:{}},Z=new Promise((j,X)=>{let A=setTimeout(()=>{this.pending.delete(H),X(Error(`MCP request timed out for "${this.registration.name}" (${f}).`))},J);this.pending.set(H,{resolve:j,reject:X,timeout:A})});try{W.stdin.write(this.protocolMode==="framed"?FA(Q):KA(Q))}catch(j){let X=this.pending.get(H);if(X)clearTimeout(X.timeout),this.pending.delete(H);throw j}return Z}notify(f,$){let J=this.process;if(!J?.stdin.writable)return;let W={jsonrpc:"2.0",method:f,...$?{params:$}:{}};J.stdin.write(this.protocolMode==="framed"?FA(W):KA(W))}failAllPending(f){for(let[$,J]of this.pending)clearTimeout(J.timeout),this.pending.delete($),J.reject(f)}}function W2(){return(f)=>new UA(f)}import{existsSync as T_,readFileSync as D_}from"node:fs";import{resolveMcpSettingsPath as __}from"@cline/shared/storage";import{z as I}from"zod";var K4=I.record(I.string(),I.string()),GA=I.record(I.string(),I.unknown()),M_=I.object({type:I.literal("stdio"),command:I.string().min(1),args:I.array(I.string()).optional(),cwd:I.string().min(1).optional(),env:K4.optional()}),L_=I.object({type:I.literal("sse"),url:I.string().url(),headers:K4.optional()}),h_=I.object({type:I.literal("streamableHttp"),url:I.string().url(),headers:K4.optional()}),O_=I.discriminatedUnion("type",[M_,L_,h_]),z_=I.object({transport:O_,disabled:I.boolean().optional(),metadata:GA.optional()}),N_=I.enum(["stdio","sse","http","streamableHttp"]).optional(),TA=I.object({type:I.enum(["stdio","sse","streamableHttp"]).optional(),transportType:N_,disabled:I.boolean().optional(),metadata:GA.optional()});function B9(f){if(!f)return;if(f==="http")return"streamableHttp";return f}var q_=TA.extend({command:I.string().min(1),args:I.array(I.string()).optional(),cwd:I.string().min(1).optional(),env:K4.optional()}).superRefine((f,$)=>{let J=f.type??B9(f.transportType);if(J&&J!=="stdio")$.addIssue({code:I.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform((f)=>({transport:{type:"stdio",command:f.command,args:f.args,cwd:f.cwd,env:f.env},disabled:f.disabled,metadata:f.metadata})),w_=TA.extend({url:I.string().url(),headers:K4.optional()}).superRefine((f,$)=>{let J=f.type??B9(f.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")$.addIssue({code:I.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform((f)=>{if((f.type??B9(f.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata};return{transport:{type:"sse",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata}}),b_=I.union([z_,q_,w_]),C_=I.object({mcpServers:I.record(I.string(),b_)}).strict();function P$(){return __()}function y4(f={}){let $=f.filePath??P$(),J=D_($,"utf8"),W;try{W=JSON.parse(J)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}let H=C_.safeParse(W);if(!H.success){let Q=H.error.issues.map((Z)=>{let j=Z.path.join(".");return j?`${j}: ${Z.message}`:Z.message}).join("; ");throw Error(`Invalid MCP settings at "${$}": ${Q}`)}return H.data}function H2(f={}){let $=f.filePath??P$();return T_($)}function U4(f={}){let $=y4(f);return Object.entries($.mcpServers).map(([J,W])=>({name:J,transport:W.transport,disabled:W.disabled,metadata:W.metadata}))}async function Q2(f,$={}){let J=U4($);for(let W of J)await f.registerServer(W);return J}function vf(){return Date.now()}function E_(f){return f.map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}class i${toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor(f){this.clientFactory=f.clientFactory,this.toolsCacheTtlMs=f.toolsCacheTtlMs??5000}async registerServer(f){await this.runExclusive(f.name,async()=>{let $=this.servers.get(f.name);if(!$){this.servers.set(f.name,{registration:{...f},status:"disconnected",updatedAt:vf()});return}let J=JSON.stringify($.registration.transport)!==JSON.stringify(f.transport);if($.registration={...f},$.updatedAt=vf(),J)await this.disconnectState($),$.client=void 0,$.toolCache=void 0,$.toolCacheUpdatedAt=void 0})}async unregisterServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($),this.servers.delete(f)})}async connectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.connectState($)})}async disconnectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($)})}async setServerDisabled(f,$){await this.runExclusive(f,async()=>{let J=this.requireServer(f);if(J.registration={...J.registration,disabled:$},J.updatedAt=vf(),$)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map((f)=>({name:f.registration.name,status:f.status,disabled:f.registration.disabled===!0,lastError:f.lastError,toolCount:f.toolCache?.length??0,updatedAt:f.updatedAt,metadata:f.registration.metadata})).sort((f,$)=>f.name.localeCompare($.name))}async listTools(f){let $=this.requireServer(f),J=$.toolCacheUpdatedAt??0;if($.toolCache&&vf()-J<=this.toolsCacheTtlMs)return $.toolCache;return this.refreshTools(f)}async refreshTools(f){return this.runExclusive(f,async()=>{let $=this.requireServer(f),W=await(await this.ensureConnectedClient($)).listTools(),H=E_(W);return $.toolCache=H,$.toolCacheUpdatedAt=vf(),$.updatedAt=vf(),H})}async callTool(f){return this.runExclusive(f.serverName,async()=>{let $=this.requireServer(f.serverName),J=await this.ensureConnectedClient($);return $.updatedAt=vf(),J.callTool({name:f.toolName,arguments:f.arguments,context:f.context})})}async dispose(){let f=[...this.servers.keys()];for(let $ of f)await this.unregisterServer($)}async ensureConnectedClient(f){if(await this.connectState(f),!f.client)throw Error(`MCP server "${f.registration.name}" does not have an initialized client.`);return f.client}async connectState(f){if(f.registration.disabled)throw Error(`MCP server "${f.registration.name}" is disabled and cannot be connected.`);if(f.status==="connected"&&f.client)return;f.status="connecting",f.updatedAt=vf();try{let $=f.client??await this.clientFactory(f.registration);await $.connect(),f.client=$,f.status="connected",f.lastError=void 0,f.updatedAt=vf()}catch($){throw f.status="disconnected",f.lastError=$ instanceof Error?$.message:String($),f.updatedAt=vf(),$}}async disconnectState(f){if(!f.client){f.status="disconnected",f.updatedAt=vf();return}try{await f.client.disconnect()}finally{f.status="disconnected",f.updatedAt=vf()}}requireServer(f){let $=this.servers.get(f);if(!$)throw Error(`Unknown MCP server: ${f}`);return $}async runExclusive(f,$){let J=this.operationLocks.get(f)??Promise.resolve(),W,H=new Promise((Z)=>{W=Z}),Q=J.catch(()=>{return}).then(()=>H);this.operationLocks.set(f,Q),await J.catch(()=>{return});try{return await $()}finally{if(W?.(),this.operationLocks.get(f)===Q)this.operationLocks.delete(f)}}}import{createHash as S_}from"node:crypto";var DA=128,k_=/[^a-zA-Z0-9_-]+/g,_A=8,I_=1,m_="mcp_tool";function x_(f){return S_("sha1").update(f).digest("hex").slice(0,_A)}function g_(f){return f.replace(k_,"_")}var wJ=({serverName:f,toolName:$})=>{let J=`${f}__${$}`,W=g_(J);if(W===J&&J.length<=DA)return J;let H=x_(J),Q=DA-I_-_A;return`${W.slice(0,Q)||m_}_${H}`};function G4(f){return{[(f.nameTransform??wJ)({serverName:f.serverName,toolName:f.toolName})]:{enabled:!1}}}function bJ(f){let $={};for(let J of f.toolNames)Object.assign($,G4({serverName:f.serverName,toolName:J,nameTransform:f.nameTransform}));return $}import{createTool as v_}from"@cline/shared";function u_(f,$){let J=$.description?.trim();if(J)return J;return`Execute MCP tool "${$.name}" from server "${f}".`}async function Z2(f){let $=await f.provider.listTools(f.serverName),J=f.nameTransform??wJ;return $.map((W)=>{let H=J({serverName:f.serverName,toolName:W.name});return v_({name:H,description:u_(f.serverName,W),inputSchema:W.inputSchema,timeoutMs:f.timeoutMs,retryable:f.retryable,maxRetries:f.maxRetries,execute:async(Q,Z)=>f.provider.callTool({serverName:f.serverName,toolName:W.name,arguments:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:void 0,context:Z})})})}var OA={};N(OA,{toHookConfigFileName:()=>M8,runSubprocessEvent:()=>j2,runHook:()=>A2,resolveHooksConfigSearchPaths:()=>D8,parseHookEventPayload:()=>X2,mergeAgentHooks:()=>v$,listHookConfigFiles:()=>e0,createSubprocessHooks:()=>SJ,createHookConfigFileHooks:()=>L8,createHookConfigFileExtension:()=>v1,createHookAuditHooks:()=>g1,createAgentHooksExtension:()=>m1,HookEventPayloadSchema:()=>EJ,HookEventNameSchema:()=>CJ,HookConfigFileName:()=>x1,HOOK_CONFIG_FILE_EVENT_MAP:()=>_8,HOOKS_CONFIG_DIRECTORY_NAME:()=>S6});import{HookEventNameSchema as CJ,HookEventPayloadSchema as EJ,parseHookEventPayload as X2,resolveHookSessionContext as n_}from"@cline/shared";import{z as n$}from"zod";import{spawn as c_}from"node:child_process";import{augmentNodeCommandForDebug as d_,withResolvedClineBuildEnv as r_}from"@cline/shared";function l_(f){let $=f.trim();if(!$)return{};let W=$.split(`
558
+ `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),H=W.length>0?W[W.length-1]:$;try{return{parsedJson:JSON.parse(H)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse subprocess stdout JSON"}}}function p_(f,$){let J=f instanceof Error?f:Error(String(f)),W=J,H=$.join(" ");if(W.code==="EACCES")return Error(`Failed to execute hook command "${H}" (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 "${H}": ${J.message}`)}async function i_(f,$){let J=f.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((W,H)=>{let Q=(Z)=>{J.off("error",Q);let j=Z.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){W();return}H(Z)};J.once("error",Q),J.end($,(Z)=>{if(J.off("error",Q),Z){let j=Z.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){W();return}H(Z);return}W()})})}async function j2(f,$){let J=d_($.command,{env:$.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!$.detached,H=c_(J[0],J.slice(1),{cwd:$.cwd,env:r_($.env),stdio:W?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W}),Q=new Promise((Y)=>{H.once("spawn",()=>{try{$.onSpawn?.({command:J,pid:H.pid??void 0,detached:W})}catch{}Y()})}),Z=new Promise((Y,V)=>{H.once("error",(R)=>{V(p_(R,J))})});if(await i_(H,JSON.stringify(f)),W){await Promise.race([Q,Z]),H.unref();return}if(!H.stdout||!H.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let j="",X="",A=!1,P;H.stdout.on("data",(Y)=>{j+=Y.toString()}),H.stderr.on("data",(Y)=>{X+=Y.toString()});let B=new Promise((Y)=>{if(($.timeoutMs??0)>0)P=setTimeout(()=>{A=!0,H.kill("SIGKILL")},$.timeoutMs);H.once("close",(V)=>{if(P)clearTimeout(P);let{parsedJson:R,parseError:U}=l_(j);Y({exitCode:V,stdout:j,stderr:X,parsedJson:R,parseError:U,timedOut:A})})});return await Promise.race([B,Z])}var a_=n$.object({contextModification:n$.string().optional(),cancel:n$.boolean().optional(),review:n$.boolean().optional(),errorMessage:n$.string().optional(),context:n$.string().optional(),overrideInput:n$.unknown().optional()}).passthrough();var t_=["agent","hook"];async function A2(f,$={}){let J=$.command??t_;return await j2(f,{command:J,cwd:$.cwd,env:$.env,detached:$.detached,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn})}function hA(f){return f instanceof Error?f:Error(String(f))}function s_(f){if(!f||typeof f!=="object")return;let $=a_.safeParse(f);if(!$.success)return;let J=$.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let H=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:H,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function LA(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,W]of Object.entries(f))if(typeof W==="string")$[J]=W;else $[J]=JSON.stringify(W);return $}function C0(f,$,J){let W=J.env??process.env,H=W.CLINE_USER_ID?.trim()||W.USER?.trim()||"unknown",Q=J.cwd||process.cwd();return{clineVersion:W.CLINE_VERSION?.trim()||"",hookName:f,timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:n_(J.sessionContext,{hookName:f,conversationId:$.conversationId,agentId:$.agentId,parentAgentId:$.parentAgentId}),workspaceRoots:Q?[Q]:[],workspaceInfo:J.workspaceInfo,userId:H,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function o_(f){return{name:f.name,message:f.message,stack:f.stack}}function e_(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function fM(f){return{agentId:f.snapshot.agentId,conversationId:f.snapshot.conversationId??f.snapshot.runId??f.snapshot.agentId,parentAgentId:f.snapshot.parentAgentId??null}}function $M(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function JM(f){return{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}function WM(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}async function a$(f,$){try{let J=await A2(f,{command:$.command,cwd:$.cwd,env:$.env,detached:!0,onSpawn:$.onSpawn});$.onDispatch?.({payload:f,result:J,detached:!0})}catch(J){$.onDispatchError?.(hA(J),f)}}function SJ(f={}){return{hooks:{beforeRun:async(j)=>{let X=fM(j);if((f.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let P={...C0("agent_resume",X,f),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await a$(P,f)}else{let P={...C0("agent_start",X,f),hookName:"agent_start",taskStart:{taskMetadata:{}}};await a$(P,f)}return},beforeTool:async(j)=>{let X={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},A={...C0("tool_call",X,f),hookName:"tool_call",iteration:j.snapshot.iteration,tool_call:{id:j.toolCall.toolCallId,name:j.toolCall.toolName,input:j.input},preToolUse:{toolName:j.toolCall.toolName,parameters:LA(j.input)}};try{let P=await A2(A,{command:f.command,cwd:f.cwd,env:f.env,detached:!1,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn});if(f.onDispatch?.({payload:A,result:P,detached:!1}),P?.timedOut)throw Error("tool_call hook command timed out");if(P?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${P.parseError}`);return WM(s_(P?.parsedJson))}catch(P){f.onDispatchError?.(hA(P),A);return}},afterTool:async(j)=>{let X=JM(j),A={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},P={...C0("tool_result",A,f),hookName:"tool_result",iteration:j.snapshot.iteration,tool_result:X,postToolUse:{toolName:X.name,parameters:LA(X.input),result:typeof X.output==="string"?X.output:JSON.stringify(X.output),success:!X.error,executionTimeMs:X.durationMs}};await a$(P,f);return},afterRun:async({snapshot:j,result:X})=>{let A={agentId:j.agentId,conversationId:j.conversationId??j.runId??j.agentId,parentAgentId:j.parentAgentId??null};if(X.status==="completed"){let Y={...C0("agent_end",A,f),hookName:"agent_end",iteration:X.iterations,turn:{outputText:X.outputText,status:X.status},taskComplete:{taskMetadata:{}}};await a$(Y,f);return}let P=X.status==="aborted"||e_(X.error?.message)?"agent_abort":"agent_error",B=P==="agent_error"?{...C0(P,A,f),hookName:P,iteration:X.iterations,error:o_(X.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...C0(P,A,f),hookName:P,reason:X.error?.message,taskCancel:{taskMetadata:{}}};await a$(B,f)},onEvent:async(j)=>{if(j.type!=="message-added"||j.message.role!=="user")return;let X={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},A={...C0("prompt_submit",X,f),hookName:"prompt_submit",userPromptSubmit:{prompt:$M(j.message.content),attachments:[]}};await a$(A,f)}},shutdown:async({agentId:j,conversationId:X,parentAgentId:A,reason:P})=>{let B={...C0("session_shutdown",{agentId:j,conversationId:X,parentAgentId:A},f),hookName:"session_shutdown",reason:P};await a$(B,f)}}}Y9();var NA={};N(NA,{registerRemoteConfigSessionBlobUpload:()=>mJ,readRemoteConfigSessionBlobUploadMetadata:()=>V9,prepareRemoteConfigCoreIntegration:()=>F9,createRemoteConfigSessionMessagesArtifactUploader:()=>R9,buildRemoteConfigSessionBlobUploadMetadata:()=>kJ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>IJ});import{buildRemoteConfigSessionBlobUploadMetadata as kJ,clearRemoteConfigSessionBlobUpload as HM,createClineTelemetryServiceConfig as QM,createSessionId as ZM,createRemoteConfigSessionMessagesArtifactUploader as jM,prepareRemoteConfigRuntime as XM,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as IJ,readRemoteConfigSessionBlobUploadMetadata as V9,registerRemoteConfigSessionBlobUpload as mJ}from"@cline/shared";function AM(f,$){let J=f.telemetry||$.telemetryService?{...$.telemetryService??{},...f.telemetry??{}}:void 0;if(!J)return;return T0(QM(J)).telemetry}function R9(){let f=jM();return{async uploadMessagesFile($){await f.uploadMessagesFile($)}}}async function F9(f){let $=await XM(f),J=AM($,f),W=[$.pluginDefinition],H=$.claims?.subject,Q=kJ($.bundle?.remoteConfig,H),Z;return{prepared:$,extensions:W,telemetry:J,applyToStartSessionInput(j){let X=j.config.extensions??[],A=j.config.telemetry,P=Q?j.config.sessionId?.trim()||ZM():j.config.sessionId;if(P&&Q)Z=P;let B=P&&Q?mJ(P,$.bundle?.remoteConfig,H):void 0,Y=B?{...j.sessionMetadata??{},[IJ]:B}:j.sessionMetadata;return{...j,...Y?{sessionMetadata:Y}:{},config:{...j.config,...P?{sessionId:P}:{},extensions:[...X,...W],telemetry:J??A}}},async dispose(){if(Z)HM(Z)}}}var IA={};N(IA,{createTeamName:()=>xJ,DefaultRuntimeBuilder:()=>Y2});import{hasRuntimeConfigExtension as MM}from"@cline/shared";import{nanoid as LM}from"nanoid";G0();var SA={};N(SA,{createLocalTeamStore:()=>G9,SqliteTeamStore:()=>t$,FileTeamStore:()=>T4});import{appendFileSync as PM,existsSync as P2,mkdirSync as qA,readdirSync as BM,readFileSync as wA,renameSync as YM,writeFileSync as VM}from"node:fs";import{join as K9}from"node:path";import{resolveTeamDataDir as RM}from"@cline/shared/storage";function bA(){return new Date().toISOString()}function y9(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function CA(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class T4{teamDirPath;constructor(f={}){this.teamDirPath=f.teamDir??RM()}init(){this.ensureTeamDir()}listTeamNames(){if(!P2(this.teamDirPath))return[];return BM(this.teamDirPath,{withFileTypes:!0}).filter((f)=>f.isDirectory()).filter((f)=>P2(this.statePath(f.name))).map((f)=>f.name).sort()}readState(f){let $=this.readEnvelope(f);return $?.teamState?CA($.teamState):void 0}readHistory(f,$=200){let J=this.historyPath(f);if(!P2(J))return[];return wA(J,"utf8").split(`
559
+ `).map((W)=>W.trim()).filter(Boolean).map((W)=>{try{return JSON.parse(W)}catch{return}}).filter((W)=>W!==void 0).reverse().slice(0,$)}loadRuntime(f){let $=this.readEnvelope(f);return{state:$?.teamState?CA($.teamState):void 0,teammates:$?.teammates??[],interruptedRunIds:[]}}handleTeamEvent(f,$){this.ensureTeamSubdir(f),PM(this.historyPath(f),`${JSON.stringify({ts:bA(),eventType:$.type,payload:$})}
560
+ `,"utf8")}persistRuntime(f,$,J){this.ensureTeamSubdir(f);let W={version:1,updatedAt:bA(),teamState:$,teammates:J},H=this.statePath(f),Q=`${H}.tmp`;VM(Q,`${JSON.stringify(W,null,2)}
561
+ `,"utf8"),YM(Q,H)}markInProgressRunsInterrupted(f,$){let J=this.readEnvelope(f);if(!J?.teamState?.runs?.length)return[];let W=J.teamState.runs.filter((Q)=>Q.status==="queued"||Q.status==="running").map((Q)=>Q.id);if(W.length===0)return[];let H=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((Q)=>Q.status==="queued"||Q.status==="running"?{...Q,status:"interrupted",error:$,endedAt:H}:Q)},this.persistRuntime(f,J.teamState,J.teammates),W}ensureTeamDir(){if(!P2(this.teamDirPath))qA(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir(f){let $=K9(this.ensureTeamDir(),y9(f));if(!P2($))qA($,{recursive:!0});return $}statePath(f){return K9(this.ensureTeamDir(),y9(f),"state.json")}historyPath(f){return K9(this.ensureTeamDir(),y9(f),"task-history.jsonl")}readEnvelope(f){let $=this.statePath(f);if(!P2($))return;try{let J=JSON.parse(wA($,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as FM,mkdirSync as KM}from"node:fs";import{join as yM}from"node:path";import{safeJsonParse as EA}from"@cline/shared";import{loadSqliteDb as UM,nowIso as U9}from"@cline/shared/db";import{resolveDbDataDir as GM}from"@cline/shared/storage";function TM(){return GM()}function B2(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function DM(f){let $=EA(f);if(!Array.isArray($))return[];let J=[];for(let W of $){if(!W||typeof W!=="object")continue;let H=W,Q=H.agentId,Z=H.rolePrompt;if(typeof Q!=="string"||!Q.trim())continue;if(typeof Z!=="string"||!Z.trim())continue;let j={agentId:Q.trim(),rolePrompt:Z};if(typeof H.modelId==="string"&&H.modelId.trim())j.modelId=H.modelId.trim();if(typeof H.maxIterations==="number"&&Number.isFinite(H.maxIterations))j.maxIterations=Math.max(1,Math.floor(H.maxIterations));J.push(j)}return J}function _M(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class t${teamDirPath;db;constructor(f={}){this.teamDirPath=f.teamDir??TM()}init(){this.getRawDb()}ensureTeamDir(){if(!FM(this.teamDirPath))KM(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return yM(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let f=UM(this.dbPath());return this.ensureSchema(f),this.db=f,f}ensureSchema(f){if(f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec(`
562
562
  CREATE TABLE IF NOT EXISTS team_store_schema_version (
563
563
  lock INTEGER PRIMARY KEY CHECK (lock = 1),
564
564
  version INTEGER NOT NULL
@@ -642,13 +642,13 @@ ${W}`,f.config.mode)}function j4(f,$){return LT(f,$==="plan"?"plan":$==="yolo"?"
642
642
  version INTEGER NOT NULL DEFAULT 1,
643
643
  PRIMARY KEY(team_name, fragment_id)
644
644
  );
645
- `)}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}withTransaction(f){let $=this.getRawDb();$.exec("BEGIN IMMEDIATE;");try{f(),$.exec("COMMIT;")}catch(J){try{$.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map((f)=>f.team_name)}readState(f){let $=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[P2(f)]);if(!$)return;let J=XX($.state_json);if(!J)return;try{return xD(J)}catch{return}}readHistory(f,$=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[P2(f),$]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime(f){let $=P2(f),J=this.readState($),H=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[$]),W=H?ID(H.teammates_json):[];return{state:J,teammates:W,interruptedRunIds:[]}}appendTeamEvent(f,$,J,H){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
646
- VALUES (?, ?, ?, ?, NULL, ?)`,[P2(f),P9(),$,JSON.stringify(J),H??null])}persistRuntime(f,$,J){let H=P2(f),W=P9();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
645
+ `)}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}withTransaction(f){let $=this.getRawDb();$.exec("BEGIN IMMEDIATE;");try{f(),$.exec("COMMIT;")}catch(J){try{$.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map((f)=>f.team_name)}readState(f){let $=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[B2(f)]);if(!$)return;let J=EA($.state_json);if(!J)return;try{return _M(J)}catch{return}}readHistory(f,$=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[B2(f),$]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime(f){let $=B2(f),J=this.readState($),W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[$]),H=W?DM(W.teammates_json):[];return{state:J,teammates:H,interruptedRunIds:[]}}appendTeamEvent(f,$,J,W){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
646
+ VALUES (?, ?, ?, ?, NULL, ?)`,[B2(f),U9(),$,JSON.stringify(J),W??null])}persistRuntime(f,$,J){let W=B2(f),H=U9();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
647
647
  VALUES (?, ?, ?, ?)
648
648
  ON CONFLICT(team_name) DO UPDATE SET
649
649
  state_json = excluded.state_json,
650
650
  teammates_json = excluded.teammates_json,
651
- updated_at = excluded.updated_at`,[H,JSON.stringify($),JSON.stringify(J),W]);for(let Q of $.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
651
+ updated_at = excluded.updated_at`,[W,JSON.stringify($),JSON.stringify(J),H]);for(let Q of $.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
652
652
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
653
653
  ON CONFLICT(team_name, task_id) DO UPDATE SET
654
654
  title = excluded.title,
@@ -658,7 +658,7 @@ ${W}`,f.config.mode)}function j4(f,$){return LT(f,$==="plan"?"plan":$==="yolo"?"
658
658
  depends_on_json = excluded.depends_on_json,
659
659
  summary = excluded.summary,
660
660
  version = team_tasks.version + 1,
661
- updated_at = excluded.updated_at`,[H,Q.id,Q.title,Q.description,Q.status,Q.assignee??null,JSON.stringify(Q.dependsOn??[]),Q.summary??null,Q.updatedAt.toISOString()]);for(let Q of $.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
661
+ updated_at = excluded.updated_at`,[W,Q.id,Q.title,Q.description,Q.status,Q.assignee??null,JSON.stringify(Q.dependsOn??[]),Q.summary??null,Q.updatedAt.toISOString()]);for(let Q of $.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
662
662
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
663
663
  ON CONFLICT(team_name, run_id) DO UPDATE SET
664
664
  agent_id = excluded.agent_id,
@@ -670,14 +670,14 @@ ${W}`,f.config.mode)}function j4(f,$){return LT(f,$==="plan"?"plan":$==="yolo"?"
670
670
  error = excluded.error,
671
671
  lease_owner = excluded.lease_owner,
672
672
  heartbeat_at = excluded.heartbeat_at,
673
- version = team_runs.version + 1`,[H,Q.id,Q.agentId,Q.taskId??null,Q.status,Q.message,Q.startedAt?Q.startedAt.toISOString():null,Q.endedAt?Q.endedAt.toISOString():null,Q.error??null,Q.leaseOwner??null,Q.heartbeatAt?Q.heartbeatAt.toISOString():null]);for(let Q of $.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
673
+ version = team_runs.version + 1`,[W,Q.id,Q.agentId,Q.taskId??null,Q.status,Q.message,Q.startedAt?Q.startedAt.toISOString():null,Q.endedAt?Q.endedAt.toISOString():null,Q.error??null,Q.leaseOwner??null,Q.heartbeatAt?Q.heartbeatAt.toISOString():null]);for(let Q of $.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
674
674
  VALUES (?, ?, ?, ?, ?, ?, 1)
675
675
  ON CONFLICT(team_name, outcome_id) DO UPDATE SET
676
676
  title = excluded.title,
677
677
  status = excluded.status,
678
678
  schema_json = excluded.schema_json,
679
679
  finalized_at = excluded.finalized_at,
680
- version = team_outcomes.version + 1`,[H,Q.id,Q.title,Q.status,JSON.stringify({requiredSections:Q.requiredSections}),Q.finalizedAt?Q.finalizedAt.toISOString():null]);for(let Q of $.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
680
+ version = team_outcomes.version + 1`,[W,Q.id,Q.title,Q.status,JSON.stringify({requiredSections:Q.requiredSections}),Q.finalizedAt?Q.finalizedAt.toISOString():null]);for(let Q of $.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
681
681
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
682
682
  ON CONFLICT(team_name, fragment_id) DO UPDATE SET
683
683
  outcome_id = excluded.outcome_id,
@@ -688,30 +688,30 @@ ${W}`,f.config.mode)}function j4(f,$){return LT(f,$==="plan"?"plan":$==="yolo"?"
688
688
  status = excluded.status,
689
689
  reviewed_by = excluded.reviewed_by,
690
690
  reviewed_at = excluded.reviewed_at,
691
- version = team_outcome_fragments.version + 1`,[H,Q.outcomeId,Q.id,Q.section,Q.sourceAgentId,Q.sourceRunId??null,Q.content,Q.status,Q.reviewedBy??null,Q.reviewedAt?Q.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted(f,$){let J=P2(f),H=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(H.length===0)return[];let W=P9();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
692
- WHERE team_name = ? AND status IN ('queued', 'running')`,[$,W,J]),H.map((Q)=>Q.run_id)}handleTeamEvent(f,$){this.appendTeamEvent(f,$.type,$)}}function X9(f={}){try{let $=new n$(f);return $.init(),$}catch{let $=new F4({teamDir:f.teamDir});return $.init(),$}}function V9(f,$){return gD(f,$)}function uD(f,$){let J=$?.["*"]??{},H=$?.[f]??{};return{...J,...H}.enabled!==!1}function cD(f,$){return f.filter((J)=>uD(J.name,$))}function YX(f,$){return R$(cD(f,$))}function IJ(){return`team-${vD(5)}`}function Y9(f,$,J,H,W,Q,Z,j){let P=bf[G0({mode:J})],X=U1($,H,J,W??K1);return YX(N$({cwd:f,...P,enableSkills:!!Z,...X,executors:{...Z?{skills:Z}:{},...j??{}}}),Q)}function dD(f){return Y9(f.cwd,f.providerId,f.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,rD,f.toolExecutors).some(($)=>$.name==="skills")}var rD=async()=>"";async function lD(f){let $=Q$();if(!$2({filePath:$}))return{tools:[]};let J=new l$({clientFactory:f2()}),H;try{H=await J2(J,{filePath:$})}catch(j){await J.dispose().catch(()=>{});let P=j instanceof Error?j.message:String(j);return f?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${P}`),{tools:[]}}let W=H.filter((j)=>j.disabled!==!0),Q=await Promise.allSettled(W.map((j)=>H2({serverName:j.name,provider:J}))),Z=[];for(let[j,P]of Q.entries())if(P.status==="fulfilled")Z.push(...P.value);else{let X=P.reason instanceof Error?P.reason.message:String(P.reason);f?.log(`[mcp] Failed to load tools from MCP server "${W[j].name}", skipping: ${X}`)}return{tools:Z,shutdown:async()=>{await J.dispose()}}}function pD(f,$){if(!f)return;for(let J of f.getTeammateIds())try{f.shutdownTeammate(J,$)}catch{}}function iD(f){if(f===void 0)return!0;switch(f){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function nD(f){let $=bf[G0({mode:f.mode})];return{sessionId:f.sessionId||"",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",enableTools:f.enableTools!==!1,enableSpawnAgent:f.enableSpawnAgent??$.enableSpawnAgent??!0,enableAgentTeams:f.enableAgentTeams??$.enableAgentTeams??!0,disableMcpSettingsTools:f.disableMcpSettingsTools===!0,yolo:f.yolo===!0,missionLogIntervalSteps:typeof f.missionLogIntervalSteps==="number"&&Number.isFinite(f.missionLogIntervalSteps)?f.missionLogIntervalSteps:3,missionLogIntervalMs:typeof f.missionLogIntervalMs==="number"&&Number.isFinite(f.missionLogIntervalMs)?f.missionLogIntervalMs:120000}}class X2{teamRuntimeEntries=new Map;async build(f){let{config:$,hooks:J,extensions:H,logger:W,telemetry:Q,createSpawnTool:Z,onTeamRestored:j,userInstructionService:P,configExtensions:X,toolExecutors:V}=f,Y=f.onTeamEvent??(()=>{}),B=nD($),A=uf(),R=[],U=$.teamName?.trim()||IJ(),y=$.sessionId?.trim()||U,F=V9(X,"rules"),K=V9(X,"skills"),M=V9(X,"workflows"),T=F||K||M,G=!1,h=Boolean(P),z=P,u;if(!z&&T)z=H$({skills:{workspacePath:$.cwd},rules:{workspacePath:$.cwd},workflows:{workspacePath:$.cwd}});if(z)await z.start().catch(()=>{});let gf=B.enableTools&&K&&Boolean(z)&&(h||z?.hasConfiguredSkills($.skills)===!0)&&dD({cwd:$.cwd,providerId:$.providerId,mode:B.mode,modelId:$.modelId,toolRoutingRules:$.toolRoutingRules,toolPolicies:$.toolPolicies,toolExecutors:V}),a=z&&T?z.createExtension({includeRules:F,includeSkills:K,includeWorkflows:M,registerSkillsTool:gf,allowedSkillNames:$.skills}):void 0,c=a?[...H??$.extensions??[],a]:H??$.extensions;if(B.enableTools){if(R.push(...Y9($.cwd,$.providerId,B.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,V)),!B.disableMcpSettingsTools){let r=await lD($.logger);R.push(...r.tools),u=r.shutdown}}let d,t=B.enableAgentTeams?X9():void 0,pf=t?.loadRuntime(y),C=pf?.state,nf=pf?.teammates??[],vf=new Map(nf.map((r)=>[r.agentId,r])),$f=$.sessionId||U,A2,P$=[],X$=!1,o$=h1({providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey??"",baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:J,extensions:c,logger:W??$.logger,telemetry:f.telemetry??$.telemetry,workspaceMetadata:$.workspaceMetadata});if(!this.teamRuntimeEntries.has($f))this.teamRuntimeEntries.set($f,{delegatedAgentConfigProvider:o$});let R2=()=>{if(!B.enableAgentTeams)return;let r=this.teamRuntimeEntries.get($f)??{delegatedAgentConfigProvider:o$};if(this.teamRuntimeEntries.set($f,r),d=r.runtime,!d){if(d=new r$({teamName:U,leadAgentId:$.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(e)=>{if(Y(e),d&&t){if(e.type==="teammate_spawned"&&e.teammate?.rolePrompt){let X0={agentId:e.agentId,rolePrompt:e.teammate.rolePrompt,modelId:e.teammate.modelId,maxIterations:e.teammate.maxIterations};vf.set(X0.agentId,X0)}if(e.type==="teammate_shutdown"&&!iD(e.reason))vf.delete(e.agentId);t.handleTeamEvent(y,e),t.persistRuntime(y,d.exportState(),Array.from(vf.values()))}}}),C)d.hydrateState(C),X$=!0;r.runtime=d}if(!G){if(!d)return;G=!0;let e=M1({runtime:d,leadAgentId:$.sessionId||"lead",restoredFromPersistence:Boolean(C),restoredTeammates:nf,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(X0)=>{P$=X0,A2?.addTools(X0)},createBaseTools:B.enableTools?()=>Y9($.cwd,$.providerId,B.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,V):void 0,teammateConfigProvider:o$});if(X$)d.recoverActiveRuns("runtime_recovered");if(e.restoredFromPersistence)j?.();R.push(...e.tools)}return d};if(B.enableSpawnAgent&&Z){let r=Z();R.push({...r,execute:async(e,X0)=>{return R2(),r.execute(e,X0)}})}if(B.enableAgentTeams)R2();let z4=YX(R,$.toolPolicies),WH=z4.some((r)=>r.name===ff.SUBMIT_AND_EXIT&&r.lifecycle?.completesRun===!0),e$=B.enableAgentTeams?()=>{let r=this.teamRuntimeEntries.get($f)?.runtime;if(!r)return;let e=r.listTasks(),X0=e.some((N0)=>N0.status==="in_progress"||N0.status==="pending"),X3=r.listRuns({}),QY=X3.some((N0)=>N0.status==="running"||N0.status==="queued");if(X0||QY){let N0=e.filter((_f)=>_f.status==="in_progress"||_f.status==="pending").map((_f)=>`${_f.id} (${_f.status}): ${_f.title}`).join(", "),V3=X3.filter((_f)=>_f.status==="running"||_f.status==="queued").map((_f)=>`${_f.id} (${_f.status})`).join(", "),QH=[];if(N0)QH.push(`Unfinished tasks: ${N0}`);if(V3)QH.push(`Active runs: ${V3}`);return`[SYSTEM] You still have team obligations. ${QH.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,F2=WH?{requireCompletionTool:!0,...e$?{completionGuard:e$}:{}}:e$?{completionGuard:e$}:void 0;return{tools:z4,logger:W??$.logger,telemetry:Q??$.telemetry,teamRuntime:d,teamRestoredFromPersistence:Boolean(C),delegatedAgentConfigProvider:this.teamRuntimeEntries.get($f)?.delegatedAgentConfigProvider??o$,extensions:c,completionPolicy:F2,registerLeadAgent:(r)=>{if(A2=r,P$.length>0)r.addTools(R$(P$,[...A]))},shutdown:async(r)=>{if(pD(d,r),this.teamRuntimeEntries.delete($f),await u?.(),!h)z?.stop()}}}}var RX={};N(RX,{requestDesktopToolApproval:()=>A9});import{mkdir as aD,readFile as tD,unlink as sD,writeFile as oD}from"node:fs/promises";import{join as AX}from"node:path";function eD(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function fM(f){return new Promise(($)=>setTimeout($,f))}async function B9(f){try{await sD(f)}catch{}}async function A9(f,$={}){let J=$.approvalDir?.trim(),H=$.sessionId?.trim();if(!J||!H)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await aD(J,{recursive:!0});let W=eD(`${f.toolCallId}`),Q=AX(J,`${H}.request.${W}.json`),Z=AX(J,`${H}.decision.${W}.json`),j=$.nowIso??(()=>new Date().toISOString());await oD(Q,`${JSON.stringify({requestId:W,sessionId:H,createdAt:j(),toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,iteration:f.iteration,agentId:f.agentId,conversationId:f.conversationId},null,2)}
693
- `,"utf8");let P=$.timeoutMs??300000,X=$.pollIntervalMs??200,V=Date.now();while(Date.now()-V<P){try{let Y=await tD(Z,"utf8"),B=JSON.parse(Y),A={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([B9(Z),B9(Q)]),A}catch{}await fM(X)}return await B9(Q),{approved:!1,reason:"Tool approval request timed out"}}F0();var wX={};N(wX,{updateLocalProvider:()=>dJ,saveLocalProviderSettings:()=>T9,saveLocalProviderOAuthCredentials:()=>L9,resolveLocalClineAuthToken:()=>z9,refreshProviderModelsFromSource:()=>D9,normalizeOAuthProvider:()=>M9,loginLocalProvider:()=>_9,listLocalProviders:()=>G9,getProviderConfigFields:()=>O9,getLocalProviderModels:()=>h9,ensureCustomProvidersLoaded:()=>cJ,deleteLocalProvider:()=>rJ,addLocalProvider:()=>U9});import*as Zf from"@cline/llms";import{isOAuthProviderId as DM}from"@cline/shared";import{existsSync as $M,mkdirSync as JM,readFileSync as HM,writeFileSync as WM}from"node:fs";import{mkdir as QM,readFile as ZM,writeFile as jM}from"node:fs/promises";import{dirname as R9,join as PM}from"node:path";import*as Tf from"@cline/llms";import{ModelCapabilitySchema as XM,ProviderCapabilitySchema as VM,ProviderClientSchema as YM,ProviderProtocolSchema as BM}from"@cline/shared";import{z as p}from"zod";var AM=p.object({id:p.string().optional(),name:p.string().optional(),capabilities:p.array(XM).optional(),supportsVision:p.boolean().optional(),supportsAttachments:p.boolean().optional(),supportsReasoning:p.boolean().optional()}).passthrough(),RM=p.object({name:p.string(),baseUrl:p.string(),defaultModelId:p.string().optional(),protocol:BM.optional(),client:YM.optional(),capabilities:p.array(VM).optional(),modelsSourceUrl:p.string().optional()}).passthrough(),FX=p.object({provider:RM.optional(),models:p.record(p.string(),AM).optional()}).passthrough(),yX=p.object({version:p.literal(1),providers:p.record(p.string(),FX)}),FM=p.object({version:p.literal(1),providers:p.record(p.string(),p.unknown())}),xJ=new Set;function KX(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function a$(f){return PM(R9(f.getFilePath()),"models.json")}function gJ(){return{version:1,providers:{}}}function UX(f){let $=FM.safeParse(f);if(!$.success)return gJ();let J={};for(let[H,W]of Object.entries($.data.providers)){let Q=FX.safeParse(W);if(Q.success)J[H]=Q.data}return{version:1,providers:J}}function F9(f){if(!$M(f))return gJ();try{let $=HM(f,"utf8");return UX(JSON.parse($))}catch{}return gJ()}async function V2(f){try{let $=await ZM(f,"utf8");return UX(JSON.parse($))}catch{}return gJ()}function GX(f,$){JM(R9(f),{recursive:!0});let J=yX.parse($);WM(f,`${JSON.stringify(J,null,2)}
694
- `,"utf8")}async function vJ(f,$){await QM(R9(f),{recursive:!0});let J=yX.parse($);await jM(f,`${JSON.stringify(J,null,2)}
695
- `,"utf8")}function hX(f,$){return{id:f,name:$.name??f,supportsAttachments:$.capabilities?.includes("files"),supportsVision:$.capabilities?.includes("images"),supportsReasoning:$.capabilities?.includes("reasoning")||$.thinkingConfig!=null}}function TX(f){if(!f||f.length===0)return;let $=new Set;if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("tools"))$.add("tools");return $.size>0?[...$]:void 0}function DX(f){let $=new Set;if(!f||f.length===0)return[...$];if(f.includes("streaming"))$.add("streaming");if(f.includes("tools"))$.add("tools");if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("vision"))$.add("images"),$.add("files");return[...$]}function yM(f){return f!=null&&typeof f.name==="string"&&typeof f.baseUrl==="string"}function MX(f,$){return f??$??"openai-chat"}function _X(f,$,J){return f??J??($==="openai-responses"?"openai":"openai-compatible")}function KM(f,$){let J=new Set($?.capabilities??[]);if($?.supportsVision)J.add("images");if($?.supportsAttachments)J.add("files");if($?.supportsReasoning)J.add("reasoning");return{id:f,name:$?.name??f,capabilities:J.size>0?[...J]:void 0}}function UM(f,$){for(let[J,H]of Object.entries($??{})){let W=H.id?.trim()||J.trim();if(!W)continue;Tf.registerModel(f,W,KM(W,H))}}function GM(f,$,J){return{...$??{},id:f,name:$?.name??f,capabilities:$?.capabilities??J}}function hM(f){return Object.assign({},...Tf.resolveProviderModelCatalogKeys(f).map((J)=>Tf.getGeneratedModelsForProvider(J)))}function TM(f){let $=f.provider.trim();if(!$||Tf.isBuiltInProviderId($))return;let J=f.baseUrl?.trim();if(!J)return;let H=Tf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=hM($),Q=DX(f.capabilities),Z=Q.length>0?Q:void 0,j=f.model?.trim(),P={...W,...H?.models??{}};if(j)P[j]=GM(j,P[j],Z);let X=Object.keys(P).filter(Boolean),V=j||X[0];if(!V)return;let Y=MX(f.protocol,H?.provider.protocol),B=_X(f.client,Y,H?.provider.client);Tf.registerProvider({provider:{id:$,name:H?.provider.name??KX($),description:H?.provider.description,protocol:Y,client:B,baseUrl:J,modelsSourceUrl:H?.provider.modelsSourceUrl,defaultModelId:V,capabilities:TX(f.capabilities)??H?.provider.capabilities,source:"file"},models:P})}function uJ(f){for(let $ of Object.values(f.providers))TM($.settings)}function y4(f,$){let J=$.models??{};if(!yM($.provider)){UM(f,J);return}let H=DX($.provider.capabilities),W=Object.entries(J).map(([X,V])=>({id:V.id?.trim()||X.trim(),model:V})).filter(({id:X})=>X.length>0),Q=$.provider.defaultModelId?.trim()||W[0]?.id||"default",Z=MX($.provider.protocol,void 0),j=_X($.provider.client,Z,void 0),P=Object.fromEntries(W.map(({id:X,model:V})=>[X,{id:X,name:V.name??X,capabilities:H.length>0?H:void 0,status:"active"}]));Tf.registerProvider({provider:{id:f,name:$.provider.name.trim()||KX(f),protocol:Z,client:j,baseUrl:$.provider.baseUrl,modelsSourceUrl:$.provider.modelsSourceUrl,defaultModelId:Q,capabilities:TX($.provider.capabilities),source:"file"},models:P})}function LX(f){let $=a$(f);if(xJ.has($))return;let J=F9($);for(let[H,W]of Object.entries(J.providers))y4(H,W);xJ.add($)}async function cJ(f){let $=a$(f);if(xJ.has($))return;let J=await V2($);for(let[H,W]of Object.entries(J.providers))y4(H,W);xJ.add($)}function MM(f){return f.apiKey??f.auth?.apiKey}function _M(f){return(f.auth?.accessToken?.trim()??"").length>0}function zX(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function LM(f){let $=f.split(/\s+/).filter(Boolean);if($.length===0)return"?";if($.length===1)return $[0].slice(0,2).toUpperCase();return`${$[0][0]}${$[1][0]}`.toUpperCase()}function zM(f){let $=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let H of f)J=J*31+H.charCodeAt(0)>>>0;return $[J%$.length]}function OX(f){return Object.entries(f).sort(([$],[J])=>$.localeCompare(J)).map(([$,J])=>hX($,J))}async function OM(f,$){let J=await Zf.getModelsForProvider(f);if(!$)return J;let H=await z8(f,{loadPrivateOnAuth:!0,failOnError:!1},$);return H?.knownModels?{...J,...H.knownModels}:J}function y9(f){return[...new Set((f??[]).map(($)=>$.trim()).filter(Boolean))]}function NX(f){let $=Object.entries(f??{}).filter(([J])=>J.trim().length>0);return $.length>0?Object.fromEntries($):void 0}function K9(f,$){let J=$?.includes("vision")??!1,H=$?.includes("reasoning")??!1;return Object.fromEntries(f.map((W)=>[W,{id:W,name:W,supportsVision:J,supportsAttachments:J,supportsReasoning:H}]))}async function qX(f){if(!f.shouldRecompute)return f.fallbackModelIds??[];let $=f.modelsSourceUrl?await c6(f.modelsSourceUrl,f.providerId):[];return[...new Set([...f.explicitModels??[],...$])]}function bX(f,$){let J=f.read(),H=!1;if(J.providers[$])delete J.providers[$],H=!0;if(J.lastUsedProvider===$)delete J.lastUsedProvider,H=!0;if(H)f.write(J);Zf.unregisterProvider($)}async function U9(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let H=$.baseUrl.trim(),W=$.apiKey?.trim()??"";if(!H&&!W){let R=a$(f);if((await V2(R)).providers[J]){let y=await rJ(f,{providerId:J});return{providerId:J,settingsPath:y.settingsPath,modelsPath:y.modelsPath,modelsCount:0}}return bX(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:R,modelsCount:0}}if(Zf.hasProvider(J))throw Error(`provider "${J}" already exists`);let Q=$.name.trim();if(!Q)throw Error("name is required");if(!H)throw Error("baseUrl is required");let Z=y9($.models),j=$.modelsSourceUrl?.trim(),P=await qX({providerId:J,explicitModels:Z,modelsSourceUrl:j,shouldRecompute:!0});if(P.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let X=$.defaultModelId?.trim()&&P.includes($.defaultModelId.trim())?$.defaultModelId.trim():P[0],V=$.capabilities?.length?[...new Set($.capabilities)]:void 0,Y=NX($.headers);f.saveProviderSettings({provider:J,apiKey:W||void 0,baseUrl:H,headers:Y,timeout:$.timeoutMs,model:X,protocol:$.protocol,client:$.client},{setLastUsed:!1});let B=a$(f),A=await V2(B);return A.providers[J]={provider:{name:Q,baseUrl:H,defaultModelId:X,protocol:$.protocol,client:$.client,capabilities:V,modelsSourceUrl:j},models:K9(P,V)},await vJ(B,A),y4(J,A.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:B,modelsCount:P.length}}async function dJ(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let H=a$(f),W=await V2(H),Q=W.providers[J];if(!Q){let T=f.getProviderSettings(J);if(!T)throw Error(`provider "${J}" does not exist`);let G=$.modelsSourceUrl?.trim(),h=y9($.models)[0]??T.model?.trim();if(!h&&!G)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:$.name?.trim()||zX(J),baseUrl:$.baseUrl?.trim()??T.baseUrl?.trim()??"",defaultModelId:h,protocol:T.protocol,client:T.client,capabilities:T.capabilities},models:h?K9([h],T.capabilities):{}}}if(!Q.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let Z=$.name?.trim()??Q.provider.name.trim();if(!Z)throw Error("name is required");let j=$.baseUrl?.trim()??Q.provider.baseUrl.trim();if(!j)throw Error("baseUrl is required");let P=$.capabilities===void 0?Q.provider.capabilities:$.capabilities===null?void 0:[...new Set($.capabilities)],X=$.protocol===void 0?Q.provider.protocol:$.protocol??void 0,V=$.client===void 0?Q.provider.client:$.client??void 0,Y=y9($.models),B=$.modelsSourceUrl===void 0?Q.provider.modelsSourceUrl:$.modelsSourceUrl?.trim()||void 0,A=$.models!==void 0||$.modelsSourceUrl!==void 0&&!!B,R=Object.keys(Q.models??{}).map((T)=>T.trim()).filter(Boolean),U=await qX({providerId:J,explicitModels:Y,modelsSourceUrl:B,fallbackModelIds:R,shouldRecompute:A});if(U.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let y=$.defaultModelId===void 0?Q.provider.defaultModelId?.trim():$.defaultModelId?.trim(),F=y&&U.includes(y)?y:U[0],M={...f.getProviderSettings(J)??{},provider:J,baseUrl:j,model:F};if(X)M.protocol=X;else delete M.protocol;if(V)M.client=V;else delete M.client;if($.apiKey!==void 0){let T=$.apiKey?.trim()??"";if(T)M.apiKey=T;else delete M.apiKey}if($.headers!==void 0){let T=NX($.headers);if(T)M.headers=T;else delete M.headers}if($.timeoutMs!==void 0)if(typeof $.timeoutMs==="number")M.timeout=$.timeoutMs;else delete M.timeout;return f.saveProviderSettings(M,{setLastUsed:!1}),W.providers[J]={provider:{name:Z,baseUrl:j,defaultModelId:F,protocol:X,client:V,capabilities:P,modelsSourceUrl:B},models:K9(U,P)},await vJ(H,W),y4(J,W.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:H,modelsCount:U.length}}async function rJ(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let H=a$(f),W=await V2(H);if(!W.providers[J])throw Error(`provider "${J}" does not exist`);return delete W.providers[J],await vJ(H,W),Zf.unregisterProvider(J),bX(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:H}}async function G9(f){let $=f.read(),J=Zf.getProviderIds().sort((W,Q)=>W.localeCompare(Q));return{providers:await Promise.all(J.map(async(W)=>{let[Q,Z]=await Promise.all([Zf.getProvider(W),Zf.getModelsForProvider(W)]),j=OX(Z),P=$.providers[W]?.settings,X=Q?.name??zX(W);return{id:W,name:X,models:j.length,color:zM(W),letter:LM(X),enabled:Boolean(P),apiKey:P?MM(P):void 0,oauthAccessTokenPresent:P?_M(P):void 0,baseUrl:P?.baseUrl??Q?.baseUrl,defaultModelId:Q?.defaultModelId,protocol:P?.protocol??Q?.protocol,client:P?.client??Q?.client,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",modelList:j}})),settingsPath:f.getFilePath()}}async function h9(f,$){let J=f.trim(),H=await OM(J,$),W=OX(H);return{providerId:J,models:W}}function T9(f,$){let J=$.providerId.trim();if($.enabled===!1){let Q=f.read();if(delete Q.providers[J],Q.lastUsedProvider===J)delete Q.lastUsedProvider;return f.write(Q),{providerId:J,enabled:!1,settingsPath:f.getFilePath()}}let W={...f.getProviderSettings(J)??{},provider:J};for(let Q of["apiKey","baseUrl","model","region"])if(Object.hasOwn($,Q)&&typeof $[Q]==="string")if($[Q].trim().length===0)delete W[Q];else W[Q]=$[Q];for(let Q of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn($,Q))W[Q]=$[Q];for(let Q of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn($,Q)&&$[Q]!=null)W[Q]={...typeof W[Q]==="object"&&W[Q]!=null?W[Q]:{},...$[Q]};return f.saveProviderSettings(W,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:f.getFilePath()}}async function D9(f,$){let J=$.trim(),H=f.getProviderSettings(J),Q=Zf.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,Z=H?.baseUrl?.trim()||Q?.baseUrl?.trim(),j=d6(Z,Q?.baseUrl,Q?.modelsSourceUrl);if(!H||!Q||!Z||!j)return{providerId:J,refreshed:!1};let P=await dJ(f,{providerId:J,name:Q.name,baseUrl:Z,apiKey:H.apiKey,headers:H.headers??null,timeoutMs:H.timeout??null,modelsSourceUrl:j,protocol:H.protocol??Q.protocol??null,client:H.client??Q.client??null,capabilities:H.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:P.modelsCount}}function M9(f){let $=f.trim().toLowerCase();if($==="codex"||$==="openai-codex")return"openai-codex";if($==="cline"||$==="oca")return $;throw Error(`provider "${f}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function NM(f,$){if(f==="cline")return $.access.startsWith("workos:")?$.access:`workos:${$.access}`;return $.access}async function _9(f,$,J){let H=E8({onPrompt:async(W)=>W.defaultValue??"",openUrl:J,onOpenUrlError:({error:W})=>{throw W instanceof Error?W:Error(String(W))}});if(f==="cline")return r1({apiBaseUrl:$?.baseUrl?.trim()||"https://api.cline.bot",useWorkOSDeviceAuth:!0,callbacks:H});if(f==="oca")return x1({mode:$?.oca?.mode,callbacks:H});return l1(H)}function L9(f,$,J,H){let W={...J?.auth??{},accessToken:NM($,H),refreshToken:H.refresh,accountId:H.accountId,expiresAt:H.expires},Q={...J??{provider:$},provider:$,auth:W};return f.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function z9(f){let $=f?.auth?.accessToken?.trim()||f?.apiKey?.trim();return $&&$.length>0?$:void 0}var qM=new Set(["ollama","lmstudio","litellm"]);function bM(f,$){if(!$?.provider.baseUrl)return!1;if($.provider.source!=="system")return!0;return qM.has(f)}function O9(f){let $=Zf.normalizeProviderId(f);if(DM($))return{providerId:$,authMethod:"oauth",fields:{}};let J=Zf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],H=J?.provider.baseUrl,W={apiKey:{}};if(bM($,J))W.baseUrl={defaultValue:H};return{providerId:$,authMethod:"api-key",fields:W}}var mX={};N(mX,{resolveLegacyClineAuth:()=>kX,migrateLegacyProviderSettings:()=>K4});import{existsSync as wM,readFileSync as CM}from"node:fs";import{dirname as EM,join as N9}from"node:path";import*as EX from"@cline/llms";import{resolveClineDataDir as SM}from"@cline/shared/storage";var SX="openai";function kX(f){let $=f?.trim();if(!$)return;try{let J=JSON.parse($);if(!J)return;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:J.expiresAt,accountId:J.userInfo?.id}}catch{return}}function E(f){let $=f?.trim();return $?$:void 0}function CX(f){if(!wM(f))return;try{let $=CM(f,"utf8"),J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function kM(f){let $=f.dataDir??SM(),J=f.globalStatePath??N9($,"globalState.json"),H=f.secretsPath??N9($,"secrets.json"),W=CX(J),Q=CX(H);if(!W&&!Q)return;return{globalState:W??{},secrets:Q??{}}}function mM(f){try{let J=new URL(f).hostname.toLowerCase();return J==="api.openai.com"||J.endsWith(".openai.azure.com")||J.endsWith(".services.ai.azure.com")}catch{return!1}}function IM(f){let $=E(f.openAiBaseUrl);if(!$)return!1;if(f.azureApiVersion||f.azureIdentity)return!1;return!mM($)}function q9(f,$){if(f==="openai"&&IM($))return SX;return f}function xM(f,$,J,H){let W=J==="plan"?"planMode":"actMode",Q=$===H?E(J==="plan"?f.planModeApiModelId:f.actModeApiModelId):void 0,j={openrouter:`${W}OpenRouterModelId`,cline:`${W}ClineModelId`,openai:`${W}OpenAiModelId`,ollama:`${W}OllamaModelId`,lmstudio:`${W}LmStudioModelId`,litellm:`${W}LiteLlmModelId`,requesty:`${W}RequestyModelId`,together:`${W}TogetherModelId`,fireworks:`${W}FireworksModelId`,sapaicore:`${W}SapAiCoreModelId`,groq:`${W}GroqModelId`,baseten:`${W}BasetenModelId`,huggingface:`${W}HuggingFaceModelId`,"huawei-cloud-maas":`${W}HuaweiCloudMaasModelId`,oca:`${W}OcaModelId`,aihubmix:`${W}AihubmixModelId`,hicap:`${W}HicapModelId`,nousResearch:`${W}NousResearchModelId`,"vercel-ai-gateway":`${W}VercelAiGatewayModelId`}[$];return(j?E(typeof f[j]==="string"?f[j]:void 0):void 0)??Q}function gM(f,$,J){let H=J==="plan"?f.planModeReasoningEffort:f.actModeReasoningEffort,W=J==="plan"?f.geminiPlanModeThinkingLevel:f.geminiActModeThinkingLevel,Q=J==="plan"?f.planModeThinkingBudgetTokens:f.actModeThinkingBudgetTokens,Z=($==="gemini"?W:void 0)??H,j=Z==="none"||Z==="low"||Z==="medium"||Z==="high"?Z:void 0,P=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!j&&P===void 0)return;return{...j?{effort:j}:{},...P!==void 0?{budgetTokens:P}:{}}}function vM(f){let $=f["openai-codex-oauth-credentials"];if(!$)return;try{let J=JSON.parse($),H=E(J.access_token),W=E(J.refresh_token),Q=E(J.accountId);if(!H&&!W&&!Q)return;return{...H?{apiKey:H}:{},auth:{...H?{accessToken:H}:{},...W?{refreshToken:W}:{},...Q?{accountId:Q}:{}}}}catch{return}}function uM(f){let $=EX.getGeneratedModelsForProvider(f);return Object.keys($)[0]??void 0}function cM(f,$,J,H){let W=q9(f,$),Q=E(H==="plan"?$.planModeApiProvider:$.actModeApiProvider),Z=xM($,f,H,Q)??uM(W),j=gM($,W,H),P=typeof $.requestTimeoutMs==="number"&&Number.isInteger($.requestTimeoutMs)&&$.requestTimeoutMs>0?$.requestTimeoutMs:void 0,X={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey,sapaicore:J.sapAiCoreClientId},V={};if(f==="openai-codex")Object.assign(V,vM(J));if(f==="cline")try{let F=E(J["cline:clineAccountId"]);if(F)V.auth={...V.auth??{},...kX(F)}}catch{}if(f==="openai"&&$.openAiHeaders)V.headers=$.openAiHeaders;if(f==="bedrock")V.aws={accessKey:E(J.awsAccessKey),secretKey:E(J.awsSecretKey),sessionToken:E(J.awsSessionToken),region:E($.awsRegion),authentication:$.awsAuthentication,profile:$.awsUseProfile?E($.awsProfile):void 0,usePromptCache:$.awsBedrockUsePromptCache,useCrossRegionInference:$.awsUseCrossRegionInference,useGlobalInference:$.awsUseGlobalInference,endpoint:E($.awsBedrockEndpoint),customModelBaseId:E(H==="plan"?$.planModeAwsBedrockCustomModelBaseId:$.actModeAwsBedrockCustomModelBaseId)};if(f==="vertex")V.gcp={projectId:E($.vertexProjectId),region:E($.vertexRegion)};if(f==="openai"&&($.azureApiVersion||$.azureIdentity!==void 0))V.azure={apiVersion:E($.azureApiVersion),useIdentity:$.azureIdentity};if(f==="sapaicore")V.sap={clientId:E(J.sapAiCoreClientId),clientSecret:E(J.sapAiCoreClientSecret),tokenUrl:E($.sapAiCoreTokenUrl),resourceGroup:E($.sapAiResourceGroup),deploymentId:E(H==="plan"?$.planModeSapAiCoreDeploymentId:$.actModeSapAiCoreDeploymentId),useOrchestrationMode:$.sapAiCoreUseOrchestrationMode};if(f==="oca"){V.oca={mode:$.ocaMode};let F=E(J.ocaRefreshToken);if(F)V.auth={...V.auth??{},refreshToken:F}}if(f==="qwen")V.apiLine=$.qwenApiLine;if(f==="moonshot")V.apiLine=$.moonshotApiLine;if(f==="zai")V.apiLine=$.zaiApiLine;if(f==="minimax")V.apiLine=$.minimaxApiLine;let Y={anthropic:$.anthropicBaseUrl,openai:$.openAiBaseUrl,ollama:$.ollamaBaseUrl,lmstudio:$.lmStudioBaseUrl,litellm:$.liteLlmBaseUrl,gemini:$.geminiBaseUrl,requesty:$.requestyBaseUrl,asksage:$.asksageApiUrl,dify:$.difyBaseUrl,oca:$.ocaBaseUrl,aihubmix:$.aihubmixBaseUrl,sapaicore:$.sapAiCoreBaseUrl},B=E(X[f]),A=E(Y[f]),R={provider:W,...B?{apiKey:B}:{},...Z?{model:Z}:{},...A?{baseUrl:A}:{},...j?{reasoning:j}:{},...P?{timeout:P}:{},...V},U=q8.safeParse(R);if(!U.success)return;return Object.keys(R).filter((F)=>F!=="provider").length>0?U.data:void 0}function dM(f,$){if(f!==SX)return;if(!$.baseUrl||!$.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:$.baseUrl,defaultModelId:$.model},models:{[$.model]:{id:$.model,name:$.model}}}}function rM(f,$){let J=new Set;for(let H of[f.actModeApiProvider,f.planModeApiProvider]){let W=E(H);if(W)J.add(W)}if(E($.apiKey))J.add("anthropic");if(E($.openRouterApiKey))J.add("openrouter");if(E($.openAiApiKey))J.add("openai");if(E($.openAiNativeApiKey))J.add("openai-native");if(E($["openai-codex-oauth-credentials"]))J.add("openai-codex");if(E($.geminiApiKey))J.add("gemini");if(E($.ollamaApiKey))J.add("ollama");if(E($.awsAccessKey)||E($.awsBedrockApiKey))J.add("bedrock");if(E(f.vertexProjectId)||E(f.vertexRegion))J.add("vertex");if(E($.clineApiKey))J.add("cline");if(E($.ocaApiKey))J.add("oca");return J}function K4(f){let $=f.providerSettingsManager.read(),J=kM(f);if(!J)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let{globalState:H,secrets:W}=J,Q=H.mode==="plan"?"plan":"act",Z=rM(H,W),j=$$();j.providers={...$.providers},j.lastUsedProvider=$.lastUsedProvider;let P=new Date().toISOString(),X=0,V=N9(EM(f.providerSettingsManager.getFilePath()),"models.json"),Y=F9(V),B=0;for(let U of Z){let y=q9(U,H);if(j.providers[y])continue;let F=cM(U,H,W,Q);if(!F)continue;j.providers[y]={settings:F,updatedAt:P,tokenSource:"migration"},X+=1;let K=dM(y,F);if(K&&!Y.providers[y])Y.providers[y]=K,B+=1}if(X===0&&B===0)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let A=E(Q==="plan"?H.planModeApiProvider:H.actModeApiProvider),R=A?q9(A,H):void 0;if(j.lastUsedProvider=$.lastUsedProvider??(R&&j.providers[R]?R:Object.keys(j.providers)[0]),f.providerSettingsManager.write(j),B>0)GX(V,Y);return{migrated:X>0||B>0,providerCount:Object.keys(j.providers).length,lastUsedProvider:j.lastUsedProvider}}Kf();o4();var gX={};N(gX,{trimMessagesToCheckpoint:()=>xX,trimMessagesBeforeCheckpoint:()=>w9,readSessionCheckpointHistory:()=>U4,createRestoredCheckpointMetadata:()=>b9,createCheckpointRestorePlan:()=>C9,applyCheckpointToWorktree:()=>E9});import{execFile as lM}from"node:child_process";import{promisify as pM}from"node:util";var Y2=pM(lM);function U4(f){let $=f?.metadata?.checkpoint&&typeof f.metadata.checkpoint==="object"&&!Array.isArray(f.metadata.checkpoint)?f.metadata.checkpoint:void 0;return(Array.isArray($?.history)?$.history:[]).filter((H)=>!!H&&typeof H==="object"&&!Array.isArray(H)).flatMap((H)=>{let W=String(H.ref??"").trim(),Q=Number(H.createdAt??0),Z=Number(H.runCount??0);if(W.length===0||!Number.isFinite(Q)||!Number.isInteger(Z)||Z<1)return[];let j=H.kind==="stash"||H.kind==="commit"?H.kind:void 0;return[{ref:W,createdAt:Q,runCount:Z,...j?{kind:j}:{}}]})}function b9(f,$){let J=U4(f).filter((W)=>W.runCount<=$),H=J.at(-1);return H?{latest:H,history:J}:void 0}function iM(f,$){return f.reduce((J,H)=>{if(H.runCount>$)return J;if(!J||H.runCount>J.runCount)return H;return J},void 0)}function IX(f,$){let J=0;for(let H=0;H<f.length;H+=1){let W=f[H];if(W?.role!=="user")continue;if(("metadata"in W&&W.metadata&&typeof W.metadata==="object"?W.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===$)return H}throw Error(`Could not find user message for checkpoint run ${$}`)}function xX(f,$){let J=IX(f,$);return f.slice(0,J+1)}function w9(f,$){let J=IX(f,$);return f.slice(0,J)}function C9(f){let $=f.checkpointRunCount;if(!Number.isInteger($)||$<1)throw Error("checkpointRunCount must be a positive integer");let J=iM(U4(f.session),$);if(!J)throw Error(`No checkpoint found at or before run ${$} in session ${f.session.sessionId}`);let H=(f.cwd?.trim()||f.session.cwd||f.session.workspaceRoot).trim();if(!H)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:H,...f.restoreMessages!==!1?{messages:xX(f.messages??[],$)}:{}}}async function E9(f,$){if((await Y2("git",["-C",f,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${f} is not a git repository`);if(await Y2("git",["-C",f,"cat-file","-e",`${$.ref}^{commit}`],{windowsHide:!0}),await Y2("git",["-C",f,"reset","--hard"],{windowsHide:!0}),await Y2("git",["-C",f,"clean","-fd"],{windowsHide:!0}),$.kind==="commit"){await Y2("git",["-C",f,"reset","--hard",$.ref],{windowsHide:!0});return}await Y2("git",["-C",f,"stash","apply",$.ref],{windowsHide:!0})}var vX={};N(vX,{SessionVersioningService:()=>Z$,SessionVersioningError:()=>Df});class Df extends Error{code;constructor(f,$){super($);this.code=f;this.name="SessionVersioningError"}}function nM(f){let $=f.sessionId.trim();if(!$)throw new Df("invalid_restore","sessionId is required");if(!f.restoreMessages&&!f.restoreWorkspace)throw new Df("invalid_restore","restore.messages or restore.workspace must be true");if(f.restoreMessages&&f.requiresStart)throw new Df("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger(f.checkpointRunCount)||f.checkpointRunCount<1)throw new Df("invalid_restore","checkpointRunCount must be a positive integer");return $}class Z${async restoreCheckpoint(f){let $=f.restore?.messages!==!1,J=f.restore?.workspace!==!1,H=nM({sessionId:f.sessionId,restoreMessages:$,restoreWorkspace:J,requiresStart:f.start===void 0,checkpointRunCount:f.checkpointRunCount}),W=await f.getSession(H);if(!W)throw new Df("session_not_found",`Session ${H} not found`);let Q=$?await f.readMessages(H):void 0;if($&&Q?.length===0)throw new Df("session_messages_not_found",`No messages found for session ${H}`);let Z=C9({session:W,messages:Q,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restoreMessages:$});if(J)await(f.applyWorkspaceCheckpoint??E9)(Z.cwd,Z.checkpoint);let j=J0({session:W,messages:Q});if(!$)return{checkpoint:Z.checkpoint,sourceSnapshot:j};let P=b9(W,f.checkpointRunCount),X=f.restore?.omitCheckpointMessageFromSession?w9(Q??[],f.checkpointRunCount):Z.messages??[],V={sourceSession:W,sourceMessages:Q,sourceSnapshot:j,plan:Z,restoredCheckpointMetadata:P,initialMessages:X,restoreMessages:$,restoreWorkspace:J,checkpointRunCount:f.checkpointRunCount};if(!f.start||!f.startSession)throw new Df("invalid_restore","start is required when restore.messages is true");let Y=f.buildStartInput?await f.buildStartInput(V,f.start):f.start,B=await f.startSession(Y),A=f.getStartedSessionId?.(B);if(A)await(f.retainCheckpointRefs??zZ)(Z.cwd,A,P?.history??[]);let R=A&&f.readRestoredSession?await f.readRestoredSession(A):void 0;return{sessionId:A,startResult:B,messages:Z.messages,checkpoint:Z.checkpoint,sourceSnapshot:j,...R?{restoredSnapshot:J0({session:R,messages:X})}:{}}}}var uX={};N(uX,{FileTeamPersistenceStore:()=>lJ});import{appendFileSync as aM,existsSync as S9,mkdirSync as tM,readFileSync as sM,renameSync as oM,unlinkSync as eM,writeFileSync as f_}from"node:fs";import{join as k9}from"node:path";import{resolveTeamDataDir as $_}from"@cline/shared/storage";function J_(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class lJ{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor(f){let $=J_(f.teamName),J=f.baseDir?.trim()||$_();this.dirPath=k9(J,$),this.statePath=k9(this.dirPath,"state.json"),this.taskHistoryPath=k9(this.dirPath,"task-history.jsonl")}loadState(){if(!S9(this.statePath))return;try{let f=sM(this.statePath,"utf8"),$=JSON.parse(f);if($.version!==1||!$.teamState)return;for(let J of $.teammates??[])this.teammateSpecs.set(J.agentId,J);return xP($.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec(f){this.teammateSpecs.set(f.agentId,f)}removeTeammateSpec(f){this.teammateSpecs.delete(f)}persist(f){if(!this.hasPersistableState(f)){this.clearPersistedState();return}this.ensureDir();let $={version:1,updatedAt:new Date().toISOString(),teamState:f.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;f_(J,`${JSON.stringify($,null,2)}
696
- `,"utf8"),oM(J,this.statePath)}appendTaskHistory(f){let $={};switch(f.type){case"team_task_updated":$=f.task;break;case"team_message":$={agentId:f.message.fromAgentId,toAgentId:f.message.toAgentId,subject:f.message.subject,taskId:f.message.taskId};break;case"team_mission_log":$={agentId:f.entry.agentId,kind:f.entry.kind,summary:f.entry.summary,taskId:f.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":$={agentId:f.agentId,message:"message"in f?f.message:void 0};break;case"task_end":$={agentId:f.agentId,finishReason:f.result?.finishReason,error:f.error?.message};break;case"agent_event":$={agentId:f.agentId,eventType:f.event.type};break}this.ensureDir(),aM(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:f.type,task:$})}
697
- `,"utf8")}ensureDir(){if(!S9(this.dirPath))tM(this.dirPath,{recursive:!0})}hasPersistableState(f){let $=f.exportState();if(this.teammateSpecs.size>0)return!0;if($.members.some((J)=>J.role==="teammate"))return!0;return $.tasks.length>0||$.mailbox.length>0||$.missionLog.length>0}clearPersistedState(){if(S9(this.statePath))eM(this.statePath)}}var cX={};N(cX,{ChatViewStateSchema:()=>m9,ChatSummarySchema:()=>tJ,ChatSessionStatusSchema:()=>iJ,ChatSessionConfigSchema:()=>pJ,ChatMessageSchema:()=>aJ,ChatMessageRoleSchema:()=>nJ});import{z as q}from"zod";var pJ=q.object({workspaceRoot:q.string().min(1),cwd:q.string().optional(),provider:q.string().min(1),model:q.string().min(1),mode:q.enum(["act","plan"]).default("act"),apiKey:q.string(),systemPrompt:q.string().optional(),rules:q.string().optional(),maxIterations:q.number().int().positive().optional(),enableTools:q.boolean(),enableSpawn:q.boolean().optional(),enableTeams:q.boolean().optional(),autoApproveTools:q.boolean().optional(),missionStepInterval:q.number().int().positive().optional(),missionTimeIntervalMs:q.number().int().positive().optional()}),iJ=q.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),nJ=q.enum(["user","assistant","tool","system","status","error"]),aJ=q.object({id:q.string().min(1),sessionId:q.string().nullable(),role:nJ,content:q.string(),createdAt:q.number().int().nonnegative(),meta:q.object({stream:q.enum(["stdout","stderr"]).optional(),toolName:q.string().optional(),iteration:q.number().int().nonnegative().optional(),agentId:q.string().optional(),conversationId:q.string().optional(),hookEventName:q.string().optional(),inputTokens:q.number().int().nonnegative().optional(),outputTokens:q.number().int().nonnegative().optional(),checkpoint:q.object({ref:q.string(),createdAt:q.number().int().nonnegative(),runCount:q.number().int().positive(),kind:q.enum(["stash","commit"]).optional()}).optional()}).optional()}),tJ=q.object({toolCalls:q.number().int().nonnegative(),tokensIn:q.number().int().nonnegative(),tokensOut:q.number().int().nonnegative()}),m9=q.object({sessionId:q.string().nullable(),status:iJ,config:pJ,messages:q.array(aJ),rawTranscript:q.string(),error:q.string().nullable(),summary:tJ});var dX={};N(dX,{CORE_BUILD_VERSION:()=>I9});var I9=n3;import{Agent as E_,createAgentRuntime as S_}from"@cline/agents";var pX={};N(pX,{fetchClineRecommendedModels:()=>x9,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>sJ});var rX="https://api.cline.bot",H_=5000,sJ={recommended:[{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",description:"Most intelligent model for agents and coding",tags:["BEST"]},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",description:"Strong coding and agent performance",tags:["NEW"]},{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"1M context window, strong coding performance",tags:["NEW"]},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",description:"OpenAI's latest with strong coding abilities",tags:["NEW"]}],free:[{id:"kwaipilot/kat-coder-pro",name:"KwaiKAT Kat Coder Pro",description:"Advanced agentic coding model",tags:["FREE"]},{id:"arcee-ai/trinity-large-preview:free",name:"Arcee AI Trinity Large Preview",description:"Advanced large preview model",tags:["FREE"]}]};function W_(f){return{recommended:f.recommended.map(($)=>({...$,tags:[...$.tags]})),free:f.free.map(($)=>({...$,tags:[...$.tags]}))}}function lX(f){if(!f||typeof f!=="object")return null;let $=f;if(typeof $.id!=="string"||$.id.length===0)return null;return{id:$.id,name:typeof $.name==="string"&&$.name.length>0?$.name:$.id,description:typeof $.description==="string"?$.description:"",tags:Array.isArray($.tags)?$.tags.filter((J)=>typeof J==="string"):[]}}function Q_(f){if(!f||typeof f!=="object")return null;let $=f,J=Array.isArray($.recommended)?$.recommended:[],H=Array.isArray($.free)?$.free:[],W=J.map(lX).filter((Z)=>Z!==null),Q=H.map(lX).filter((Z)=>Z!==null);if(W.length===0&&Q.length===0)return null;return{recommended:W,free:Q}}function Z_(f){let $=f.baseUrl?.trim();if($)return $;try{return(f.providerSettingsManager??new P0).getProviderSettings("cline")?.baseUrl?.trim()||rX}catch{return rX}}async function j_(f,$,J){let H=new AbortController,W=setTimeout(()=>H.abort(),J);try{return await f($,{signal:H.signal})}finally{clearTimeout(W)}}async function x9(f={}){try{let $=Z_(f),J=f.fetchImpl??fetch,H=await j_(J,`${$}/api/v1/ai/cline/recommended-models`,f.timeoutMs??H_);if(!H.ok)throw Error(`HTTP ${H.status}`);let W=await H.json(),Q=Q_(W);if(Q)return Q}catch{}return W_(sJ)}var iX={};N(iX,{loadLlmsConfigFromFile:()=>v9,defineLlmsConfig:()=>g9});import{readFile as P_}from"node:fs/promises";import X_ from"node:path";function g9(f){return f}async function v9(f){let $=X_.resolve(f),J=await P_($,"utf8"),H;try{H=JSON.parse(J)}catch(W){let Q=W instanceof Error?W.message:String(W);throw Error(`Failed to parse JSON config at "${$}": ${Q}`)}return V_(H,$)}function V_(f,$){if(!f||typeof f!=="object")throw Error(`Invalid llms config in "${$}": expected an object.`);let H=f.providers;if(!Array.isArray(H))throw Error(`Invalid llms config in "${$}": "providers" must be an array.`);if(!H.length)throw Error(`Invalid llms config in "${$}": "providers" cannot be empty.`);return f}var eX={};N(eX,{createLlmsSdk:()=>c9,DefaultLlmsSdk:()=>G4});import{BUILT_IN_PROVIDER_IDS as tX,createHandler as A_,createHandlerAsync as R_,getProviderCollection as F_,hasProvider as sX,registerAsyncHandler as y_,registerHandler as K_,registerModel as U_,registerProvider as oX}from"@cline/llms";function nX(f){return f?{...f}:{}}function Y_(f,$){if(f)return f;if(!$)return;let J=globalThis.process;if(!J?.env)return;return J.env[$]}function B_(f,$){if(!$.length)throw Error(`Provider "${f}" must include at least one model.`)}function aX(f){let $=Object.keys(f.collection.models);return{id:f.collection.provider.id,name:f.collection.provider.name,description:f.collection.provider.description,protocol:f.collection.provider.protocol,baseUrl:f.collection.provider.baseUrl,capabilities:f.collection.provider.capabilities,env:f.collection.provider.env,models:$,defaultModel:f.collection.provider.defaultModelId,modelCount:$.length}}class u9{providers=new Map;register(f){B_(f.id,f.models);let $=f.defaultModel??f.models[0];if(!$)throw Error(`Provider "${f.id}" must define a default model.`);if(!f.models.includes($))throw Error(`Default model "${$}" is not included in configured models for "${f.id}".`);let J=this.providers.get(f.id);this.providers.set(f.id,{id:f.id,models:new Set([...J?.models??[],...f.models]),defaultModel:$,defaults:{...J?.defaults??{},...nX(f.defaults)}})}registerSelectionConfig(f){this.register({id:f.id,models:f.models,defaultModel:f.defaultModel,defaults:{apiKey:Y_(f.apiKey,f.apiKeyEnv),routingProviderId:f.builtinProviderId,baseUrl:f.baseUrl,headers:f.headers,timeoutMs:f.timeoutMs,capabilities:f.capabilities,...nX(f.settings)}})}registerModel(f,$){let J=this.providers.get(f);if(!J){this.providers.set(f,{id:f,models:new Set([$]),defaultModel:$,defaults:{}});return}J.models.add($)}createHandlerConfig(f){let $=this.require(f.providerId),J=f.modelId??$.defaultModel;if(!$.models.has(J))throw Error(`Model "${J}" is not configured for provider "${f.providerId}".`);return{providerId:f.providerId,modelId:J,...$.defaults,...f.overrides}}list(){return Array.from(this.providers.values()).map((f)=>({id:f.id,models:Array.from(f.models),defaultModel:f.defaultModel}))}getModels(f){return Array.from(this.require(f).models)}hasProvider(f){return this.providers.has(f)}hasModel(f,$){return this.providers.get(f)?.models.has($)??!1}require(f){let $=this.providers.get(f);if(!$)throw Error(`Provider "${f}" is not configured in this SDK instance.`);return $}}class G4{configuredProviders=new u9;constructor(f){this.applyConfig(f)}createHandler(f){return A_(this.configuredProviders.createHandlerConfig(f))}async createHandlerAsync(f){return R_(this.configuredProviders.createHandlerConfig(f))}registerProvider(f){if(oX(f.collection),f.handlerFactory&&f.asyncHandlerFactory)throw Error(`Provider "${f.collection.provider.id}" cannot register both sync and async handlers.`);if(f.handlerFactory)K_(f.collection.provider.id,f.handlerFactory);if(f.asyncHandlerFactory)y_(f.collection.provider.id,f.asyncHandlerFactory);this.configuredProviders.register({id:f.collection.provider.id,models:f.exposeModels??Object.keys(f.collection.models),defaultModel:f.defaultModel??f.collection.provider.defaultModelId,defaults:f.defaults})}registerBuiltinProvider(f){let $=f.exposeModels??Object.keys(f.models),J=f.defaultModel??$[0];if(!J)throw Error(`Provider "${f.id}" must define a default model.`);oX({provider:{id:f.id,name:f.name??f.id,description:f.description,protocol:f.protocol,baseUrl:f.baseUrl,defaultModelId:J,client:f.client??"openai-compatible",capabilities:f.capabilities,env:f.env,source:"system"},models:f.models}),this.configuredProviders.register({id:f.id,models:$,defaultModel:J,defaults:{routingProviderId:f.builtinProviderId,...f.defaults??{}}})}registerModel(f){U_(f.providerId,f.modelId,f.info),this.configuredProviders.registerModel(f.providerId,f.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...tX]}async getBuiltInProviders(){return(await Promise.all(tX.map(($)=>F_($)))).filter(($)=>$!==void 0).map(($)=>aX({collection:$}))}getModels(f){return this.configuredProviders.getModels(f)}isProviderConfigured(f){return this.configuredProviders.hasProvider(f)}isModelConfigured(f,$){return this.configuredProviders.hasModel(f,$)}applyConfig(f){for(let $ of f.providers)this.configuredProviders.registerSelectionConfig($);for(let $ of f.models??[])this.registerModel($);for(let $ of f.customProviders??[])this.registerProvider($);for(let $ of this.configuredProviders.list()){let J=sX($.id),H=this.configuredProviders.createHandlerConfig({providerId:$.id,modelId:$.defaultModel}).routingProviderId,W=typeof H==="string"&&sX(H);if(!J&&!W)throw Error(`Provider "${$.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function c9(f){return new G4(f)}GH();async function G_(){return Promise.resolve().then(() => ($V(),fV))}function g_(){return new Date().toISOString()}function v_(f){if(XV(f)!=="providers.json")return;let $=r9(f);if(XV($)!=="settings")return;return r9($)}class P0{filePath;dataDir;constructor(f={}){if(this.filePath=f.filePath??x_(),this.dataDir=f.dataDir??v_(this.filePath),this.dataDir||!f.filePath)K4({providerSettingsManager:this,dataDir:this.dataDir});if(LX(this),uJ(this.read()),d9(this.filePath))try{PV(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!d9(this.filePath))return $$();try{let f=m_(this.filePath,"utf8"),$=JSON.parse(f),J=u1.safeParse($);if(J.success)return uJ(J.data),J.data}catch{}return $$()}write(f){let $=u1.parse(f),J=r9(this.filePath);if(!d9(J))k_(J,{recursive:!0,mode:448});I_(this.filePath,`${JSON.stringify($,null,2)}
698
- `,"utf8");try{PV(this.filePath,384)}catch{}uJ($)}saveProviderSettings(f,$={}){let J=q8.parse(f),H=this.read(),W=J.provider,Q=$.setLastUsed!==!1,Z=H.providers[W],j=$.tokenSource??Z?.tokenSource??"manual",P={...H,providers:{...H.providers,[W]:{settings:J,updatedAt:g_(),tokenSource:j}},lastUsedProvider:Q?W:H.lastUsedProvider};return this.write(P),P}getProviderSettings(f){return this.read().providers[f]?.settings}getLastUsedProviderSettings(){let f=this.read(),$=f.lastUsedProvider;if(!$)return;return f.providers[$]?.settings}getProviderConfig(f,$){let J=this.getProviderSettings(f);if(!J)return;return Cf(J,$)}getLastUsedProviderConfig(f){let $=this.getLastUsedProviderSettings();if(!$)return;return Cf($,f)}async refreshCatalog(){try{await g1({})}catch{}}}Kf();s4();import{isOAuthProviderId as u_}from"@cline/shared";var c_="https://api.cline.bot",l9="workos:";function d_(f,$){if(f==="cline")return`${l9}${$}`;return $}function r_(f,$){if(f==="cline"&&$.toLowerCase().startsWith(l9))return $.slice(l9.length);return $}function l_(f){let J=Ff(f)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function p_(f,$){let J=f.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let H=l_($);if(H)return H;return Date.now()-1}function i_(f,$){let J=$.auth?.accessToken?.trim(),H=$.auth?.refreshToken?.trim();if(!J||!H)return null;let W=r_(f,J);if(!W)return null;return{access:W,refresh:H,expires:p_($,W),accountId:$.auth?.accountId}}function n_(f,$){let J=f?.expiresAt,H=$?.expiresAt;return f?.accessToken===$?.accessToken&&f?.refreshToken===$?.refreshToken&&f?.accountId===$?.accountId&&J===H}class eJ extends Error{providerId;constructor(f){super(`OAuth credentials for provider "${f}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=f}}class p9{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor(f){this.providerSettingsManager=f?.providerSettingsManager??new P0,this.telemetry=f?.telemetry}async resolveProviderApiKey(f){if(!u_(f.providerId))return null;return this.resolveWithSingleFlight(f.providerId,f.forceRefresh)}async resolveWithSingleFlight(f,$=!1){let J=this.refreshInFlight.get(f);if(J)return J;let H=this.resolveProviderApiKeyInternal(f,$).catch((W)=>{throw W}).finally(()=>{this.refreshInFlight.delete(f)});return this.refreshInFlight.set(f,H),H}async resolveProviderApiKeyInternal(f,$){let J=this.providerSettingsManager.getProviderSettings(f);if(!J)return null;let H=i_(f,J);if(!H)return null;let W=await this.resolveCredentials(f,J,H,$);if(!W)throw new eJ(f);let Q=d_(f,W.access),Z={...J.auth??{},accessToken:Q,refreshToken:W.refresh,accountId:W.accountId};Z.expiresAt=W.expires;let j={...J,auth:Z},P=!n_(J.auth,j.auth);if(P)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:f,apiKey:Q,accountId:W.accountId,refreshed:P}}async resolveCredentials(f,$,J,H){if(f==="cline")return k8(J,{apiBaseUrl:$.baseUrl?.trim()||c_,telemetry:this.telemetry},{forceRefresh:H});if(f==="oca")return M8(J,{forceRefresh:H,telemetry:this.telemetry},{mode:$.oca?.mode,telemetry:this.telemetry});return I8(J,{forceRefresh:H,telemetry:this.telemetry})}}import{normalizeUserInput as a_}from"@cline/shared";import{nanoid as t_}from"nanoid";class VV{list(f){return f?mf(f):[]}update(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=$.promptId.trim(),H=f.pendingPrompts.findIndex((P)=>P.id===J);if(H<0)return{sessionId:$.sessionId,prompts:mf(f),updated:!1};let W=f.pendingPrompts[H];if(!W)return{sessionId:$.sessionId,prompts:mf(f),updated:!1};let Q=$.prompt===void 0?W.prompt:a_($.prompt).trim();if(!Q)throw Error("prompt cannot be empty");let Z=$.delivery??W.delivery,j={...W,prompt:Q,delivery:Z};return f.pendingPrompts.splice(H,1),s_(f,j,H,W.delivery),{sessionId:$.sessionId,prompts:mf(f),prompt:fH(j),updated:!0}}delete(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=$.promptId.trim(),H=f.pendingPrompts.findIndex((Q)=>Q.id===J);if(H<0)return{sessionId:$.sessionId,prompts:mf(f),removed:!1};let[W]=f.pendingPrompts.splice(H,1);return{sessionId:$.sessionId,prompts:mf(f),prompt:W?fH(W):void 0,removed:!0}}enqueue(f,$){let{prompt:J,delivery:H,userImages:W,userFiles:Q}=$,Z=f.pendingPrompts.findIndex((j)=>j.prompt===J);if(Z>=0){let[j]=f.pendingPrompts.splice(Z,1),P={...j,prompt:J,userImages:W??j.userImages,userFiles:Q??j.userFiles};if(H==="steer"||j.delivery==="steer")f.pendingPrompts.unshift({...P,delivery:"steer"});else f.pendingPrompts.push(P)}else{let j={id:`pending_${Date.now()}_${t_(5)}`,prompt:J,delivery:H,userImages:W,userFiles:Q};if(H==="steer")f.pendingPrompts.unshift(j);else f.pendingPrompts.push(j)}return mf(f)}consumeSteer(f){let $=f.pendingPrompts.findIndex((H)=>H.delivery==="steer");if($<0)return{prompts:mf(f)};let[J]=f.pendingPrompts.splice($,1);return{entry:J,prompts:mf(f)}}shiftNext(f){return{entry:f.pendingPrompts.shift(),prompts:mf(f)}}requeueFront(f,$){return f.pendingPrompts.unshift($),mf(f)}clear(f){return f.pendingPrompts.length=0,[]}}class i9{deps;service=new VV;constructor(f){this.deps=f}list(f){return this.service.list(this.deps.getSession(f))}update(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=this.service.update($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}delete(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=this.service.delete($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}enqueue(f,$){let J=this.deps.getSession(f);if(!J||J.aborting)return;this.service.enqueue(J,$),this.emitPrompts(J),this.scheduleDrain(f,J)}consumeSteer(f){let $=this.deps.getSession(f);if(!$)return;let{entry:J}=this.service.consumeSteer($);if(!J)return;return this.emitPrompts($),this.emitSubmitted($,J),J.prompt}clearAborted(f){if(f.pendingPrompts.length===0)return;this.service.clear(f),this.emitPrompts(f)}emitPrompts(f){this.deps.emit({type:"pending_prompts",payload:{sessionId:f.sessionId,prompts:mf(f)}})}scheduleDrain(f,$){if($.pendingPrompts.length===0||$.aborting||$.drainingPendingPrompts||!$.agent.canStartRun())return;queueMicrotask(()=>{this.drain(f)})}async drain(f){let $=this.deps.getSession(f);if(!$||$.aborting||$.drainingPendingPrompts)return;if(!$.agent.canStartRun())return;let{entry:J}=this.service.shiftNext($);if(!J)return;this.emitPrompts($),this.emitSubmitted($,J),$.drainingPendingPrompts=!0;try{await this.deps.send({sessionId:f,prompt:J.prompt,userImages:J.userImages,userFiles:J.userFiles})}catch(H){if((H instanceof Error?H.message:String(H)).includes("already in progress"))this.service.requeueFront($,J),this.emitPrompts($);else throw H}finally{if($.drainingPendingPrompts=!1,$.pendingPrompts.length>0&&$.status!=="failed"&&$.status!=="cancelled")queueMicrotask(()=>{this.drain(f)})}}emitSubmitted(f,$){let J=fH($);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:f.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function fH(f){return{id:f.id,prompt:f.prompt,delivery:f.delivery,attachmentCount:(f.userImages?.length??0)+(f.userFiles?.length??0)}}function mf(f){return f.pendingPrompts.map(fH)}function s_(f,$,J,H){if($.delivery==="steer")f.pendingPrompts.unshift($);else if(H==="steer")f.pendingPrompts.push($);else f.pendingPrompts.splice(J,0,$)}Kf();class n9{deps;constructor(f){this.deps=f}dispatchAgentEvent(f,$,J){let H=this.deps.getSession(f),W={sessionId:f,config:$,liveSession:H,usageBySession:this.deps.usageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},Q=zW(J),Z=H&&Q.agentId===YV(H.agent);OW(W,J,Z?{isPrimaryAgentEvent:!0,...H?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent(f,$){let J=this.deps.getSession(f);if(J){if(d5(J,$),$.type==="agent_event"){let H={sessionId:f,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};OW(H,$.event,{teamRole:"teammate",teamAgentId:$.agentId,isPrimaryAgentEvent:!1})}if($.type==="teammate_spawned"){let H=T0({agentId:$.teammate.runtimeAgentId??$.agentId,conversationId:$.teammate.conversationId,parentAgentId:$.teammate.parentAgentId,createdByAgentId:YV(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:$.agentId});if(H)E0(J.config.telemetry,{ulid:f,modelId:$.teammate.modelId??J.config.modelId,provider:J.config.providerId,...H})}}if(await r5(f,$,this.deps.invokeBackendOptional),J)l5(J,f,$,this.deps.emit)}async handlePluginEvent(f,$,J){if($.name==="plugin_log"){this.handlePluginLog(f,$.payload);return}if($.name==="automation_event"){let P=this.deps.getSession(f)?.config.extensionContext?.automation??J;if(!P)return;let X=$.payload&&typeof $.payload==="object"?$.payload:void 0;if(!X)return;await P.ingestEvent(X);return}if($.name!=="steer_message"&&$.name!=="queue_message"&&$.name!=="pending_prompt")return;let H=$.payload&&typeof $.payload==="object"?$.payload:void 0,W=typeof H?.sessionId==="string"&&H.sessionId.trim().length>0?H.sessionId.trim():f,Q=typeof H?.prompt==="string"?H.prompt.trim():"";if(!Q)return;let Z=$.name==="steer_message"?"steer":$.name==="queue_message"?"queue":H?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(W,{prompt:Q,delivery:Z})}handlePluginLog(f,$,J){let H=this.deps.getSession(f),W=J??H?.config.extensionContext?.logger??H?.config.logger;if(!W||!$||typeof $!=="object")return;let Q=$,Z=typeof Q.message==="string"?Q.message:"";if(!Z)return;let j=Q.metadata&&typeof Q.metadata==="object"?{...Q.metadata}:{};if(j.sessionId??=f,typeof Q.pluginName==="string"&&Q.pluginName)j.pluginName=Q.pluginName;if(Q.level==="debug"){W.debug(Z,j);return}if(Q.level==="error"){if(W.error)W.error(Z,j);else W.log(Z,{...j,severity:"error"});return}W.log(Z,j)}}function YV(f){return f.getAgentId()}function a9(f){return{sessionId:f.sessionId,source:f.source,pid:process.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:n0(f.config),teamName:f.config.teamName?.trim()||void 0,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,parentSessionId:typeof f.sessionMetadata?.parentSessionId==="string"?f.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof f.sessionMetadata?.parentAgentId==="string"?f.sessionMetadata.parentAgentId:void 0,agentId:typeof f.sessionMetadata?.agentId==="string"?f.sessionMetadata.agentId:void 0,conversationId:typeof f.sessionMetadata?.conversationId==="string"?f.sessionMetadata.conversationId:void 0,isSubagent:typeof f.sessionMetadata?.isSubagent==="boolean"?f.sessionMetadata.isSubagent:!1,prompt:f.pendingPrompt,metadata:f.sessionMetadata,messagesPath:f.artifacts?.messagesPath,updatedAt:f.updatedAt??f.endedAt??f.startedAt}}function t9(f,$){let J=f[$];return typeof J==="function"?J:null}async function BV(f,$,...J){let H=t9(f,$);if(!H)throw Error(`session service method not available: ${$}`);return Promise.resolve(H.apply(f,J))}async function AV(f,$,...J){let H=t9(f,$);if(!H)return;await Promise.resolve(H.apply(f,J))}async function RV(f,$,...J){let H=t9(f,$);if(!H)return;return await Promise.resolve(H.apply(f,J))}F0();Kf();function s9(f,$,J,H){return r0({configProvider:{getRuntimeConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:$.hooks,extensions:$.extensions,logger:$.logger,telemetry:$.telemetry},getConnectionConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Q=$.enableTools?N$({cwd:$.cwd,...bf[G0({mode:$.mode})],executors:H}):[];if($.enableSpawnAgent)Q.push(s9(f,$,J,H));return R$(Q)},onSubAgentEvent:(Q)=>f.onAgentEvent(J,$,Q),onSubAgentStart:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime;f.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let j=T0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)E0($.telemetry,{ulid:J,modelId:$.modelId,provider:$.providerId,...j});z2($.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...j}),f.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime,j=f.subAgentStarts.get(Q.subAgentId),P=j?Date.now()-j.startedAt:0,X=Q.result?.text?Q.result.text.split(`
699
- `).length:0;z2($.telemetry,{event:"ended",ulid:J,durationMs:P,outputLines:X,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...T0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId})}),f.subAgentStarts.delete(Q.subAgentId),f.invokeBackendOptional("handleSubAgentEnd",J,Q)}})}import{readFile as o_,stat as e_}from"node:fs/promises";var fL=20480000;async function FV(f){let $=await e_(f);if(!$.isFile())throw Error("Path is not a file");if($.size>fL)throw Error("File is too large to read into context.");let J=await o_(f,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var yV=5000;class j0{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new J4;sessions=new Map;usageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new Z$;constructor(f){let $=$L();if($)jL($);let J=F$(f.distinctId);this.sessionService=f.sessionService,this.runtimeBuilder=f.runtimeBuilder??new X2,this.createAgentInstance=f.createAgent??((H)=>new d0(H)),this.defaultCapabilities=Bf(f.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=f.toolPolicies,this.providerSettingsManager=f.providerSettingsManager??new P0,this.oauthTokenManager=f.oauthTokenManager??new p9({providerSettingsManager:this.providerSettingsManager,telemetry:f.telemetry}),this.defaultTelemetry=f.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=f.fetch,this.pendingPromptsController=new i9({getSession:(H)=>this.sessions.get(H),emit:(H)=>this.emit(H),send:(H)=>this.runTurn(H)}),this.pendingPrompts={list:async(H)=>this.pendingPromptsController.list(H.sessionId),update:async(H)=>this.pendingPromptsController.update(H),delete:async(H)=>this.pendingPromptsController.delete(H)},this.eventBridge=new n9({getSession:(H)=>this.sessions.get(H),usageBySession:this.usageBySession,emit:(H)=>this.emit(H),persistMessages:(H,W,Q)=>{this.invoke("persistSessionMessages",H,W,Q)},enqueuePendingPrompt:(H,W)=>this.pendingPromptsController.enqueue(H,W),invokeBackendOptional:(H,...W)=>this.invokeOptional(H,...W)})}async startSession(f){let $=f.source??Vf.CLI,J=s(),H=f.config.sessionId?.trim()??"",W=H||WL(),Q=f,Z=Q.initialMessages??[];this.usageBySession.set(W,Z.length>0?A8(Z):p0());let j=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!j)throw Error("session service method not available: ensureSessionsDir");let P=o9(j,W),X=o9(P,`${W}.messages.json`),V=o9(P,`${W}.json`),Y=n0(f.config),B=Gf.parse({version:1,session_id:W,source:$,pid:process.pid,started_at:J,status:"running",interactive:f.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Q.config.cwd,workspace_root:Y,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,messages_path:X}),A;if(H.length>0&&Z.length>0&&!Q.prompt?.trim()){let C=await this.invokeOptionalValue("readSessionManifest",W);if(C)B=C,A={manifestPath:V,messagesPath:C.messages_path||X,manifest:C}}let U=Bf(this.defaultCapabilities,f.capabilities),y=U?.toolExecutors??this.toolExecutors,F=f.localRuntime,K=F?.extensionContext?.logger??F?.logger,M=F?.extensionContext?.automation,T;T=await Wj({input:Q,localRuntime:f.localRuntime,sessionId:W,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(C)=>{if(C.name==="plugin_log"){this.eventBridge.handlePluginLog(W,C.payload,K);return}this.eventBridge.handlePluginEvent(W,C,M)},onTeamEvent:(C)=>{this.eventBridge.handleTeamEvent(W,C),T.config.onTeamEvent?.(C)},createSpawnTool:()=>s9({getSession:(C)=>this.sessions.get(C),subAgentStarts:this.subAgentStarts,onAgentEvent:(C,nf,vf)=>this.eventBridge.dispatchAgentEvent(C,nf,vf),invokeBackendOptional:(C,...nf)=>this.invokeOptional(C,...nf)},T.config,W,y),readSessionMetadata:async()=>(await this.getSession(W))?.metadata,writeSessionMetadata:async(C)=>{await this.persistSessionMetadata(W,()=>C)}});let G=await this.runtimeBuilder.build(T.runtimeBuilderInput),h=T.config,z=T.providerConfig;if(G.teamRuntime&&!h.teamName?.trim())h.teamName=G.teamRuntime.getTeamName();let u=[...G.tools,...h.extraTools??[]],gf=G.extensions??T.extensions,a={sessionId:W,providerId:z.providerId,modelId:z.modelId,apiKey:z.apiKey,baseUrl:z.baseUrl,headers:z.headers,knownModels:z.knownModels,providerConfig:z,thinking:h.thinking,reasoningEffort:h.reasoningEffort??z.reasoningEffort,systemPrompt:h.systemPrompt,maxIterations:h.maxIterations,execution:h.execution,prepareTurn:d2(h),tools:u,hooks:T.hooks,extensions:gf,hookErrorMode:h.hookErrorMode,initialMessages:T.effectiveInput.initialMessages,userFileContentLoader:FV,toolPolicies:T.toolPolicies,requestToolApproval:T.requestToolApproval,onConsecutiveMistakeLimitReached:h.onConsecutiveMistakeLimitReached,completionPolicy:G.completionPolicy,consumePendingUserMessage:()=>{let C=this.pendingPromptsController.consumeSteer(W);return C?j4(C,h.mode):C},logger:G.logger??h.logger,extensionContext:h.extensionContext,onEvent:(C)=>this.eventBridge.dispatchAgentEvent(W,h,C)};a.hooks={...a.hooks,onEvent:async(C)=>{if(await T.hooks?.onEvent?.(C),C.type!=="assistant-message")return;let nf=this.sessions.get(W);if(!nf)return;let vf=nf.agent.getMessages();try{await this.invoke("persistSessionMessages",W,vf,h.systemPrompt)}catch($f){h.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:W,error:$f})}}};let c=this.createAgentInstance(a);if(a.onEvent)c.subscribeEvents(a.onEvent);G.registerLeadAgent?.(c);let d=T0({agentId:c.getAgentId(),conversationId:c.getConversationId(),teamId:G.teamRuntime?.getTeamId(),teamName:G.teamRuntime?.getTeamName(),teamRole:G.teamRuntime?"lead":void 0});if(Zj(h,W,H.length>0,Y,d),d)E0(h.telemetry,{ulid:W,modelId:h.modelId,provider:h.providerId,...d});if(G.teamRuntime)l4(h.telemetry,{ulid:W,teamId:G.teamRuntime.getTeamId(),teamName:G.teamRuntime.getTeamName(),leadAgentId:c.getAgentId(),restoredFromPersistence:G.teamRestoredFromPersistence===!0});let t={sessionId:W,config:h,sessionMetadata:Q.sessionMetadata,...A?{artifacts:A}:{},source:$,startedAt:A?.manifest.started_at??J,updatedAt:A?.manifest.ended_at??A?.manifest.started_at??J,pendingPrompt:B.prompt,runtime:G,agent:c,started:!1,status:A?.manifest.status??"running",aborting:!1,interactive:f.interactive===!0,persistedMessages:Z,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:T.pluginSandboxShutdown,submitAndExitObserved:!1};if(this.sessions.set(W,t),this.emitStatus(W,"running"),Z.length>0&&!A){if(await this.ensureSessionPersisted(t),await this.invoke("persistSessionMessages",t.sessionId,Z,t.config.systemPrompt),!Q.prompt?.trim())await this.updateStatus(t,"completed",0)}let pf;try{if(Q.prompt?.trim())if(pf=await this.executeTurn(t,{prompt:Q.prompt,userImages:Q.userImages,userFiles:Q.userFiles}),!t.interactive)await this.finalizeSingleRun(t,pf.finishReason);else await this.completeInteractiveTurn(t,pf.finishReason)}catch(C){if(t.interactive&&t.aborting)pf=await this.completeAbortedInteractiveTurn(t);else throw await this.failSession(t),C}return{sessionId:W,manifest:B,manifestPath:V,messagesPath:X,result:pf}}async restoreSession(f){return this.sessionVersioning.restoreCheckpoint({...f,getSession:($)=>this.getSession($),readMessages:($)=>this.readSessionMessages($),buildStartInput:($,J)=>{let H=$.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:$.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...H?{sessionMetadata:H}:{},initialMessages:$.initialMessages}},startSession:($)=>this.startSession($),getStartedSessionId:($)=>$.sessionId,readRestoredSession:($)=>this.getSession($)})}async runTurn(f){let $=this.getSessionOrThrow(f.sessionId),J=$.agent.canStartRun(),H=f.delivery??($.interactive&&!J?"queue":void 0);if($.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:f.sessionId,promptLength:f.prompt.length,userImageCount:f.userImages?.length??0,userFileCount:f.userFiles?.length??0,delivery:H??"immediate"}}),H==="queue"||H==="steer"){this.pendingPromptsController.enqueue(f.sessionId,{prompt:f.prompt,delivery:H,userImages:f.userImages,userFiles:f.userFiles});return}try{let W=await this.executeTurn($,{prompt:f.prompt,userImages:f.userImages,userFiles:f.userFiles});if(!$.interactive)await this.finalizeSingleRun($,W.finishReason);else await this.completeInteractiveTurn($,W.finishReason);if(W.finishReason==="error"||W.finishReason==="aborted")return W;return queueMicrotask(()=>{this.pendingPromptsController.drain(f.sessionId)}),W}catch(W){if($.interactive&&$.aborting)return await this.completeAbortedInteractiveTurn($);throw await this.failSession($),W}}async getAccumulatedUsage(f){return WP(this.usageBySession.get(f))}async abort(f,$){let J=this.sessions.get(f);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:f}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort($)}async stopSession(f){let $=this.sessions.get(f);if(!$)return;if($.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:f}}),$.interactive&&$.status!=="running"){await this.releaseSessionRuntime($,"session_stop");return}$.aborting=!0,$.agent.abort(Error("session_stop")),await this.shutdownSession($,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose(f="session_manager_dispose"){let $=[...this.sessions.values()];if($.length===0)return;await Promise.allSettled($.map((J)=>J.interactive&&J.status!=="running"?this.releaseSessionRuntime(J,f):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:f,endReason:"disposed"}))),this.usageBySession.clear()}async getSession(f){let $=this.sessions.get(f);if($)return a9($);let J=f.trim();if(!J)return;let H=await this.getRow(J);if(H)return Y8(H);let W=await this.readManifest(J);return W?zJ(W):void 0}async listSessions(f=200){let J=(await this.listRows(f)).map(Y8),H=new Set(J.map((W)=>W.sessionId));for(let W of this.sessions.values()){if(H.has(W.sessionId))continue;J.unshift(a9(W))}return J.slice(0,f)}async deleteSession(f){if(this.sessions.has(f))await this.stopSession(f);let $=await this.invoke("deleteSession",f);if($.deleted)this.usageBySession.delete(f);return $.deleted}async updateSession(f,$){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:f,prompt:$.prompt,metadata:$.metadata,title:$.title}))?.updated===!0}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.getRow($);if(J?.messagesPath)return u$(J.messagesPath);let H=await this.readManifest($);return u$(H?.messages_path)}async dispatchHookEvent(f){await QP(f,{queueSpawnRequest:($)=>this.invokeOptional("queueSpawnRequest",$),upsertSubagentSessionFromHook:($)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",$),appendSubagentHookAudit:($,J)=>this.invokeOptional("appendSubagentHookAudit",$,J),applySubagentStatus:($,J)=>this.invokeOptional("applySubagentStatus",$,J)})}subscribe(f,$){return this.events.subscribe(f,$)}async updateSessionModel(f,$){let J=this.getSessionOrThrow(f);J.config.modelId=$,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:$}),J.agent.updateConnection({modelId:$})}handlePluginEvent(f,$,J){return this.eventBridge.handlePluginEvent(f,$,J)}async executeTurn(f,$){let J=await this.prepareTurnInput(f,$),H=J.prompt.trim();if(!H)throw Error("prompt cannot be empty");if(!f.artifacts&&!f.pendingPrompt)f.pendingPrompt=H;await this.ensureSessionPersisted(f),await this.syncOAuthCredentials(f),await this.markTurnRunning(f);let W=await this.executeAgentTurn(f,H,J.userImages,J.userFiles);while(p5(f,W.finishReason)){let Q=await i5(f);if(Q.length===0)break;let Z=n5(f,Q);W=await this.executeAgentTurn(f,Z)}return W}async completeInteractiveTurn(f,$){if(Z4(f))return;let J=$==="aborted"||f.aborting,H=$==="error";await this.updateStatus(f,J?"cancelled":H?"failed":"completed",H?1:0),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$,ts:Date.now()}}),f.aborting=!1}async completeAbortedInteractiveTurn(f){let $=new Date,J=f.agent.getMessages();return f.persistedMessages=J,f.started=f.started||J.length>0,await this.completeInteractiveTurn(f,"aborted"),{text:"",usage:p0(),messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:f.config.modelId,provider:f.config.providerId},startedAt:$,endedAt:$,durationMs:0}}async executeAgentTurn(f,$,J,H){let W=f.started||f.agent.getMessages().length>0,Q=f.persistedMessages??f.agent.getMessages(),Z=this.usageBySession.get(f.sessionId)??p0();f.turnUsageBaseline=Z,x4(f.config.telemetry,f.sessionId,f.config.mode),Z1(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,model:f.config.modelId,source:"user",mode:f.config.mode,...this.getSessionAgentTelemetryIdentity(f)});try{let j=W?()=>f.agent.continue($,J,H):()=>f.agent.run($,J,H),P=await this.runWithAuthRetry(f,j,Q);f.started=!0;let X=D6(P.messages,P,Q);f.persistedMessages=X;let V=i0(Z,P.usage);return this.usageBySession.set(f.sessionId,V),await this.persistSessionMetadata(f.sessionId,(Y)=>({...Y??{},totalCost:V.totalCost})),await this.invoke("persistSessionMessages",f.sessionId,X,f.config.systemPrompt),this.observeTaskCompletionTool(f,P),P}catch(j){throw await this.invoke("persistSessionMessages",f.sessionId,f.agent.getMessages(),f.config.systemPrompt),j}finally{f.turnUsageBaseline=void 0}}observeTaskCompletionTool(f,$){if(f.submitAndExitObserved)return;if(!$.toolCalls.some((H)=>H.name===ff.SUBMIT_AND_EXIT&&H.error===void 0))return;f.submitAndExitObserved=!0,_2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity(f)})}async prepareTurnInput(f,$){let J=n0(f.config),H=ZL($.prompt).trim();if(!H)return{prompt:"",userImages:$.userImages,userFiles:this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles)};let W=await F1(H,J);jj(f.config.telemetry,W);let Q=j4(W.prompt,f.config.mode),Z=this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles),j=this.resolveAbsoluteFilePaths(J,W.matchedFiles),P=Array.from(new Set([...Z,...j]));return{prompt:Q,userImages:$.userImages,userFiles:P.length>0?P:void 0}}async ensureSessionPersisted(f){if(f.artifacts)return;let $=n0(f.config);f.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:f.sessionId,source:f.source,pid:process.pid,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:$,teamName:f.config.teamName,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,prompt:f.pendingPrompt,metadata:f.sessionMetadata,startedAt:f.startedAt})}async markTurnRunning(f){if(f.status==="running")return;await this.updateStatus(f,"running",null)}async persistSessionMetadata(f,$){let J=this.sessions.get(f),H=await this.invokeOptionalValue("readSessionManifest",f)??J?.artifacts?.manifest,W=$(H?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:f,metadata:W}))?.updated===!1)return;J.sessionMetadata=W,J.artifacts.manifest.metadata=W}async finalizeSingleRun(f,$){if(Z4(f))return;let J=$==="aborted"||f.aborting,H=$==="error";await this.shutdownSession(f,{status:J?"cancelled":H?"failed":"completed",exitCode:H?1:0,shutdownReason:H?"session_error":"session_complete",endReason:$})}async failSession(f){await this.shutdownSession(f,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession(f,$){if($.status==="completed"&&!f.submitAndExitObserved)_2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity(f)});wJ(f);let J=[],H=(W,Q)=>{J.push(Q),f.config.logger?.log("Session shutdown cleanup failed",{sessionId:f.sessionId,stage:W,error:Q,severity:"warn"})};if(f.artifacts){try{await this.updateStatus(f,$.status,$.exitCode)}catch(W){H("update_status",W)}try{await f.agent.shutdown($.shutdownReason)}catch(W){H("agent_shutdown",W)}}try{await Promise.resolve(f.runtime.shutdown($.shutdownReason))}catch(W){H("runtime_shutdown",W)}try{await f.pluginSandboxShutdown?.()}catch(W){H("plugin_sandbox_shutdown",W)}if(this.sessions.delete(f.sessionId),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$.endReason,ts:Date.now()}}),J.length>0&&$.status==="failed")throw J[0]}async releaseSessionRuntime(f,$){let J=[],H=(W,Q)=>{J.push(Q),f.config.logger?.log("Session runtime cleanup failed",{sessionId:f.sessionId,stage:W,error:Q,severity:"warn"})};try{await f.agent.shutdown($)}catch(W){H("agent_shutdown",W)}try{await Promise.resolve(f.runtime.shutdown($))}catch(W){H("runtime_shutdown",W)}try{await f.pluginSandboxShutdown?.()}catch(W){H("plugin_sandbox_shutdown",W)}if(this.sessions.delete(f.sessionId),J.length>0)throw J[0]}async updateStatus(f,$,J){if(!f.artifacts)return;let H=await this.invoke("updateSessionStatus",f.sessionId,$,J);if(!H.updated)return;let W=await this.invokeOptionalValue("readSessionManifest",f.sessionId)??f.artifacts.manifest;if(W.status=$,$==="running")delete W.ended_at,W.exit_code=null;else W.ended_at=H.endedAt??s(),W.exit_code=typeof J==="number"?J:null;f.artifacts.manifest=W,f.status=$,f.updatedAt=H.endedAt??s(),f.endedAt=$==="running"?null:W.ended_at,f.exitCode=W.exit_code,await this.invoke("writeSessionManifest",f.artifacts.manifestPath,W),this.emitStatus(f.sessionId,$)}async runWithAuthRetry(f,$,J){try{return await $()}catch(H){if(!QL(H,f.config.providerId))throw H;return await this.syncOAuthCredentials(f,{forceRefresh:!0}),f.agent.restore(J),$()}}async syncOAuthCredentials(f,$){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:f.config.providerId,forceRefresh:$?.forceRefresh})}catch(H){if(H instanceof eJ)throw Error(`${H.providerId} requires re-authentication.`);throw H}if(!J?.apiKey||f.config.apiKey===J.apiKey)return;f.config.apiKey=J.apiKey,f.agent.updateConnection({apiKey:J.apiKey}),f.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),f.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow(f){let $=this.sessions.get(f);if(!$)throw Error(`session not found: ${f}`);return $}resolveAbsoluteFilePaths(f,$){if(!$||$.length===0)return[];let J=$.map((H)=>H.trim()).filter((H)=>H.length>0).map((H)=>JL(H)?H:HL(f,H));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity(f){return T0({agentId:f.agent.getAgentId(),conversationId:f.agent.getConversationId(),teamId:f.runtime.teamRuntime?.getTeamId(),teamName:f.runtime.teamRuntime?.getTeamName(),teamRole:f.runtime.teamRuntime?"lead":void 0})}emitStatus(f,$){this.emitSessionSnapshot(f),this.emit({type:"status",payload:{sessionId:f,status:$}})}async emitSessionSnapshot(f){let $=await this.getSession(f);if(!$)return;this.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J0({session:$,messages:await this.readSessionMessages(f),usage:this.usageBySession.get(f)})}})}emit(f){this.events.emit(f)}async listRows(f){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor(f)),yV))}async getRow(f){let $=f.trim();if(!$)return;return(await this.listRows(yV)).find((H)=>H.sessionId===$)}async readManifest(f){let $=f.trim();if(!$)return;return await this.invokeOptionalValue("readSessionManifest",$)}invoke(f,...$){return BV(this.sessionService,f,...$)}invokeOptional(f,...$){return AV(this.sessionService,f,...$)}invokeOptionalValue(f,...$){return RV(this.sessionService,f,...$)}}function XL(f){return{text:f.text,usage:f.usage,inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function VL(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}function WV(f={}){let $=new j0({sessionService:new Z0(new W0),fetch:f.fetch,telemetry:f.telemetry});return{async startSession(J){let H=(J.cwd?.trim()||J.workspaceRoot).trim(),W=await $.startSession({source:J.source?.trim()||Vf.CLI,interactive:!1,config:{providerId:PL(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:H,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:VL(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(J,H){let W=await $.runTurn({sessionId:J,prompt:H.prompt,userImages:H.attachments?.userImages,userFiles:H.attachments?.userFiles?.map((Q)=>Q.content)});if(!W)throw Error("local hub schedule runtime returned no turn result");return{result:XL(W)}},async abortSession(J){return await $.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function YL(f){if(typeof f==="string")return f.trim()||void 0;if(!Array.isArray(f))return;return f.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
700
- `).trim()||void 0}var KV=120,e9="...";function h4(f){let $=f.trim();if(!$)return"";if(Buffer.byteLength($,"utf8")<=KV)return $;let J=KV-Buffer.byteLength(e9,"utf8");if(J<=0)return e9;let H="";for(let W of $){if(Buffer.byteLength(H+W,"utf8")>J)break;H+=W}return`${H}${e9}`}async function UV(f){let $=f?.sessionId?.trim()||"unknown",J=typeof f?.metadata?.messagesPath==="string"?f.metadata.messagesPath:void 0,W=[...await u$(J)].reverse().find((P)=>P.role==="assistant"),Q=W?YL(W.content):void 0,Z=f?.workspaceRoot?.trim()||"workspace",j=typeof f?.metadata?.prompt==="string"?f.metadata.prompt.trim():Z;return{title:`Task completed (${$})`,body:h4(Q&&Q.length>0?Q:j.length>0?j:Z),severity:"info"}}import{createSessionId as gL}from"@cline/shared";import{createSessionId as FL}from"@cline/shared";import{createSessionId as RL}from"@cline/shared";function BL(f){switch(f){case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function AL(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):{};if(f.parentSessionId?.trim())$.parentSessionId=f.parentSessionId;if(f.parentAgentId?.trim())$.parentAgentId=f.parentAgentId;if(f.agentId?.trim())$.agentId=f.agentId;if(f.conversationId?.trim())$.conversationId=f.conversationId;if(f.messagesPath?.trim())$.messagesPath=f.messagesPath;if(f.prompt?.trim())$.prompt=f.prompt;if(f.provider?.trim())$.provider=f.provider;if(f.model?.trim())$.model=f.model;if(f.source?.trim())$.source=f.source;if(typeof f.pid==="number")$.pid=f.pid;return Object.keys($).length>0?$:void 0}function $H(f,$){return{sessionId:f.sessionId,workspaceRoot:f.workspaceRoot,cwd:f.cwd,createdAt:Date.parse(f.startedAt),updatedAt:Date.parse(f.updatedAt),createdByClientId:$?.createdByClientId??"hub",status:BL(f.status),participants:$?[...$.participants.values()]:[],metadata:AL(f),runtimeOptions:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,mode:typeof f.metadata?.mode==="string"?f.metadata.mode:void 0,systemPrompt:typeof f.metadata?.systemPrompt==="string"?f.metadata.systemPrompt:void 0},runtimeSession:f.agentId?{agentId:f.agentId,team:f.teamName?{teamId:f.teamName}:void 0}:void 0}}function v(f,$){return{version:f.version,requestId:f.requestId,ok:!0,...$!==void 0?{payload:$}:{}}}function m(f,$,J){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:$,message:J}}}function JH(f){return f&&typeof f==="object"&&!Array.isArray(f)?f:void 0}function Mf(f){if(typeof f.payload?.sessionId==="string")return f.payload.sessionId.trim();return f.sessionId?.trim()??""}function t$(f,$,J){return{version:"v1",event:f,eventId:RL("hevt_"),sessionId:J,timestamp:Date.now(),payload:$}}async function If(f,$){let J=await f.sessionHost.getSession($);if(!J)return;return $H(J,f.sessionState.get($))}async function xf(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let[H,W]=await Promise.all([typeof f.sessionHost.readSessionMessages==="function"?f.sessionHost.readSessionMessages($):[],f.sessionHost.getAccumulatedUsage?.($)]);return J0({session:J,messages:H,usage:W})}function HH(f,$,J,H,W={}){let Q=f.sessionState.get($);if(Q){if(W.interactive!==void 0)Q.interactive=W.interactive;if(!Q.participants.has(J))Q.participants.set(J,{clientId:J,attachedAt:Date.now(),role:H});return Q}let Z={createdByClientId:J,interactive:W.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:H}]])};return f.sessionState.set($,Z),Z}async function f3(f,$){let J=FL("approval_"),H=$.sessionId;if(f.sessionState.get(H)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((Q)=>{f.pendingApprovals.set(J,{sessionId:H,resolve:Q}),f.publish(f.buildEvent("approval.requested",{approvalId:J,sessionId:$.sessionId,agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:JSON.stringify($.input??null),policy:$.policy},H))})}function $3(f,$,J){let H=f.pendingApprovals.get($);if(!H)return;return f.pendingApprovals.delete($),H.resolve(J),{sessionId:H.sessionId}}function J3(f,$,J){let H=0;for(let[W,Q]of[...f.pendingApprovals.entries()]){if(!$({approvalId:W,sessionId:Q.sessionId}))continue;f.pendingApprovals.delete(W),Q.resolve({approved:!1,reason:J}),f.publish(f.buildEvent("approval.resolved",{approvalId:W,approved:!1,cancelled:!0,reason:J},Q.sessionId)),H+=1}return H}async function GV(f,$){let J=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"";if(!f.pendingApprovals.get(J))return m($,"approval_not_found",`Unknown approval: ${J}`);let W=typeof $.payload?.reason==="string"?$.payload.reason:$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)&&typeof $.payload.payload.reason==="string"?$.payload.payload.reason:void 0,Q=$.payload?.approved===!0,Z=$3(f,J,{approved:Q,reason:W});if(!Z)return m($,"approval_not_found",`Unknown approval: ${J}`);return f.publish(f.buildEvent("approval.resolved",{approvalId:J,approved:Q,reason:W},Z.sessionId)),v($,{approvalId:J,approved:Q})}import{createSessionId as UL}from"@cline/shared";function yL(f){if(f instanceof Error)return{name:f.name,message:f.message,stack:f.stack};if(f===void 0)return;return f}var hV={debug:10,info:20,warn:30,error:40,silent:50};function KL(){let f=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if(f==="debug"||f==="info"||f==="warn"||f==="error"||f==="silent")return f;return process.env.VITEST?"error":"info"}function x(f,$,J={}){if(hV[f]<hV[KL()])return;let H=JSON.stringify({ts:new Date().toISOString(),level:f,component:"hub",message:$,...Object.fromEntries(Object.entries(J).map(([W,Q])=>[W,yL(Q)]).filter(([,W])=>W!==void 0))});if(f==="error"||f==="warn"){console.error(`[hub] ${H}`);return}console.log(`[hub] ${H}`)}function H3(f,$){let J=$ instanceof Error?$.stack||$.message:String($);x("error",f,{error:J})}async function TV(f,$,J,H,W,Q){let Z=UL("capreq_"),j=performance.now();return x("info","capability.request.start",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:W}),await new Promise((P,X)=>{f.pendingCapabilityRequests.set(Z,{sessionId:$,targetClientId:W,capabilityName:J,onProgress:Q,resolve:(V)=>{if(x(V.ok?"info":"warn","capability.request.end",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:W,ok:V.ok,error:V.error,durationMs:Math.round(performance.now()-j)}),!V.ok){X(Error(V.error||`Capability ${J} was rejected by ${W}.`));return}P(V.payload)}}),f.publish(f.buildEvent("capability.requested",{requestId:Z,targetClientId:W,capabilityName:J,payload:H},$)),x("info","capability.request.published",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:W})})}function DV(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",H=f.pendingCapabilityRequests.get(J);if(!H)return m($,"capability_not_found",`Unknown capability request: ${J}`);if(($.clientId?.trim()||"")!==H.targetClientId)return m($,"capability_wrong_client",`Capability request ${J} is owned by ${H.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==H.sessionId)return m($,"capability_wrong_session",`Capability request ${J} belongs to session ${H.sessionId}`);let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{};return H.onProgress?.(Q),v($,{requestId:J})}function j$(f,$,J){let H=0;for(let[W,Q]of[...f.pendingCapabilityRequests.entries()]){if(!$({requestId:W,...Q}))continue;f.pendingCapabilityRequests.delete(W),x("warn","capability.request.cancelled",{requestId:W,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,reason:J}),Q.resolve({ok:!1,error:J}),f.publish(f.buildEvent("capability.resolved",{requestId:W,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,ok:!1,cancelled:!0,error:J},Q.sessionId)),H+=1}return H}async function MV(f,$){let J=typeof $.payload?.sessionId==="string"?$.payload.sessionId.trim():$.sessionId?.trim()||"",H=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName.trim():"",W=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId.trim():"";if(!J||!H||!W)return m($,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},Z=await f.requestCapability(J,H,Q,W);return v($,Z)}catch(Q){return m($,"capability_request_failed",Q instanceof Error?Q.message:String(Q))}}function _V(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",H=f.pendingCapabilityRequests.get(J);if(!H)return m($,"capability_not_found",`Unknown capability request: ${J}`);let W=$.clientId?.trim()||"";if(W!==H.targetClientId)return m($,"capability_wrong_client",`Capability request ${J} is owned by ${H.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==H.sessionId)return m($,"capability_wrong_session",`Capability request ${J} belongs to session ${H.sessionId}`);f.pendingCapabilityRequests.delete(J);let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:void 0,Z=typeof $.payload?.error==="string"?$.payload.error:void 0,j=$.payload?.ok===!0;return x(j?"info":"warn","capability.respond",{requestId:J,sessionId:H.sessionId,capabilityName:H.capabilityName,targetClientId:H.targetClientId,respondedByClientId:W,ok:j,error:Z}),H.resolve({ok:j,payload:Q,error:Z}),f.publish(f.buildEvent("capability.resolved",{requestId:J,capabilityName:H.capabilityName,targetClientId:H.targetClientId,respondedByClientId:W,ok:j,payload:Q,error:Z},H.sessionId)),v($,{requestId:J,ok:j})}import{createSessionId as GL}from"@cline/shared";function LV(f,$){let J=$.payload,H=J?.clientId?.trim()||$.clientId?.trim()||GL("client_");return f.clients.set(H,{clientId:H,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),f.publish(f.buildEvent("hub.client.registered",{clientId:H,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),v($,{clientId:H})}function zV(f,$){let J=$.clientId?.trim(),H=J?f.clients.get(J):void 0;if(!J||!H)return m($,"client_not_found","Client is not registered with this hub.");let W=JH($.payload?.metadata);if(H.lastSeenAt=Date.now(),W)H.metadata=JSON.parse(JSON.stringify(W));return v($)}function OV(f,$,J){let H=$.clientId?.trim();if(H)f.clients.delete(H),J(H),f.publish(f.buildEvent("hub.client.disconnected",{clientId:H}));return v($)}function NV(f,$){return v($,{clients:[...f.clients.values()]})}var hL=30000;function TL(f){if(f==="aborted")return"run.aborted";if(f==="error"||f==="failed")return"run.failed";return"run.completed"}function DL(f){if(f.finishReason!=="error")return;return f.text.trim()||void 0}function ML(f){let $=typeof f.timeoutMs==="number"?f.timeoutMs:typeof f.timeout_ms==="number"?f.timeout_ms:void 0;if($&&Number.isFinite($)&&$>0)return Math.floor($);let J=typeof f.timeoutSeconds==="number"?f.timeoutSeconds:typeof f.timeout_seconds==="number"?f.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function _L(f,$,J,H){let W=performance.now(),Q=!1,Z={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:J.sessionId,timeoutMs:H},j=setInterval(()=>{if(Q)return;let V=Math.round(performance.now()-W);x("warn","run.heartbeat",{...Z,elapsedMs:V}),f.publish(f.buildEvent("run.heartbeat",{requestId:$.requestId,elapsedMs:V,...H?{timeoutMs:H}:{}},J.sessionId))},hL),P=f.sessionHost.runTurn(J);P.then((V)=>{if(!Q)return;x("warn","run.late_end",{...Z,elapsedMs:Math.round(performance.now()-W),finishReason:V?.finishReason})},(V)=>{if(!Q)return;x("error","run.late_error",{...Z,elapsedMs:Math.round(performance.now()-W),error:V})});let X;try{if(!H)return await P;return await Promise.race([P,new Promise((V,Y)=>{X=setTimeout(()=>{let B=`Hub run ${$.command} timed out after ${H}ms.`;Q=!0,clearInterval(j),Y(Error(B)),x("error","run.timeout",{...Z,elapsedMs:Math.round(performance.now()-W)}),J3(f,(A)=>A.sessionId===J.sessionId,B),j$(f,(A)=>A.sessionId===J.sessionId,B),f.sessionHost.abort(J.sessionId,B).catch((A)=>{x("error","run.timeout_abort_failed",{...Z,error:A})})},H)})])}finally{if(Q=!0,clearInterval(j),X)clearTimeout(X)}}async function qV(f,$){let J=Mf($),H=$.payload&&typeof $.payload==="object"?$.payload:{},W=typeof H.prompt==="string"?H.prompt:typeof H.input==="string"?H.input:"";if(!W.trim())return m($,"invalid_session_input","session input requires a prompt string");f.publish(f.buildEvent("run.started",void 0,J));let Q=H.attachments&&typeof H.attachments==="object"&&!Array.isArray(H.attachments)?H.attachments:void 0,Z=Array.isArray(Q?.userFiles)?Q.userFiles.filter((V)=>typeof V==="string"):void 0,j=ML(H);f.suppressNextTerminalEventBySession.set(J,"run.start.reply");let P;try{P=await _L(f,$,{sessionId:J,prompt:W,delivery:H.delivery==="queue"||H.delivery==="steer"?H.delivery:void 0,userImages:Array.isArray(Q?.userImages)?Q.userImages:void 0,userFiles:Z,timeoutMs:j},j)}catch(V){if(f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J);throw f.publish(f.buildEvent("run.failed",{reason:"error",error:V instanceof Error?V.message:String(V)},J)),V}if(P){let V=await xf(f,J),Y=DL(P);if(f.publish(f.buildEvent(TL(P.finishReason),{reason:P.finishReason,...Y?{error:Y}:{},result:P,...V?{snapshot:V}:{}},J)),f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J)}else f.suppressNextTerminalEventBySession.delete(J);let X=await xf(f,J);return v($,P||X?{...P?{result:P}:{},...X?{snapshot:X}:{}}:void 0)}async function bV(f,$){let J=Mf($),H=typeof $.payload?.reason==="string"?$.payload.reason:"Run was aborted before pending approval or capability request was resolved.";return J3(f,(W)=>W.sessionId===J,H),await f.sessionHost.abort(J,$.payload?.reason),j$(f,(W)=>W.sessionId===J,H),f.publish(f.buildEvent("run.aborted",{reason:H},J)),v($,{applied:!0})}async function wV(f,$){let J=Q2($.payload?.payload);if(!J)return m($,"invalid_hook_payload","session.hook requires a valid hook event payload");return await f.sessionHost.dispatchHookEvent(J),v($,{applied:!0})}async function CV(f,$){switch($.type){case"chunk":return;case"agent_event":LL(f,$);return;case"hook":if($.payload.hookEventName==="tool_call")f.publish(f.buildEvent("tool.started",{toolName:$.payload.toolName},$.payload.sessionId));else if($.payload.hookEventName==="tool_result")f.publish(f.buildEvent("tool.finished",{toolName:$.payload.toolName},$.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:$.payload.sessionId,summary:$.payload.summary,lastEvent:$.payload.lifecycle};f.publish(f.buildEvent("team.progress",J,$.payload.sessionId));return}case"pending_prompts":f.publish(f.buildEvent("session.pending_prompts",{sessionId:$.payload.sessionId,prompts:$.payload.prompts},$.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:$.payload.id,prompt:$.payload.prompt,delivery:$.payload.delivery,attachmentCount:$.payload.attachmentCount};f.publish(f.buildEvent("session.pending_prompt_submitted",{sessionId:$.payload.sessionId,prompt:J},$.payload.sessionId));return}case"session_snapshot":f.publish(f.buildEvent("session.updated",{sessionId:$.payload.sessionId,snapshot:$.payload.snapshot},$.payload.sessionId));return;case"status":{let[J,H]=await Promise.all([If(f,$.payload.sessionId),xf(f,$.payload.sessionId)]);if(J)f.publish(f.buildEvent("session.updated",{session:J,...H?{snapshot:H}:{}},$.payload.sessionId));return}case"ended":await zL(f,$);return;default:return}}function LL(f,$){let{sessionId:J,event:H}=$.payload;if(H.type==="iteration_start"){f.publish(f.buildEvent("iteration.started",{iteration:H.iteration},J));return}if(H.type==="iteration_end"){f.publish(f.buildEvent("iteration.finished",{iteration:H.iteration,hadToolCalls:H.hadToolCalls,toolCallCount:H.toolCallCount},J));return}if(H.type==="content_start"){if(H.contentType==="text"&&typeof H.text==="string"&&H.text.length>0){f.publish(f.buildEvent("assistant.delta",{text:H.text},J));return}if(H.contentType==="reasoning"){if(H.redacted&&!H.reasoning){f.publish(f.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof H.reasoning==="string"&&H.reasoning.length>0)f.publish(f.buildEvent("reasoning.delta",{text:H.reasoning,redacted:H.redacted===!0},J));return}if(H.contentType==="tool"){f.publish(f.buildEvent("tool.started",{toolCallId:H.toolCallId,toolName:H.toolName,input:H.input},J));return}}if(H.type==="content_end"){switch(H.contentType){case"text":f.publish(f.buildEvent("assistant.finished",{text:H.text},J));break;case"reasoning":f.publish(f.buildEvent("reasoning.finished",{reasoning:H.reasoning},J));break;case"tool":f.publish(f.buildEvent("tool.finished",{toolCallId:H.toolCallId,toolName:H.toolName,output:H.output,error:H.error},J));break}return}if(H.type==="done")f.publish(f.buildEvent("agent.done",{reason:H.reason,text:H.text,iterations:H.iterations,usage:H.usage},J))}async function zL(f,$){let J=f.suppressNextTerminalEventBySession.get($.payload.sessionId),H=J===$.payload.reason||J==="run.start.reply";if(H)f.suppressNextTerminalEventBySession.delete($.payload.sessionId);let[W,Q]=await Promise.all([If(f,$.payload.sessionId),xf(f,$.payload.sessionId)]);if($.payload.reason==="completed"){let Z=await UV(W);f.publish(f.buildEvent("ui.notify",Z,$.payload.sessionId))}if(H)return;f.publish(f.buildEvent($.payload.reason==="aborted"?"run.aborted":$.payload.reason==="error"||$.payload.reason==="failed"?"run.failed":"run.completed",{reason:$.payload.reason,...Q?{snapshot:Q}:{}},$.payload.sessionId))}import{createSessionId as SV,parseRuntimeConfigExtensions as kV}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as fv,HUB_COMPACTION_CAPABILITY as $v,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Jv,HUB_HOOK_CAPABILITY_PREFIX as Hv,HUB_MISTAKE_LIMIT_CAPABILITY as Wv,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Qv,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Zv,isHubToolExecutorName as OL}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Yv,HUB_COMPACTION_CAPABILITY as Bv,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Av,HUB_HOOK_CAPABILITY_PREFIX as Rv,HUB_MISTAKE_LIMIT_CAPABILITY as Fv,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as yv,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Kv}from"@cline/shared";var NL=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function s$(f){return f&&typeof f==="object"&&!Array.isArray(f)?JSON.parse(JSON.stringify(f)):void 0}function qL(f,$){let J=typeof f.name==="string"?f.name.trim():"",H=typeof f.description==="string"?f.description:"",W=typeof f.capabilityName==="string"?f.capabilityName.trim():"",Q=s$(f.inputSchema);if(!J||!H||!Q||!W||$.has(W))return;return $.add(W),{kind:"tool",capabilityName:W,name:J,description:H,inputSchema:Q,...s$(f.lifecycle)?{lifecycle:s$(f.lifecycle)}:{}}}function Q3(f){if(!Array.isArray(f))return[];let $=[],J=new Set;for(let H of f){if(!H||typeof H!=="object"||Array.isArray(H))continue;let W=H,Q=W.kind,Z=typeof W.capabilityName==="string"?W.capabilityName.trim():"";if(!Z||J.has(Z))continue;if(Q==="tool"){let j=qL(W,J);if(j)$.push(j);continue}if(Q==="toolExecutor"){let j=W.executor;if(!OL(j))continue;J.add(Z),$.push({kind:"toolExecutor",capabilityName:Z,executor:j});continue}if(Q==="hook"){let j=typeof W.name==="string"?W.name.trim():"";if(!j)continue;J.add(Z),$.push({kind:"hook",capabilityName:Z,name:j});continue}if(Q==="compaction"){J.add(Z),$.push({kind:"compaction",capabilityName:Z,...s$(W.config)?{config:s$(W.config)}:{}});continue}if(Q==="checkpoint"){J.add(Z),$.push({kind:"checkpoint",capabilityName:Z,...s$(W.config)?{config:s$(W.config)}:{}});continue}if(Q==="mistakeLimit"){J.add(Z),$.push({kind:"mistakeLimit",capabilityName:Z});continue}if(Q==="userInstructionService")J.add(Z),$.push({kind:"userInstructionService",capabilityName:Z})}return $}function EV(f){return{agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,metadata:f.metadata}}function bL(f){return Object.hasOwn(f,"update")?f.update:f}function _4(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function wL(f){let $=(f??[]).map(_4).filter(Boolean);return $.length>0?new Set($):void 0}function CL(f,$,J){if(!J)return!0;let H=_4(f),W=_4($),Q=H.includes(":")?H.split(":").at(-1)??H:H,Z=W.includes(":")?W.split(":").at(-1)??W:W;return J.has(H)||J.has(W)||J.has(Q)||J.has(Z)}function W3(f,$){let J=wL($);return f.records.skill.map((H)=>({id:H.id,name:H.item.name,description:"description"in H.item&&typeof H.item.description==="string"?H.item.description:void 0,disabled:H.item.disabled===!0,skill:H.item})).filter((H)=>CL(H.id,H.name,J))}function EL(f,$){let J=async(H,W)=>{let Q=_4(H),j=W3(f,$).filter((B)=>B.id===Q||_4(B.name)===Q||B.id.endsWith(`:${Q}`)).filter((B)=>!B.disabled);if(j.length!==1)return j.length>1?`Skill "${H}" is ambiguous. Use one of: ${j.map((B)=>B.id).join(", ")}`:`Skill "${H}" not found.`;let P=j[0].skill,X=W?.trim(),V=X?`
701
- <command-args>${X}</command-args>`:"",Y=P.description?.trim()?`Description: ${P.description.trim()}
702
-
703
- `:"";return`<command-name>${P.name}</command-name>${V}
691
+ version = team_outcome_fragments.version + 1`,[W,Q.outcomeId,Q.id,Q.section,Q.sourceAgentId,Q.sourceRunId??null,Q.content,Q.status,Q.reviewedBy??null,Q.reviewedAt?Q.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted(f,$){let J=B2(f),W=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(W.length===0)return[];let H=U9();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
692
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[$,H,J]),W.map((Q)=>Q.run_id)}handleTeamEvent(f,$){this.appendTeamEvent(f,$.type,$)}}function G9(f={}){try{let $=new t$(f);return $.init(),$}catch{let $=new T4({teamDir:f.teamDir});return $.init(),$}}function T9(f,$){return MM(f,$)}function hM(f,$){let J=$?.["*"]??{},W=$?.[f]??{};return{...J,...W}.enabled!==!1}function OM(f,$){return f.filter((J)=>hM(J.name,$))}function kA(f,$){return U$(OM(f,$))}function xJ(){return`team-${LM(5)}`}function D9(f,$,J,W,H,Q,Z,j){let X=kf[L0({mode:J})],A=T1($,W,J,H??G1);return kA(b$({cwd:f,...X,enableSkills:!!Z,...A,executors:{...Z?{skills:Z}:{},...j??{}}}),Q)}function zM(f){return D9(f.cwd,f.providerId,f.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,NM,f.toolExecutors).some(($)=>$.name==="skills")}var NM=async()=>"";async function qM(f){let $=P$();if(!H2({filePath:$}))return{tools:[]};let J=new i$({clientFactory:W2()}),W;try{W=await Q2(J,{filePath:$})}catch(j){await J.dispose().catch(()=>{});let X=j instanceof Error?j.message:String(j);return f?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${X}`),{tools:[]}}let H=W.filter((j)=>j.disabled!==!0),Q=await Promise.allSettled(H.map((j)=>Z2({serverName:j.name,provider:J}))),Z=[];for(let[j,X]of Q.entries())if(X.status==="fulfilled")Z.push(...X.value);else{let A=X.reason instanceof Error?X.reason.message:String(X.reason);f?.log(`[mcp] Failed to load tools from MCP server "${H[j].name}", skipping: ${A}`)}return{tools:Z,shutdown:async()=>{await J.dispose()}}}function wM(f,$){if(!f)return;for(let J of f.getTeammateIds())try{f.shutdownTeammate(J,$)}catch{}}function bM(f){if(f===void 0)return!0;switch(f){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function CM(f){let $=kf[L0({mode:f.mode})];return{sessionId:f.sessionId||"",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",enableTools:f.enableTools!==!1,enableSpawnAgent:f.enableSpawnAgent??$.enableSpawnAgent??!0,enableAgentTeams:f.enableAgentTeams??$.enableAgentTeams??!0,disableMcpSettingsTools:f.disableMcpSettingsTools===!0,yolo:f.yolo===!0,missionLogIntervalSteps:typeof f.missionLogIntervalSteps==="number"&&Number.isFinite(f.missionLogIntervalSteps)?f.missionLogIntervalSteps:3,missionLogIntervalMs:typeof f.missionLogIntervalMs==="number"&&Number.isFinite(f.missionLogIntervalMs)?f.missionLogIntervalMs:120000}}class Y2{teamRuntimeEntries=new Map;async build(f){let{config:$,hooks:J,extensions:W,logger:H,telemetry:Q,createSpawnTool:Z,onTeamRestored:j,userInstructionService:X,configExtensions:A,toolExecutors:P}=f,B=f.onTeamEvent??(()=>{}),Y=CM($),V=rf(),R=[],U=$.teamName?.trim()||xJ(),K=$.sessionId?.trim()||U,F=T9(A,"rules"),y=T9(A,"skills"),D=T9(A,"workflows"),M=F||y||D,T=!1,_=Boolean(X),L=X,q;if(!L&&M)L=Z$({skills:{workspacePath:$.cwd},rules:{workspacePath:$.cwd},workflows:{workspacePath:$.cwd}});if(L)await L.start().catch(()=>{});let Wf=Y.enableTools&&y&&Boolean(L)&&(_||L?.hasConfiguredSkills($.skills)===!0)&&zM({cwd:$.cwd,providerId:$.providerId,mode:Y.mode,modelId:$.modelId,toolRoutingRules:$.toolRoutingRules,toolPolicies:$.toolPolicies,toolExecutors:P}),Hf=L&&M?L.createExtension({includeRules:F,includeSkills:y,includeWorkflows:D,registerSkillsTool:Wf,allowedSkillNames:$.skills}):void 0,o=Hf?[...W??$.extensions??[],Hf]:W??$.extensions;if(Y.enableTools){if(R.push(...D9($.cwd,$.providerId,Y.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,P)),!Y.disableMcpSettingsTools){let r=await qM($.logger);R.push(...r.tools),q=r.shutdown}}let c,Gf=Y.enableAgentTeams?G9():void 0,E0=Gf?.loadRuntime(K),i=E0?.state,P0=E0?.teammates??[],S=new Map(P0.map((r)=>[r.agentId,r])),n=$.sessionId||U,B0,Y0=[],V$=!1,f1=_1({providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey??"",baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:J,extensions:o,logger:H??$.logger,telemetry:f.telemetry??$.telemetry,workspaceMetadata:$.workspaceMetadata});if(!this.teamRuntimeEntries.has(n))this.teamRuntimeEntries.set(n,{delegatedAgentConfigProvider:f1});let K2=()=>{if(!Y.enableAgentTeams)return;let r=this.teamRuntimeEntries.get(n)??{delegatedAgentConfigProvider:f1};if(this.teamRuntimeEntries.set(n,r),c=r.runtime,!c){if(c=new p$({teamName:U,leadAgentId:$.sessionId||"lead",missionLogIntervalSteps:Y.missionLogIntervalSteps,missionLogIntervalMs:Y.missionLogIntervalMs,onTeamEvent:($f)=>{if(B($f),c&&Gf){if($f.type==="teammate_spawned"&&$f.teammate?.rolePrompt){let V0={agentId:$f.agentId,rolePrompt:$f.teammate.rolePrompt,modelId:$f.teammate.modelId,maxIterations:$f.teammate.maxIterations};S.set(V0.agentId,V0)}if($f.type==="teammate_shutdown"&&!bM($f.reason))S.delete($f.agentId);Gf.handleTeamEvent(K,$f),Gf.persistRuntime(K,c.exportState(),Array.from(S.values()))}}}),i)c.hydrateState(i),V$=!0;r.runtime=c}if(!T){if(!c)return;T=!0;let $f=h1({runtime:c,leadAgentId:$.sessionId||"lead",restoredFromPersistence:Boolean(i),restoredTeammates:P0,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(V0)=>{Y0=V0,B0?.addTools(V0)},createBaseTools:Y.enableTools?()=>D9($.cwd,$.providerId,Y.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,P):void 0,teammateConfigProvider:f1});if(V$)c.recoverActiveRuns("runtime_recovered");if($f.restoredFromPersistence)j?.();R.push(...$f.tools)}return c};if(Y.enableSpawnAgent&&Z){let r=Z();R.push({...r,execute:async($f,V0)=>{return K2(),r.execute($f,V0)}})}if(Y.enableAgentTeams)K2();let C4=kA(R,$.toolPolicies),Q5=C4.some((r)=>r.name===Jf.SUBMIT_AND_EXIT&&r.lifecycle?.completesRun===!0),$1=Y.enableAgentTeams?()=>{let r=this.teamRuntimeEntries.get(n)?.runtime;if(!r)return;let $f=r.listTasks(),V0=$f.some((S0)=>S0.status==="in_progress"||S0.status==="pending"),D3=r.listRuns({}),hB=D3.some((S0)=>S0.status==="running"||S0.status==="queued");if(V0||hB){let S0=$f.filter((qf)=>qf.status==="in_progress"||qf.status==="pending").map((qf)=>`${qf.id} (${qf.status}): ${qf.title}`).join(", "),_3=D3.filter((qf)=>qf.status==="running"||qf.status==="queued").map((qf)=>`${qf.id} (${qf.status})`).join(", "),Z5=[];if(S0)Z5.push(`Unfinished tasks: ${S0}`);if(_3)Z5.push(`Active runs: ${_3}`);return`[SYSTEM] You still have team obligations. ${Z5.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,y2=Q5?{requireCompletionTool:!0,...$1?{completionGuard:$1}:{}}:$1?{completionGuard:$1}:void 0;return{tools:C4,logger:H??$.logger,telemetry:Q??$.telemetry,teamRuntime:c,teamRestoredFromPersistence:Boolean(i),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(n)?.delegatedAgentConfigProvider??f1,extensions:o,completionPolicy:y2,registerLeadAgent:(r)=>{if(B0=r,Y0.length>0)r.addTools(U$(Y0,[...V]))},shutdown:async(r)=>{if(wM(c,r),this.teamRuntimeEntries.delete(n),await q?.(),!_)L?.stop()}}}}var xA={};N(xA,{requestDesktopToolApproval:()=>M9});import{mkdir as EM,readFile as SM,unlink as kM,writeFile as IM}from"node:fs/promises";import{join as mA}from"node:path";function mM(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function xM(f){return new Promise(($)=>setTimeout($,f))}async function _9(f){try{await kM(f)}catch{}}async function M9(f,$={}){let J=$.approvalDir?.trim(),W=$.sessionId?.trim();if(!J||!W)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await EM(J,{recursive:!0});let H=mM(`${f.toolCallId}`),Q=mA(J,`${W}.request.${H}.json`),Z=mA(J,`${W}.decision.${H}.json`),j=$.nowIso??(()=>new Date().toISOString());await IM(Q,`${JSON.stringify({requestId:H,sessionId:W,createdAt:j(),toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,iteration:f.iteration,agentId:f.agentId,conversationId:f.conversationId},null,2)}
693
+ `,"utf8");let X=$.timeoutMs??300000,A=$.pollIntervalMs??200,P=Date.now();while(Date.now()-P<X){try{let B=await SM(Z,"utf8"),Y=JSON.parse(B),V={approved:Y.approved===!0,reason:typeof Y.reason==="string"?Y.reason:void 0};return await Promise.all([_9(Z),_9(Q)]),V}catch{}await xM(A)}return await _9(Q),{approved:!1,reason:"Tool approval request timed out"}}G0();var $P={};N($P,{updateLocalProvider:()=>rJ,saveLocalProviderSettings:()=>b9,saveLocalProviderOAuthCredentials:()=>k9,resolveLocalClineAuthToken:()=>I9,refreshProviderModelsFromSource:()=>C9,normalizeOAuthProvider:()=>E9,loginLocalProvider:()=>S9,listLocalProviders:()=>q9,getProviderConfigFields:()=>m9,getLocalProviderModels:()=>w9,ensureCustomProvidersLoaded:()=>dJ,deleteLocalProvider:()=>lJ,addLocalProvider:()=>N9});import*as Bf from"@cline/llms";import{getClineEnvironmentConfig as ZL,isOAuthProviderId as jL}from"@cline/shared";import{existsSync as gM,mkdirSync as vM,readFileSync as uM,writeFileSync as cM}from"node:fs";import{mkdir as dM,readFile as rM,writeFile as lM}from"node:fs/promises";import{dirname as L9,join as pM}from"node:path";import*as Of from"@cline/llms";import{ModelCapabilitySchema as iM,ProviderCapabilitySchema as nM,ProviderClientSchema as aM,ProviderProtocolSchema as tM}from"@cline/shared";import{z as p}from"zod";var sM=p.object({id:p.string().optional(),name:p.string().optional(),capabilities:p.array(iM).optional(),supportsVision:p.boolean().optional(),supportsAttachments:p.boolean().optional(),supportsReasoning:p.boolean().optional()}).passthrough(),oM=p.object({name:p.string(),baseUrl:p.string(),defaultModelId:p.string().optional(),protocol:tM.optional(),client:aM.optional(),capabilities:p.array(nM).optional(),modelsSourceUrl:p.string().optional()}).passthrough(),gA=p.object({provider:oM.optional(),models:p.record(p.string(),sM).optional()}).passthrough(),vA=p.object({version:p.literal(1),providers:p.record(p.string(),gA)}),eM=p.object({version:p.literal(1),providers:p.record(p.string(),p.unknown())}),gJ=new Set;function uA(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function s$(f){return pM(L9(f.getFilePath()),"models.json")}function vJ(){return{version:1,providers:{}}}function cA(f){let $=eM.safeParse(f);if(!$.success)return vJ();let J={};for(let[W,H]of Object.entries($.data.providers)){let Q=gA.safeParse(H);if(Q.success)J[W]=Q.data}return{version:1,providers:J}}function h9(f){if(!gM(f))return vJ();try{let $=uM(f,"utf8");return cA(JSON.parse($))}catch{}return vJ()}async function V2(f){try{let $=await rM(f,"utf8");return cA(JSON.parse($))}catch{}return vJ()}function dA(f,$){vM(L9(f),{recursive:!0});let J=vA.parse($);cM(f,`${JSON.stringify(J,null,2)}
694
+ `,"utf8")}async function uJ(f,$){await dM(L9(f),{recursive:!0});let J=vA.parse($);await lM(f,`${JSON.stringify(J,null,2)}
695
+ `,"utf8")}function rA(f,$){return{id:f,name:$.name??f,supportsAttachments:$.capabilities?.includes("files"),supportsVision:$.capabilities?.includes("images"),supportsReasoning:$.capabilities?.includes("reasoning")||$.thinkingConfig!=null}}function lA(f){if(!f||f.length===0)return;let $=new Set;if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("tools"))$.add("tools");return $.size>0?[...$]:void 0}function pA(f){let $=new Set;if(!f||f.length===0)return[...$];if(f.includes("streaming"))$.add("streaming");if(f.includes("tools"))$.add("tools");if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("vision"))$.add("images"),$.add("files");return[...$]}function fL(f){return f!=null&&typeof f.name==="string"&&typeof f.baseUrl==="string"}function iA(f,$){return f??$??"openai-chat"}function nA(f,$,J){return f??J??($==="openai-responses"?"openai":"openai-compatible")}function $L(f,$){let J=new Set($?.capabilities??[]);if($?.supportsVision)J.add("images");if($?.supportsAttachments)J.add("files");if($?.supportsReasoning)J.add("reasoning");return{id:f,name:$?.name??f,capabilities:J.size>0?[...J]:void 0}}function JL(f,$){for(let[J,W]of Object.entries($??{})){let H=W.id?.trim()||J.trim();if(!H)continue;Of.registerModel(f,H,$L(H,W))}}function WL(f,$,J){return{...$??{},id:f,name:$?.name??f,capabilities:$?.capabilities??J}}function HL(f){return Object.assign({},...Of.resolveProviderModelCatalogKeys(f).map((J)=>Of.getGeneratedModelsForProvider(J)))}function QL(f){let $=f.provider.trim();if(!$||Of.isBuiltInProviderId($))return;let J=f.baseUrl?.trim();if(!J)return;let W=Of.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],H=HL($),Q=pA(f.capabilities),Z=Q.length>0?Q:void 0,j=f.model?.trim(),X={...H,...W?.models??{}};if(j)X[j]=WL(j,X[j],Z);let A=Object.keys(X).filter(Boolean),P=j||A[0];if(!P)return;let B=iA(f.protocol,W?.provider.protocol),Y=nA(f.client,B,W?.provider.client);Of.registerProvider({provider:{id:$,name:W?.provider.name??uA($),description:W?.provider.description,protocol:B,client:Y,baseUrl:J,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:P,capabilities:lA(f.capabilities)??W?.provider.capabilities,source:"file"},models:X})}function cJ(f){for(let $ of Object.values(f.providers))QL($.settings)}function D4(f,$){let J=$.models??{};if(!fL($.provider)){JL(f,J);return}let W=pA($.provider.capabilities),H=Object.entries(J).map(([A,P])=>({id:P.id?.trim()||A.trim(),model:P})).filter(({id:A})=>A.length>0),Q=$.provider.defaultModelId?.trim()||H[0]?.id||"default",Z=iA($.provider.protocol,void 0),j=nA($.provider.client,Z,void 0),X=Object.fromEntries(H.map(({id:A,model:P})=>[A,{id:A,name:P.name??A,capabilities:W.length>0?W:void 0,status:"active"}]));Of.registerProvider({provider:{id:f,name:$.provider.name.trim()||uA(f),protocol:Z,client:j,baseUrl:$.provider.baseUrl,modelsSourceUrl:$.provider.modelsSourceUrl,defaultModelId:Q,capabilities:lA($.provider.capabilities),source:"file"},models:X})}function aA(f){let $=s$(f);if(gJ.has($))return;let J=h9($);for(let[W,H]of Object.entries(J.providers))D4(W,H);gJ.add($)}async function dJ(f){let $=s$(f);if(gJ.has($))return;let J=await V2($);for(let[W,H]of Object.entries(J.providers))D4(W,H);gJ.add($)}function XL(f){return f.apiKey??f.auth?.apiKey}function AL(f){return(f.auth?.accessToken?.trim()??"").length>0}function tA(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function PL(f){let $=f.split(/\s+/).filter(Boolean);if($.length===0)return"?";if($.length===1)return $[0].slice(0,2).toUpperCase();return`${$[0][0]}${$[1][0]}`.toUpperCase()}function BL(f){let $=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let W of f)J=J*31+W.charCodeAt(0)>>>0;return $[J%$.length]}function sA(f){return Object.entries(f).sort(([$],[J])=>$.localeCompare(J)).map(([$,J])=>rA($,J))}async function YL(f,$){let J=await Bf.getModelsForProvider(f);if(!$)return J;let W=await b8(f,{loadPrivateOnAuth:!0,failOnError:!1},$);return W?.knownModels?{...J,...W.knownModels}:J}function O9(f){return[...new Set((f??[]).map(($)=>$.trim()).filter(Boolean))]}function oA(f){let $=Object.entries(f??{}).filter(([J])=>J.trim().length>0);return $.length>0?Object.fromEntries($):void 0}function z9(f,$){let J=$?.includes("vision")??!1,W=$?.includes("reasoning")??!1;return Object.fromEntries(f.map((H)=>[H,{id:H,name:H,supportsVision:J,supportsAttachments:J,supportsReasoning:W}]))}async function eA(f){if(!f.shouldRecompute)return f.fallbackModelIds??[];let $=f.modelsSourceUrl?await u6(f.modelsSourceUrl,f.providerId):[];return[...new Set([...f.explicitModels??[],...$])]}function fP(f,$){let J=f.read(),W=!1;if(J.providers[$])delete J.providers[$],W=!0;if(J.lastUsedProvider===$)delete J.lastUsedProvider,W=!0;if(W)f.write(J);Bf.unregisterProvider($)}async function N9(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=$.baseUrl.trim(),H=$.apiKey?.trim()??"";if(!W&&!H){let R=s$(f);if((await V2(R)).providers[J]){let K=await lJ(f,{providerId:J});return{providerId:J,settingsPath:K.settingsPath,modelsPath:K.modelsPath,modelsCount:0}}return fP(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:R,modelsCount:0}}if(Bf.hasProvider(J))throw Error(`provider "${J}" already exists`);let Q=$.name.trim();if(!Q)throw Error("name is required");if(!W)throw Error("baseUrl is required");let Z=O9($.models),j=$.modelsSourceUrl?.trim(),X=await eA({providerId:J,explicitModels:Z,modelsSourceUrl:j,shouldRecompute:!0});if(X.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let A=$.defaultModelId?.trim()&&X.includes($.defaultModelId.trim())?$.defaultModelId.trim():X[0],P=$.capabilities?.length?[...new Set($.capabilities)]:void 0,B=oA($.headers);f.saveProviderSettings({provider:J,apiKey:H||void 0,baseUrl:W,headers:B,timeout:$.timeoutMs,model:A,protocol:$.protocol,client:$.client},{setLastUsed:!1});let Y=s$(f),V=await V2(Y);return V.providers[J]={provider:{name:Q,baseUrl:W,defaultModelId:A,protocol:$.protocol,client:$.client,capabilities:P,modelsSourceUrl:j},models:z9(X,P)},await uJ(Y,V),D4(J,V.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:Y,modelsCount:X.length}}async function rJ(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=s$(f),H=await V2(W),Q=H.providers[J];if(!Q){let M=f.getProviderSettings(J);if(!M)throw Error(`provider "${J}" does not exist`);let T=$.modelsSourceUrl?.trim(),_=O9($.models)[0]??M.model?.trim();if(!_&&!T)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:$.name?.trim()||tA(J),baseUrl:$.baseUrl?.trim()??M.baseUrl?.trim()??"",defaultModelId:_,protocol:M.protocol,client:M.client,capabilities:M.capabilities},models:_?z9([_],M.capabilities):{}}}if(!Q.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let Z=$.name?.trim()??Q.provider.name.trim();if(!Z)throw Error("name is required");let j=$.baseUrl?.trim()??Q.provider.baseUrl.trim();if(!j)throw Error("baseUrl is required");let X=$.capabilities===void 0?Q.provider.capabilities:$.capabilities===null?void 0:[...new Set($.capabilities)],A=$.protocol===void 0?Q.provider.protocol:$.protocol??void 0,P=$.client===void 0?Q.provider.client:$.client??void 0,B=O9($.models),Y=$.modelsSourceUrl===void 0?Q.provider.modelsSourceUrl:$.modelsSourceUrl?.trim()||void 0,V=$.models!==void 0||$.modelsSourceUrl!==void 0&&!!Y,R=Object.keys(Q.models??{}).map((M)=>M.trim()).filter(Boolean),U=await eA({providerId:J,explicitModels:B,modelsSourceUrl:Y,fallbackModelIds:R,shouldRecompute:V});if(U.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let K=$.defaultModelId===void 0?Q.provider.defaultModelId?.trim():$.defaultModelId?.trim(),F=K&&U.includes(K)?K:U[0],D={...f.getProviderSettings(J)??{},provider:J,baseUrl:j,model:F};if(A)D.protocol=A;else delete D.protocol;if(P)D.client=P;else delete D.client;if($.apiKey!==void 0){let M=$.apiKey?.trim()??"";if(M)D.apiKey=M;else delete D.apiKey}if($.headers!==void 0){let M=oA($.headers);if(M)D.headers=M;else delete D.headers}if($.timeoutMs!==void 0)if(typeof $.timeoutMs==="number")D.timeout=$.timeoutMs;else delete D.timeout;return f.saveProviderSettings(D,{setLastUsed:!1}),H.providers[J]={provider:{name:Z,baseUrl:j,defaultModelId:F,protocol:A,client:P,capabilities:X,modelsSourceUrl:Y},models:z9(U,X)},await uJ(W,H),D4(J,H.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:W,modelsCount:U.length}}async function lJ(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=s$(f),H=await V2(W);if(!H.providers[J])throw Error(`provider "${J}" does not exist`);return delete H.providers[J],await uJ(W,H),Bf.unregisterProvider(J),fP(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:W}}async function q9(f){let $=f.read(),J=Bf.getProviderIds().sort((H,Q)=>H.localeCompare(Q));return{providers:await Promise.all(J.map(async(H)=>{let[Q,Z]=await Promise.all([Bf.getProvider(H),Bf.getModelsForProvider(H)]),j=sA(Z),X=$.providers[H]?.settings,A=Q?.name??tA(H);return{id:H,name:A,models:j.length,color:BL(H),letter:PL(A),enabled:Boolean(X),apiKey:X?XL(X):void 0,oauthAccessTokenPresent:X?AL(X):void 0,baseUrl:X?.baseUrl??Q?.baseUrl,defaultModelId:Q?.defaultModelId,protocol:X?.protocol??Q?.protocol,client:X?.client??Q?.client,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",modelList:j}})),settingsPath:f.getFilePath()}}async function w9(f,$){let J=f.trim(),W=await YL(J,$),H=sA(W);return{providerId:J,models:H}}function b9(f,$){let J=$.providerId.trim();if($.enabled===!1){let Q=f.read();if(delete Q.providers[J],Q.lastUsedProvider===J)delete Q.lastUsedProvider;return f.write(Q),{providerId:J,enabled:!1,settingsPath:f.getFilePath()}}let H={...f.getProviderSettings(J)??{},provider:J};for(let Q of["apiKey","baseUrl","model","region"])if(Object.hasOwn($,Q)&&typeof $[Q]==="string")if($[Q].trim().length===0)delete H[Q];else H[Q]=$[Q];for(let Q of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn($,Q))H[Q]=$[Q];for(let Q of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn($,Q)&&$[Q]!=null)H[Q]={...typeof H[Q]==="object"&&H[Q]!=null?H[Q]:{},...$[Q]};return f.saveProviderSettings(H,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:f.getFilePath()}}async function C9(f,$){let J=$.trim(),W=f.getProviderSettings(J),Q=Bf.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,Z=W?.baseUrl?.trim()||Q?.baseUrl?.trim(),j=c6(Z,Q?.baseUrl,Q?.modelsSourceUrl);if(!W||!Q||!Z||!j)return{providerId:J,refreshed:!1};let X=await rJ(f,{providerId:J,name:Q.name,baseUrl:Z,apiKey:W.apiKey,headers:W.headers??null,timeoutMs:W.timeout??null,modelsSourceUrl:j,protocol:W.protocol??Q.protocol??null,client:W.client??Q.client??null,capabilities:W.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:X.modelsCount}}function E9(f){let $=f.trim().toLowerCase();if($==="codex"||$==="openai-codex")return"openai-codex";if($==="cline"||$==="oca")return $;throw Error(`provider "${f}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function VL(f,$){if(f==="cline")return $.access.startsWith("workos:")?$.access:`workos:${$.access}`;return $.access}async function S9(f,$,J){let W=x8({onPrompt:async(H)=>H.defaultValue??"",openUrl:J,onOpenUrlError:({error:H})=>{throw H instanceof Error?H:Error(String(H))}});if(f==="cline")return i1({apiBaseUrl:$?.baseUrl?.trim()||ZL().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:W});if(f==="oca")return u1({mode:$?.oca?.mode,callbacks:W});return n1(W)}function k9(f,$,J,W){let H={...J?.auth??{},accessToken:VL($,W),refreshToken:W.refresh,accountId:W.accountId,expiresAt:W.expires},Q={...J??{provider:$},provider:$,auth:H};return f.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function I9(f){let $=f?.auth?.accessToken?.trim()||f?.apiKey?.trim();return $&&$.length>0?$:void 0}var RL=new Set(["ollama","lmstudio","litellm"]);function FL(f,$){if(!$?.provider.baseUrl)return!1;if($.provider.source!=="system")return!0;return RL.has(f)}function m9(f){let $=Bf.normalizeProviderId(f);if(jL($))return{providerId:$,authMethod:"oauth",fields:{}};let J=Bf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=J?.provider.baseUrl,H={apiKey:{}};if(FL($,J))H.baseUrl={defaultValue:W};return{providerId:$,authMethod:"api-key",fields:H}}var ZP={};N(ZP,{resolveLegacyClineAuth:()=>QP,migrateLegacyProviderSettings:()=>_4});import{existsSync as KL,readFileSync as yL}from"node:fs";import{dirname as UL,join as x9}from"node:path";import*as WP from"@cline/llms";import{resolveClineDataDir as GL}from"@cline/shared/storage";var HP="openai";function QP(f){let $=f?.trim();if(!$)return;try{let J=JSON.parse($);if(!J)return;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:J.expiresAt,accountId:J.userInfo?.id}}catch{return}}function E(f){let $=f?.trim();return $?$:void 0}function JP(f){if(!KL(f))return;try{let $=yL(f,"utf8"),J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function TL(f){let $=f.dataDir??GL(),J=f.globalStatePath??x9($,"globalState.json"),W=f.secretsPath??x9($,"secrets.json"),H=JP(J),Q=JP(W);if(!H&&!Q)return;return{globalState:H??{},secrets:Q??{}}}function DL(f){try{let J=new URL(f).hostname.toLowerCase();return J==="api.openai.com"||J.endsWith(".openai.azure.com")||J.endsWith(".services.ai.azure.com")}catch{return!1}}function _L(f){let $=E(f.openAiBaseUrl);if(!$)return!1;if(f.azureApiVersion||f.azureIdentity)return!1;return!DL($)}function g9(f,$){if(f==="openai"&&_L($))return HP;return f}function ML(f,$,J,W){let H=J==="plan"?"planMode":"actMode",Q=$===W?E(J==="plan"?f.planModeApiModelId:f.actModeApiModelId):void 0,j={openrouter:`${H}OpenRouterModelId`,cline:`${H}ClineModelId`,openai:`${H}OpenAiModelId`,ollama:`${H}OllamaModelId`,lmstudio:`${H}LmStudioModelId`,litellm:`${H}LiteLlmModelId`,requesty:`${H}RequestyModelId`,together:`${H}TogetherModelId`,fireworks:`${H}FireworksModelId`,sapaicore:`${H}SapAiCoreModelId`,groq:`${H}GroqModelId`,baseten:`${H}BasetenModelId`,huggingface:`${H}HuggingFaceModelId`,"huawei-cloud-maas":`${H}HuaweiCloudMaasModelId`,oca:`${H}OcaModelId`,aihubmix:`${H}AihubmixModelId`,hicap:`${H}HicapModelId`,nousResearch:`${H}NousResearchModelId`,"vercel-ai-gateway":`${H}VercelAiGatewayModelId`}[$];return(j?E(typeof f[j]==="string"?f[j]:void 0):void 0)??Q}function LL(f,$,J){let W=J==="plan"?f.planModeReasoningEffort:f.actModeReasoningEffort,H=J==="plan"?f.geminiPlanModeThinkingLevel:f.geminiActModeThinkingLevel,Q=J==="plan"?f.planModeThinkingBudgetTokens:f.actModeThinkingBudgetTokens,Z=($==="gemini"?H:void 0)??W,j=Z==="none"||Z==="low"||Z==="medium"||Z==="high"?Z: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 hL(f){let $=f["openai-codex-oauth-credentials"];if(!$)return;try{let J=JSON.parse($),W=E(J.access_token),H=E(J.refresh_token),Q=E(J.accountId);if(!W&&!H&&!Q)return;return{...W?{apiKey:W}:{},auth:{...W?{accessToken:W}:{},...H?{refreshToken:H}:{},...Q?{accountId:Q}:{}}}}catch{return}}function OL(f){let $=WP.getGeneratedModelsForProvider(f);return Object.keys($)[0]??void 0}function zL(f,$,J,W){let H=g9(f,$),Q=E(W==="plan"?$.planModeApiProvider:$.actModeApiProvider),Z=ML($,f,W,Q)??OL(H),j=LL($,H,W),X=typeof $.requestTimeoutMs==="number"&&Number.isInteger($.requestTimeoutMs)&&$.requestTimeoutMs>0?$.requestTimeoutMs:void 0,A={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey,sapaicore:J.sapAiCoreClientId},P={};if(f==="openai-codex")Object.assign(P,hL(J));if(f==="cline")try{let F=E(J["cline:clineAccountId"]);if(F)P.auth={...P.auth??{},...QP(F)}}catch{}if(f==="openai"&&$.openAiHeaders)P.headers=$.openAiHeaders;if(f==="bedrock")P.aws={accessKey:E(J.awsAccessKey),secretKey:E(J.awsSecretKey),sessionToken:E(J.awsSessionToken),region:E($.awsRegion),authentication:$.awsAuthentication,profile:$.awsUseProfile?E($.awsProfile):void 0,usePromptCache:$.awsBedrockUsePromptCache,useCrossRegionInference:$.awsUseCrossRegionInference,useGlobalInference:$.awsUseGlobalInference,endpoint:E($.awsBedrockEndpoint),customModelBaseId:E(W==="plan"?$.planModeAwsBedrockCustomModelBaseId:$.actModeAwsBedrockCustomModelBaseId)};if(f==="vertex")P.gcp={projectId:E($.vertexProjectId),region:E($.vertexRegion)};if(f==="openai"&&($.azureApiVersion||$.azureIdentity!==void 0))P.azure={apiVersion:E($.azureApiVersion),useIdentity:$.azureIdentity};if(f==="sapaicore")P.sap={clientId:E(J.sapAiCoreClientId),clientSecret:E(J.sapAiCoreClientSecret),tokenUrl:E($.sapAiCoreTokenUrl),resourceGroup:E($.sapAiResourceGroup),deploymentId:E(W==="plan"?$.planModeSapAiCoreDeploymentId:$.actModeSapAiCoreDeploymentId),useOrchestrationMode:$.sapAiCoreUseOrchestrationMode};if(f==="oca"){P.oca={mode:$.ocaMode};let F=E(J.ocaRefreshToken);if(F)P.auth={...P.auth??{},refreshToken:F}}if(f==="qwen")P.apiLine=$.qwenApiLine;if(f==="moonshot")P.apiLine=$.moonshotApiLine;if(f==="zai")P.apiLine=$.zaiApiLine;if(f==="minimax")P.apiLine=$.minimaxApiLine;let B={anthropic:$.anthropicBaseUrl,openai:$.openAiBaseUrl,ollama:$.ollamaBaseUrl,lmstudio:$.lmStudioBaseUrl,litellm:$.liteLlmBaseUrl,gemini:$.geminiBaseUrl,requesty:$.requestyBaseUrl,asksage:$.asksageApiUrl,dify:$.difyBaseUrl,oca:$.ocaBaseUrl,aihubmix:$.aihubmixBaseUrl,sapaicore:$.sapAiCoreBaseUrl},Y=E(A[f]),V=E(B[f]),R={provider:H,...Y?{apiKey:Y}:{},...Z?{model:Z}:{},...V?{baseUrl:V}:{},...j?{reasoning:j}:{},...X?{timeout:X}:{},...P},U=S8.safeParse(R);if(!U.success)return;return Object.keys(R).filter((F)=>F!=="provider").length>0?U.data:void 0}function NL(f,$){if(f!==HP)return;if(!$.baseUrl||!$.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:$.baseUrl,defaultModelId:$.model},models:{[$.model]:{id:$.model,name:$.model}}}}function qL(f,$){let J=new Set;for(let W of[f.actModeApiProvider,f.planModeApiProvider]){let H=E(W);if(H)J.add(H)}if(E($.apiKey))J.add("anthropic");if(E($.openRouterApiKey))J.add("openrouter");if(E($.openAiApiKey))J.add("openai");if(E($.openAiNativeApiKey))J.add("openai-native");if(E($["openai-codex-oauth-credentials"]))J.add("openai-codex");if(E($.geminiApiKey))J.add("gemini");if(E($.ollamaApiKey))J.add("ollama");if(E($.awsAccessKey)||E($.awsBedrockApiKey))J.add("bedrock");if(E(f.vertexProjectId)||E(f.vertexRegion))J.add("vertex");if(E($.clineApiKey))J.add("cline");if(E($.ocaApiKey))J.add("oca");return J}function _4(f){let $=f.providerSettingsManager.read(),J=TL(f);if(!J)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let{globalState:W,secrets:H}=J,Q=W.mode==="plan"?"plan":"act",Z=qL(W,H),j=H$();j.providers={...$.providers},j.lastUsedProvider=$.lastUsedProvider;let X=new Date().toISOString(),A=0,P=x9(UL(f.providerSettingsManager.getFilePath()),"models.json"),B=h9(P),Y=0;for(let U of Z){let K=g9(U,W);if(j.providers[K])continue;let F=zL(U,W,H,Q);if(!F)continue;j.providers[K]={settings:F,updatedAt:X,tokenSource:"migration"},A+=1;let y=NL(K,F);if(y&&!B.providers[K])B.providers[K]=y,Y+=1}if(A===0&&Y===0)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let V=E(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),R=V?g9(V,W):void 0;if(j.lastUsedProvider=$.lastUsedProvider??(R&&j.providers[R]?R:Object.keys(j.providers)[0]),f.providerSettingsManager.write(j),Y>0)dA(P,B);return{migrated:A>0||Y>0,providerCount:Object.keys(j.providers).length,lastUsedProvider:j.lastUsedProvider}}_f();H6();var AP={};N(AP,{trimMessagesToCheckpoint:()=>XP,trimMessagesBeforeCheckpoint:()=>u9,readSessionCheckpointHistory:()=>M4,createRestoredCheckpointMetadata:()=>v9,createCheckpointRestorePlan:()=>c9,applyCheckpointToWorktree:()=>d9});import{execFile as wL}from"node:child_process";import{promisify as bL}from"node:util";var R2=bL(wL);function M4(f){let $=f?.metadata?.checkpoint&&typeof f.metadata.checkpoint==="object"&&!Array.isArray(f.metadata.checkpoint)?f.metadata.checkpoint:void 0;return(Array.isArray($?.history)?$.history:[]).filter((W)=>!!W&&typeof W==="object"&&!Array.isArray(W)).flatMap((W)=>{let H=String(W.ref??"").trim(),Q=Number(W.createdAt??0),Z=Number(W.runCount??0);if(H.length===0||!Number.isFinite(Q)||!Number.isInteger(Z)||Z<1)return[];let j=W.kind==="stash"||W.kind==="commit"?W.kind:void 0;return[{ref:H,createdAt:Q,runCount:Z,...j?{kind:j}:{}}]})}function v9(f,$){let J=M4(f).filter((H)=>H.runCount<=$),W=J.at(-1);return W?{latest:W,history:J}:void 0}function CL(f,$){return f.reduce((J,W)=>{if(W.runCount>$)return J;if(!J||W.runCount>J.runCount)return W;return J},void 0)}function jP(f,$){let J=0;for(let W=0;W<f.length;W+=1){let H=f[W];if(H?.role!=="user")continue;if(("metadata"in H&&H.metadata&&typeof H.metadata==="object"?H.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===$)return W}throw Error(`Could not find user message for checkpoint run ${$}`)}function XP(f,$){let J=jP(f,$);return f.slice(0,J+1)}function u9(f,$){let J=jP(f,$);return f.slice(0,J)}function c9(f){let $=f.checkpointRunCount;if(!Number.isInteger($)||$<1)throw Error("checkpointRunCount must be a positive integer");let J=CL(M4(f.session),$);if(!J)throw Error(`No checkpoint found at or before run ${$} in session ${f.session.sessionId}`);let W=(f.cwd?.trim()||f.session.cwd||f.session.workspaceRoot).trim();if(!W)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:W,...f.restoreMessages!==!1?{messages:XP(f.messages??[],$)}:{}}}async function d9(f,$){if((await R2("git",["-C",f,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${f} is not a git repository`);if(await R2("git",["-C",f,"cat-file","-e",`${$.ref}^{commit}`],{windowsHide:!0}),await R2("git",["-C",f,"reset","--hard"],{windowsHide:!0}),await R2("git",["-C",f,"clean","-fd"],{windowsHide:!0}),$.kind==="commit"){await R2("git",["-C",f,"reset","--hard",$.ref],{windowsHide:!0});return}await R2("git",["-C",f,"stash","apply",$.ref],{windowsHide:!0})}var PP={};N(PP,{SessionVersioningService:()=>B$,SessionVersioningError:()=>zf});class zf extends Error{code;constructor(f,$){super($);this.code=f;this.name="SessionVersioningError"}}function EL(f){let $=f.sessionId.trim();if(!$)throw new zf("invalid_restore","sessionId is required");if(!f.restoreMessages&&!f.restoreWorkspace)throw new zf("invalid_restore","restore.messages or restore.workspace must be true");if(f.restoreMessages&&f.requiresStart)throw new zf("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger(f.checkpointRunCount)||f.checkpointRunCount<1)throw new zf("invalid_restore","checkpointRunCount must be a positive integer");return $}class B${async restoreCheckpoint(f){let $=f.restore?.messages!==!1,J=f.restore?.workspace!==!1,W=EL({sessionId:f.sessionId,restoreMessages:$,restoreWorkspace:J,requiresStart:f.start===void 0,checkpointRunCount:f.checkpointRunCount}),H=await f.getSession(W);if(!H)throw new zf("session_not_found",`Session ${W} not found`);let Q=$?await f.readMessages(W):void 0;if($&&Q?.length===0)throw new zf("session_messages_not_found",`No messages found for session ${W}`);let Z=c9({session:H,messages:Q,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restoreMessages:$});if(J)await(f.applyWorkspaceCheckpoint??d9)(Z.cwd,Z.checkpoint);let j=W0({session:H,messages:Q});if(!$)return{checkpoint:Z.checkpoint,sourceSnapshot:j};let X=v9(H,f.checkpointRunCount),A=f.restore?.omitCheckpointMessageFromSession?u9(Q??[],f.checkpointRunCount):Z.messages??[],P={sourceSession:H,sourceMessages:Q,sourceSnapshot:j,plan:Z,restoredCheckpointMetadata:X,initialMessages:A,restoreMessages:$,restoreWorkspace:J,checkpointRunCount:f.checkpointRunCount};if(!f.start||!f.startSession)throw new zf("invalid_restore","start is required when restore.messages is true");let B=f.buildStartInput?await f.buildStartInput(P,f.start):f.start,Y=await f.startSession(B),V=f.getStartedSessionId?.(Y);if(V)await(f.retainCheckpointRefs??uZ)(Z.cwd,V,X?.history??[]);let R=V&&f.readRestoredSession?await f.readRestoredSession(V):void 0;return{sessionId:V,startResult:Y,messages:Z.messages,checkpoint:Z.checkpoint,sourceSnapshot:j,...R?{restoredSnapshot:W0({session:R,messages:A})}:{}}}}var BP={};N(BP,{FileTeamPersistenceStore:()=>pJ});import{appendFileSync as SL,existsSync as r9,mkdirSync as kL,readFileSync as IL,renameSync as mL,unlinkSync as xL,writeFileSync as gL}from"node:fs";import{join as l9}from"node:path";import{resolveTeamDataDir as vL}from"@cline/shared/storage";function uL(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class pJ{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor(f){let $=uL(f.teamName),J=f.baseDir?.trim()||vL();this.dirPath=l9(J,$),this.statePath=l9(this.dirPath,"state.json"),this.taskHistoryPath=l9(this.dirPath,"task-history.jsonl")}loadState(){if(!r9(this.statePath))return;try{let f=IL(this.statePath,"utf8"),$=JSON.parse(f);if($.version!==1||!$.teamState)return;for(let J of $.teammates??[])this.teammateSpecs.set(J.agentId,J);return ZA($.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec(f){this.teammateSpecs.set(f.agentId,f)}removeTeammateSpec(f){this.teammateSpecs.delete(f)}persist(f){if(!this.hasPersistableState(f)){this.clearPersistedState();return}this.ensureDir();let $={version:1,updatedAt:new Date().toISOString(),teamState:f.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;gL(J,`${JSON.stringify($,null,2)}
696
+ `,"utf8"),mL(J,this.statePath)}appendTaskHistory(f){let $={};switch(f.type){case"team_task_updated":$=f.task;break;case"team_message":$={agentId:f.message.fromAgentId,toAgentId:f.message.toAgentId,subject:f.message.subject,taskId:f.message.taskId};break;case"team_mission_log":$={agentId:f.entry.agentId,kind:f.entry.kind,summary:f.entry.summary,taskId:f.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":$={agentId:f.agentId,message:"message"in f?f.message:void 0};break;case"task_end":$={agentId:f.agentId,finishReason:f.result?.finishReason,error:f.error?.message};break;case"agent_event":$={agentId:f.agentId,eventType:f.event.type};break}this.ensureDir(),SL(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:f.type,task:$})}
697
+ `,"utf8")}ensureDir(){if(!r9(this.dirPath))kL(this.dirPath,{recursive:!0})}hasPersistableState(f){let $=f.exportState();if(this.teammateSpecs.size>0)return!0;if($.members.some((J)=>J.role==="teammate"))return!0;return $.tasks.length>0||$.mailbox.length>0||$.missionLog.length>0}clearPersistedState(){if(r9(this.statePath))xL(this.statePath)}}var YP={};N(YP,{ChatViewStateSchema:()=>p9,ChatSummarySchema:()=>sJ,ChatSessionStatusSchema:()=>nJ,ChatSessionConfigSchema:()=>iJ,ChatMessageSchema:()=>tJ,ChatMessageRoleSchema:()=>aJ});import{z as w}from"zod";var iJ=w.object({workspaceRoot:w.string().min(1),cwd:w.string().optional(),provider:w.string().min(1),model:w.string().min(1),mode:w.enum(["act","plan"]).default("act"),apiKey:w.string(),systemPrompt:w.string().optional(),rules:w.string().optional(),maxIterations:w.number().int().positive().optional(),enableTools:w.boolean(),enableSpawn:w.boolean().optional(),enableTeams:w.boolean().optional(),autoApproveTools:w.boolean().optional(),missionStepInterval:w.number().int().positive().optional(),missionTimeIntervalMs:w.number().int().positive().optional()}),nJ=w.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),aJ=w.enum(["user","assistant","tool","system","status","error"]),tJ=w.object({id:w.string().min(1),sessionId:w.string().nullable(),role:aJ,content:w.string(),createdAt:w.number().int().nonnegative(),meta:w.object({stream:w.enum(["stdout","stderr"]).optional(),toolName:w.string().optional(),iteration:w.number().int().nonnegative().optional(),agentId:w.string().optional(),conversationId:w.string().optional(),hookEventName:w.string().optional(),inputTokens:w.number().int().nonnegative().optional(),outputTokens:w.number().int().nonnegative().optional(),checkpoint:w.object({ref:w.string(),createdAt:w.number().int().nonnegative(),runCount:w.number().int().positive(),kind:w.enum(["stash","commit"]).optional()}).optional()}).optional()}),sJ=w.object({toolCalls:w.number().int().nonnegative(),tokensIn:w.number().int().nonnegative(),tokensOut:w.number().int().nonnegative()}),p9=w.object({sessionId:w.string().nullable(),status:nJ,config:iJ,messages:w.array(tJ),rawTranscript:w.string(),error:w.string().nullable(),summary:sJ});var VP={};N(VP,{CORE_BUILD_VERSION:()=>i9});var i9=ZQ;import{Agent as Gh,createAgentRuntime as Th}from"@cline/agents";var FP={};N(FP,{fetchClineRecommendedModels:()=>n9,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>oJ});import{getClineEnvironmentConfig as cL}from"@cline/shared";var dL=5000,oJ={recommended:[{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",description:"Most intelligent model for agents and coding",tags:["BEST"]},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",description:"Strong coding and agent performance",tags:["NEW"]},{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"1M context window, strong coding performance",tags:["NEW"]},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",description:"OpenAI's latest with strong coding abilities",tags:["NEW"]}],free:[{id:"kwaipilot/kat-coder-pro",name:"KwaiKAT Kat Coder Pro",description:"Advanced agentic coding model",tags:["FREE"]},{id:"arcee-ai/trinity-large-preview:free",name:"Arcee AI Trinity Large Preview",description:"Advanced large preview model",tags:["FREE"]}]};function rL(f){return{recommended:f.recommended.map(($)=>({...$,tags:[...$.tags]})),free:f.free.map(($)=>({...$,tags:[...$.tags]}))}}function RP(f){if(!f||typeof f!=="object")return null;let $=f;if(typeof $.id!=="string"||$.id.length===0)return null;return{id:$.id,name:typeof $.name==="string"&&$.name.length>0?$.name:$.id,description:typeof $.description==="string"?$.description:"",tags:Array.isArray($.tags)?$.tags.filter((J)=>typeof J==="string"):[]}}function lL(f){if(!f||typeof f!=="object")return null;let $=f,J=Array.isArray($.recommended)?$.recommended:[],W=Array.isArray($.free)?$.free:[],H=J.map(RP).filter((Z)=>Z!==null),Q=W.map(RP).filter((Z)=>Z!==null);if(H.length===0&&Q.length===0)return null;return{recommended:H,free:Q}}function pL(f){let $=f.baseUrl?.trim();if($)return $;let J=cL().apiBaseUrl;try{return(f.providerSettingsManager??new A0).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function iL(f,$,J){let W=new AbortController,H=setTimeout(()=>W.abort(),J);try{return await f($,{signal:W.signal})}finally{clearTimeout(H)}}async function n9(f={}){try{let $=pL(f),J=f.fetchImpl??fetch,W=await iL(J,`${$}/api/v1/ai/cline/recommended-models`,f.timeoutMs??dL);if(!W.ok)throw Error(`HTTP ${W.status}`);let H=await W.json(),Q=lL(H);if(Q)return Q}catch{}return rL(oJ)}var KP={};N(KP,{loadLlmsConfigFromFile:()=>t9,defineLlmsConfig:()=>a9});import{readFile as nL}from"node:fs/promises";import aL from"node:path";function a9(f){return f}async function t9(f){let $=aL.resolve(f),J=await nL($,"utf8"),W;try{W=JSON.parse(J)}catch(H){let Q=H instanceof Error?H.message:String(H);throw Error(`Failed to parse JSON config at "${$}": ${Q}`)}return tL(W,$)}function tL(f,$){if(!f||typeof f!=="object")throw Error(`Invalid llms config in "${$}": expected an object.`);let W=f.providers;if(!Array.isArray(W))throw Error(`Invalid llms config in "${$}": "providers" must be an array.`);if(!W.length)throw Error(`Invalid llms config in "${$}": "providers" cannot be empty.`);return f}var _P={};N(_P,{createLlmsSdk:()=>o9,DefaultLlmsSdk:()=>L4});import{BUILT_IN_PROVIDER_IDS as GP,createHandler as eL,createHandlerAsync as fh,getProviderCollection as $h,hasProvider as TP,registerAsyncHandler as Jh,registerHandler as Wh,registerModel as Hh,registerProvider as DP}from"@cline/llms";function yP(f){return f?{...f}:{}}function sL(f,$){if(f)return f;if(!$)return;let J=globalThis.process;if(!J?.env)return;return J.env[$]}function oL(f,$){if(!$.length)throw Error(`Provider "${f}" must include at least one model.`)}function UP(f){let $=Object.keys(f.collection.models);return{id:f.collection.provider.id,name:f.collection.provider.name,description:f.collection.provider.description,protocol:f.collection.provider.protocol,baseUrl:f.collection.provider.baseUrl,capabilities:f.collection.provider.capabilities,env:f.collection.provider.env,models:$,defaultModel:f.collection.provider.defaultModelId,modelCount:$.length}}class s9{providers=new Map;register(f){oL(f.id,f.models);let $=f.defaultModel??f.models[0];if(!$)throw Error(`Provider "${f.id}" must define a default model.`);if(!f.models.includes($))throw Error(`Default model "${$}" is not included in configured models for "${f.id}".`);let J=this.providers.get(f.id);this.providers.set(f.id,{id:f.id,models:new Set([...J?.models??[],...f.models]),defaultModel:$,defaults:{...J?.defaults??{},...yP(f.defaults)}})}registerSelectionConfig(f){this.register({id:f.id,models:f.models,defaultModel:f.defaultModel,defaults:{apiKey:sL(f.apiKey,f.apiKeyEnv),routingProviderId:f.builtinProviderId,baseUrl:f.baseUrl,headers:f.headers,timeoutMs:f.timeoutMs,capabilities:f.capabilities,...yP(f.settings)}})}registerModel(f,$){let J=this.providers.get(f);if(!J){this.providers.set(f,{id:f,models:new Set([$]),defaultModel:$,defaults:{}});return}J.models.add($)}createHandlerConfig(f){let $=this.require(f.providerId),J=f.modelId??$.defaultModel;if(!$.models.has(J))throw Error(`Model "${J}" is not configured for provider "${f.providerId}".`);return{providerId:f.providerId,modelId:J,...$.defaults,...f.overrides}}list(){return Array.from(this.providers.values()).map((f)=>({id:f.id,models:Array.from(f.models),defaultModel:f.defaultModel}))}getModels(f){return Array.from(this.require(f).models)}hasProvider(f){return this.providers.has(f)}hasModel(f,$){return this.providers.get(f)?.models.has($)??!1}require(f){let $=this.providers.get(f);if(!$)throw Error(`Provider "${f}" is not configured in this SDK instance.`);return $}}class L4{configuredProviders=new s9;constructor(f){this.applyConfig(f)}createHandler(f){return eL(this.configuredProviders.createHandlerConfig(f))}async createHandlerAsync(f){return fh(this.configuredProviders.createHandlerConfig(f))}registerProvider(f){if(DP(f.collection),f.handlerFactory&&f.asyncHandlerFactory)throw Error(`Provider "${f.collection.provider.id}" cannot register both sync and async handlers.`);if(f.handlerFactory)Wh(f.collection.provider.id,f.handlerFactory);if(f.asyncHandlerFactory)Jh(f.collection.provider.id,f.asyncHandlerFactory);this.configuredProviders.register({id:f.collection.provider.id,models:f.exposeModels??Object.keys(f.collection.models),defaultModel:f.defaultModel??f.collection.provider.defaultModelId,defaults:f.defaults})}registerBuiltinProvider(f){let $=f.exposeModels??Object.keys(f.models),J=f.defaultModel??$[0];if(!J)throw Error(`Provider "${f.id}" must define a default model.`);DP({provider:{id:f.id,name:f.name??f.id,description:f.description,protocol:f.protocol,baseUrl:f.baseUrl,defaultModelId:J,client:f.client??"openai-compatible",capabilities:f.capabilities,env:f.env,source:"system"},models:f.models}),this.configuredProviders.register({id:f.id,models:$,defaultModel:J,defaults:{routingProviderId:f.builtinProviderId,...f.defaults??{}}})}registerModel(f){Hh(f.providerId,f.modelId,f.info),this.configuredProviders.registerModel(f.providerId,f.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...GP]}async getBuiltInProviders(){return(await Promise.all(GP.map(($)=>$h($)))).filter(($)=>$!==void 0).map(($)=>UP({collection:$}))}getModels(f){return this.configuredProviders.getModels(f)}isProviderConfigured(f){return this.configuredProviders.hasProvider(f)}isModelConfigured(f,$){return this.configuredProviders.hasModel(f,$)}applyConfig(f){for(let $ of f.providers)this.configuredProviders.registerSelectionConfig($);for(let $ of f.models??[])this.registerModel($);for(let $ of f.customProviders??[])this.registerProvider($);for(let $ of this.configuredProviders.list()){let J=TP($.id),W=this.configuredProviders.createHandlerConfig({providerId:$.id,modelId:$.defaultModel}).routingProviderId,H=typeof W==="string"&&TP(W);if(!J&&!H)throw Error(`Provider "${$.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function o9(f){return new L4(f)}T5();async function Qh(){return Promise.resolve().then(() => (Y9(),zA))}function hh(){return new Date().toISOString()}function Oh(f){if(wP(f)!=="providers.json")return;let $=f3(f);if(wP($)!=="settings")return;return f3($)}class A0{filePath;dataDir;constructor(f={}){if(this.filePath=f.filePath??Lh(),this.dataDir=f.dataDir??Oh(this.filePath),this.dataDir||!f.filePath)_4({providerSettingsManager:this,dataDir:this.dataDir});if(aA(this),cJ(this.read()),e9(this.filePath))try{qP(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!e9(this.filePath))return H$();try{let f=_h(this.filePath,"utf8"),$=JSON.parse(f),J=r1.safeParse($);if(J.success)return cJ(J.data),J.data}catch{}return H$()}write(f){let $=r1.parse(f),J=f3(this.filePath);if(!e9(J))Dh(J,{recursive:!0,mode:448});Mh(this.filePath,`${JSON.stringify($,null,2)}
698
+ `,"utf8");try{qP(this.filePath,384)}catch{}cJ($)}saveProviderSettings(f,$={}){let J=S8.parse(f),W=this.read(),H=J.provider,Q=$.setLastUsed!==!1,Z=W.providers[H],j=$.tokenSource??Z?.tokenSource??"manual",X={...W,providers:{...W.providers,[H]:{settings:J,updatedAt:hh(),tokenSource:j}},lastUsedProvider:Q?H:W.lastUsedProvider};return this.write(X),X}getProviderSettings(f){return this.read().providers[f]?.settings}getLastUsedProviderSettings(){let f=this.read(),$=f.lastUsedProvider;if(!$)return;return f.providers[$]?.settings}getProviderConfig(f,$){let J=this.getProviderSettings(f);if(!J)return;return mf(J,$)}getLastUsedProviderConfig(f){let $=this.getLastUsedProviderSettings();if(!$)return;return mf($,f)}async refreshCatalog(){try{await c1({})}catch{}}}_f();W6();import{getClineEnvironmentConfig as zh,isOAuthProviderId as Nh}from"@cline/shared";var $3="workos:";function qh(f,$){if(f==="cline")return`${$3}${$}`;return $}function wh(f,$){if(f==="cline"&&$.toLowerCase().startsWith($3))return $.slice($3.length);return $}function bh(f){let J=Kf(f)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function Ch(f,$){let J=f.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let W=bh($);if(W)return W;return Date.now()-1}function Eh(f,$){let J=$.auth?.accessToken?.trim(),W=$.auth?.refreshToken?.trim();if(!J||!W)return null;let H=wh(f,J);if(!H)return null;return{access:H,refresh:W,expires:Ch($,H),accountId:$.auth?.accountId}}function Sh(f,$){let J=f?.expiresAt,W=$?.expiresAt;return f?.accessToken===$?.accessToken&&f?.refreshToken===$?.refreshToken&&f?.accountId===$?.accountId&&J===W}class f5 extends Error{providerId;constructor(f){super(`OAuth credentials for provider "${f}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=f}}class J3{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor(f){this.providerSettingsManager=f?.providerSettingsManager??new A0,this.telemetry=f?.telemetry}async resolveProviderApiKey(f){if(!Nh(f.providerId))return null;return this.resolveWithSingleFlight(f.providerId,f.forceRefresh)}async resolveWithSingleFlight(f,$=!1){let J=this.refreshInFlight.get(f);if(J)return J;let W=this.resolveProviderApiKeyInternal(f,$).catch((H)=>{throw H}).finally(()=>{this.refreshInFlight.delete(f)});return this.refreshInFlight.set(f,W),W}async resolveProviderApiKeyInternal(f,$){let J=this.providerSettingsManager.getProviderSettings(f);if(!J)return null;let W=Eh(f,J);if(!W)return null;let H=await this.resolveCredentials(f,J,W,$);if(!H)throw new f5(f);let Q=qh(f,H.access),Z={...J.auth??{},accessToken:Q,refreshToken:H.refresh,accountId:H.accountId};Z.expiresAt=H.expires;let j={...J,auth:Z},X=!Sh(J.auth,j.auth);if(X)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:f,apiKey:Q,accountId:H.accountId,refreshed:X}}async resolveCredentials(f,$,J,W){if(f==="cline")return v8(J,{apiBaseUrl:$.baseUrl?.trim()||zh().apiBaseUrl,telemetry:this.telemetry},{forceRefresh:W});if(f==="oca")return z8(J,{forceRefresh:W,telemetry:this.telemetry},{mode:$.oca?.mode,telemetry:this.telemetry});return c8(J,{forceRefresh:W,telemetry:this.telemetry})}}import{normalizeUserInput as kh}from"@cline/shared";import{nanoid as Ih}from"nanoid";class bP{list(f){return f?uf(f):[]}update(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=$.promptId.trim(),W=f.pendingPrompts.findIndex((X)=>X.id===J);if(W<0)return{sessionId:$.sessionId,prompts:uf(f),updated:!1};let H=f.pendingPrompts[W];if(!H)return{sessionId:$.sessionId,prompts:uf(f),updated:!1};let Q=$.prompt===void 0?H.prompt:kh($.prompt).trim();if(!Q)throw Error("prompt cannot be empty");let Z=$.delivery??H.delivery,j={...H,prompt:Q,delivery:Z};return f.pendingPrompts.splice(W,1),mh(f,j,W,H.delivery),{sessionId:$.sessionId,prompts:uf(f),prompt:$5(j),updated:!0}}delete(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=$.promptId.trim(),W=f.pendingPrompts.findIndex((Q)=>Q.id===J);if(W<0)return{sessionId:$.sessionId,prompts:uf(f),removed:!1};let[H]=f.pendingPrompts.splice(W,1);return{sessionId:$.sessionId,prompts:uf(f),prompt:H?$5(H):void 0,removed:!0}}enqueue(f,$){let{prompt:J,delivery:W,userImages:H,userFiles:Q}=$,Z=f.pendingPrompts.findIndex((j)=>j.prompt===J);if(Z>=0){let[j]=f.pendingPrompts.splice(Z,1),X={...j,prompt:J,userImages:H??j.userImages,userFiles:Q??j.userFiles};if(W==="steer"||j.delivery==="steer")f.pendingPrompts.unshift({...X,delivery:"steer"});else f.pendingPrompts.push(X)}else{let j={id:`pending_${Date.now()}_${Ih(5)}`,prompt:J,delivery:W,userImages:H,userFiles:Q};if(W==="steer")f.pendingPrompts.unshift(j);else f.pendingPrompts.push(j)}return uf(f)}consumeSteer(f){let $=f.pendingPrompts.findIndex((W)=>W.delivery==="steer");if($<0)return{prompts:uf(f)};let[J]=f.pendingPrompts.splice($,1);return{entry:J,prompts:uf(f)}}shiftNext(f){return{entry:f.pendingPrompts.shift(),prompts:uf(f)}}requeueFront(f,$){return f.pendingPrompts.unshift($),uf(f)}clear(f){return f.pendingPrompts.length=0,[]}}class W3{deps;service=new bP;constructor(f){this.deps=f}list(f){return this.service.list(this.deps.getSession(f))}update(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=this.service.update($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}delete(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=this.service.delete($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}enqueue(f,$){let J=this.deps.getSession(f);if(!J||J.aborting)return;this.service.enqueue(J,$),this.emitPrompts(J),this.scheduleDrain(f,J)}consumeSteer(f){let $=this.deps.getSession(f);if(!$)return;let{entry:J}=this.service.consumeSteer($);if(!J)return;return this.emitPrompts($),this.emitSubmitted($,J),J.prompt}clearAborted(f){if(f.pendingPrompts.length===0)return;this.service.clear(f),this.emitPrompts(f)}emitPrompts(f){this.deps.emit({type:"pending_prompts",payload:{sessionId:f.sessionId,prompts:uf(f)}})}scheduleDrain(f,$){if($.pendingPrompts.length===0||$.aborting||$.drainingPendingPrompts||!$.agent.canStartRun())return;queueMicrotask(()=>{this.drain(f)})}async drain(f){let $=this.deps.getSession(f);if(!$||$.aborting||$.drainingPendingPrompts)return;if(!$.agent.canStartRun())return;let{entry:J}=this.service.shiftNext($);if(!J)return;this.emitPrompts($),this.emitSubmitted($,J),$.drainingPendingPrompts=!0;try{await this.deps.send({sessionId:f,prompt:J.prompt,userImages:J.userImages,userFiles:J.userFiles})}catch(W){if((W instanceof Error?W.message:String(W)).includes("already in progress"))this.service.requeueFront($,J),this.emitPrompts($);else throw W}finally{if($.drainingPendingPrompts=!1,$.pendingPrompts.length>0&&$.status!=="failed"&&$.status!=="cancelled")queueMicrotask(()=>{this.drain(f)})}}emitSubmitted(f,$){let J=$5($);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:f.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function $5(f){return{id:f.id,prompt:f.prompt,delivery:f.delivery,attachmentCount:(f.userImages?.length??0)+(f.userFiles?.length??0)}}function uf(f){return f.pendingPrompts.map($5)}function mh(f,$,J,W){if($.delivery==="steer")f.pendingPrompts.unshift($);else if(W==="steer")f.pendingPrompts.push($);else f.pendingPrompts.splice(J,0,$)}_f();class Q3{deps;constructor(f){this.deps=f}dispatchAgentEvent(f,$,J){let W=this.deps.getSession(f),H={sessionId:f,config:$,liveSession:W,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},Q=NW(J),Z=!!W&&(!Q.agentId||Q.agentId===H3(W.agent));qW(H,J,Z?{isPrimaryAgentEvent:!0,agentId:H3(W.agent),conversationId:W.agent.getConversationId(),...W?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent(f,$){let J=this.deps.getSession(f);if(J){if(aH(J,$),$.type==="agent_event"){let W={sessionId:f,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};qW(W,$.event,{agentId:$.agentId,teamRole:"teammate",teamAgentId:$.agentId,isPrimaryAgentEvent:!1})}if($.type==="teammate_spawned"){let W=O0({agentId:$.teammate.runtimeAgentId??$.agentId,conversationId:$.teammate.conversationId,parentAgentId:$.teammate.parentAgentId,createdByAgentId:H3(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:$.agentId});if(W)g0(J.config.telemetry,{ulid:f,modelId:$.teammate.modelId??J.config.modelId,provider:J.config.providerId,...W})}}if(await tH(f,$,this.deps.invokeBackendOptional),J)sH(J,f,$,this.deps.emit)}async handlePluginEvent(f,$,J){if($.name==="plugin_log"){this.handlePluginLog(f,$.payload);return}if($.name==="automation_event"){let X=this.deps.getSession(f)?.config.extensionContext?.automation??J;if(!X)return;let A=$.payload&&typeof $.payload==="object"?$.payload:void 0;if(!A)return;await X.ingestEvent(A);return}if($.name!=="steer_message"&&$.name!=="queue_message"&&$.name!=="pending_prompt")return;let W=$.payload&&typeof $.payload==="object"?$.payload:void 0,H=typeof W?.sessionId==="string"&&W.sessionId.trim().length>0?W.sessionId.trim():f,Q=typeof W?.prompt==="string"?W.prompt.trim():"";if(!Q)return;let Z=$.name==="steer_message"?"steer":$.name==="queue_message"?"queue":W?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(H,{prompt:Q,delivery:Z})}handlePluginLog(f,$,J){let W=this.deps.getSession(f),H=J??W?.config.extensionContext?.logger??W?.config.logger;if(!H||!$||typeof $!=="object")return;let Q=$,Z=typeof Q.message==="string"?Q.message:"";if(!Z)return;let j=Q.metadata&&typeof Q.metadata==="object"?{...Q.metadata}:{};if(j.sessionId??=f,typeof Q.pluginName==="string"&&Q.pluginName)j.pluginName=Q.pluginName;if(Q.level==="debug"){H.debug(Z,j);return}if(Q.level==="error"){if(H.error)H.error(Z,j);else H.log(Z,{...j,severity:"error"});return}H.log(Z,j)}}function H3(f){return f.getAgentId()}function Z3(f){return{sessionId:f.sessionId,source:f.source,pid:process.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:o0(f.config),teamName:f.config.teamName?.trim()||void 0,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,parentSessionId:typeof f.sessionMetadata?.parentSessionId==="string"?f.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof f.sessionMetadata?.parentAgentId==="string"?f.sessionMetadata.parentAgentId:void 0,agentId:typeof f.sessionMetadata?.agentId==="string"?f.sessionMetadata.agentId:void 0,conversationId:typeof f.sessionMetadata?.conversationId==="string"?f.sessionMetadata.conversationId:void 0,isSubagent:typeof f.sessionMetadata?.isSubagent==="boolean"?f.sessionMetadata.isSubagent:!1,prompt:f.pendingPrompt,metadata:f.sessionMetadata,messagesPath:f.artifacts?.messagesPath,updatedAt:f.updatedAt??f.endedAt??f.startedAt}}function j3(f,$){let J=f[$];return typeof J==="function"?J:null}async function CP(f,$,...J){let W=j3(f,$);if(!W)throw Error(`session service method not available: ${$}`);return Promise.resolve(W.apply(f,J))}async function EP(f,$,...J){let W=j3(f,$);if(!W)return;await Promise.resolve(W.apply(f,J))}async function SP(f,$,...J){let W=j3(f,$);if(!W)return;return await Promise.resolve(W.apply(f,J))}G0();_f();function X3(f,$,J,W){return t0({configProvider:{getRuntimeConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:$.hooks,extensions:$.extensions,logger:$.logger,telemetry:$.telemetry},getConnectionConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Q=$.enableTools?b$({cwd:$.cwd,...kf[L0({mode:$.mode})],executors:W}):[];if($.enableSpawnAgent)Q.push(X3(f,$,J,W));return U$(Q)},onSubAgentEvent:(Q)=>f.onAgentEvent(J,$,Q),onSubAgentStart:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime;f.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let j=O0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)g0($.telemetry,{ulid:J,modelId:$.modelId,provider:$.providerId,...j});N2($.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...j}),f.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime,j=f.subAgentStarts.get(Q.subAgentId),X=j?Date.now()-j.startedAt:0,A=Q.result?.text?Q.result.text.split(`
699
+ `).length:0;N2($.telemetry,{event:"ended",ulid:J,durationMs:X,outputLines:A,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...O0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId})}),f.subAgentStarts.delete(Q.subAgentId),f.invokeBackendOptional("handleSubAgentEnd",J,Q)}})}import{readFile as xh,stat as gh}from"node:fs/promises";var vh=20480000;async function kP(f){let $=await gh(f);if(!$.isFile())throw Error("Path is not a file");if($.size>vh)throw Error("File is too large to read into context.");let J=await xh(f,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var IP=5000;function q4(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function nh(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=q4($.inputTokens),W=q4($.outputTokens),H=q4($.cacheReadTokens),Q=q4($.cacheWriteTokens),Z=q4($.totalCost);if(J===void 0||W===void 0||H===void 0||Q===void 0||Z===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:H,cacheWriteTokens:Q,totalCost:Z}}function ah(f,$){return{inputTokens:Math.max(f.inputTokens,$.inputTokens),outputTokens:Math.max(f.outputTokens,$.outputTokens),cacheReadTokens:Math.max(f.cacheReadTokens,$.cacheReadTokens),cacheWriteTokens:Math.max(f.cacheWriteTokens,$.cacheWriteTokens),totalCost:Math.max(f.totalCost,$.totalCost)}}class X0{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new j4;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new B$;constructor(f){let $=ch();if($)ih($);let J=G$(f.distinctId);this.sessionService=f.sessionService,this.runtimeBuilder=f.runtimeBuilder??new Y2,this.createAgentInstance=f.createAgent??((W)=>new a0(W)),this.defaultCapabilities=Uf(f.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=f.toolPolicies,this.providerSettingsManager=f.providerSettingsManager??new A0,this.oauthTokenManager=f.oauthTokenManager??new J3({providerSettingsManager:this.providerSettingsManager,telemetry:f.telemetry}),this.defaultTelemetry=f.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=f.fetch,this.pendingPromptsController=new W3({getSession:(W)=>this.sessions.get(W),emit:(W)=>this.emit(W),send:(W)=>this.runTurn(W)}),this.pendingPrompts={list:async(W)=>this.pendingPromptsController.list(W.sessionId),update:async(W)=>this.pendingPromptsController.update(W),delete:async(W)=>this.pendingPromptsController.delete(W)},this.eventBridge=new Q3({getSession:(W)=>this.sessions.get(W),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(W)=>this.emit(W),persistMessages:(W,H,Q)=>{this.invoke("persistSessionMessages",W,H,Q)},enqueuePendingPrompt:(W,H)=>this.pendingPromptsController.enqueue(W,H),invokeBackendOptional:(W,...H)=>this.invokeOptional(W,...H)})}async startSession(f){let $=f.source??Ff.CLI,J=s(),W=f.config.sessionId?.trim()??"",H=W||rh(),Q=f,Z=Q.initialMessages??[],j=Z.length>0?q1(Z):Pf(),X=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!X)throw Error("session service method not available: ensureSessionsDir");let A=A3(X,H),P=A3(A,`${H}.messages.json`),B=A3(A,`${H}.json`),Y=o0(f.config),V=Lf.parse({version:1,session_id:H,source:$,pid:process.pid,started_at:J,status:"running",interactive:f.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Q.config.cwd,workspace_root:Y,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,messages_path:P}),R;if(W.length>0&&Z.length>0&&!Q.prompt?.trim()){let S=await this.invokeOptionalValue("readSessionManifest",H);if(S)V=S,R={manifestPath:B,messagesPath:S.messages_path||P,manifest:S}}let K=await this.seedAggregateUsageFromArtifacts({initialUsage:j,sessionDir:A,rootMessagesPath:R?.messagesPath??P,manifest:V});this.usageBySession.set(H,j),this.aggregateUsageBySession.set(H,K);let F=Uf(this.defaultCapabilities,f.capabilities),y=F?.toolExecutors??this.toolExecutors,D=f.localRuntime,M=D?.extensionContext?.logger??D?.logger,T=D?.extensionContext?.automation,_;_=await Oj({input:Q,localRuntime:f.localRuntime,sessionId:H,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:F,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(S)=>{if(S.name==="plugin_log"){this.eventBridge.handlePluginLog(H,S.payload,M);return}this.eventBridge.handlePluginEvent(H,S,T)},onTeamEvent:(S)=>{this.eventBridge.handleTeamEvent(H,S),_.config.onTeamEvent?.(S)},createSpawnTool:()=>X3({getSession:(S)=>this.sessions.get(S),subAgentStarts:this.subAgentStarts,onAgentEvent:(S,n,B0)=>this.eventBridge.dispatchAgentEvent(S,n,B0),invokeBackendOptional:(S,...n)=>this.invokeOptional(S,...n)},_.config,H,y),readSessionMetadata:async()=>(await this.getSession(H))?.metadata,writeSessionMetadata:async(S)=>{await this.persistSessionMetadata(H,()=>S)}});let L=await this.runtimeBuilder.build(_.runtimeBuilderInput),q=_.config,Wf=_.providerConfig;if(L.teamRuntime&&!q.teamName?.trim())q.teamName=L.teamRuntime.getTeamName();let Hf=[...L.tools,...q.extraTools??[]],o=L.extensions??_.extensions,c={sessionId:H,providerId:Wf.providerId,modelId:Wf.modelId,apiKey:Wf.apiKey,baseUrl:Wf.baseUrl,headers:Wf.headers,knownModels:Wf.knownModels,providerConfig:Wf,thinking:q.thinking,reasoningEffort:q.reasoningEffort??Wf.reasoningEffort,systemPrompt:q.systemPrompt,maxIterations:q.maxIterations,execution:q.execution,prepareTurn:l2(q),tools:Hf,hooks:_.hooks,extensions:o,hookErrorMode:q.hookErrorMode,initialMessages:_.effectiveInput.initialMessages,userFileContentLoader:kP,toolPolicies:_.toolPolicies,requestToolApproval:_.requestToolApproval,onConsecutiveMistakeLimitReached:q.onConsecutiveMistakeLimitReached,completionPolicy:L.completionPolicy,consumePendingUserMessage:()=>{let S=this.pendingPromptsController.consumeSteer(H);return S?Y4(S,q.mode):S},logger:L.logger??q.logger,extensionContext:q.extensionContext,onEvent:(S)=>this.eventBridge.dispatchAgentEvent(H,q,S)};c.hooks={...c.hooks,onEvent:async(S)=>{if(await _.hooks?.onEvent?.(S),S.type!=="assistant-message")return;let n=this.sessions.get(H);if(!n)return;let B0=n.agent.getMessages();try{await this.invoke("persistSessionMessages",H,B0,q.systemPrompt)}catch(Y0){q.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:H,error:Y0})}}};let Gf=this.createAgentInstance(c);if(c.onEvent)Gf.subscribeEvents(c.onEvent);L.registerLeadAgent?.(Gf);let E0=O0({agentId:Gf.getAgentId(),conversationId:Gf.getConversationId(),teamId:L.teamRuntime?.getTeamId(),teamName:L.teamRuntime?.getTeamName(),teamRole:L.teamRuntime?"lead":void 0});if(Nj(q,H,W.length>0,Y,E0),E0)g0(q.telemetry,{ulid:H,modelId:q.modelId,provider:q.providerId,...E0});if(L.teamRuntime)s4(q.telemetry,{ulid:H,teamId:L.teamRuntime.getTeamId(),teamName:L.teamRuntime.getTeamName(),leadAgentId:Gf.getAgentId(),restoredFromPersistence:L.teamRestoredFromPersistence===!0});let i={sessionId:H,config:q,sessionMetadata:Q.sessionMetadata,...R?{artifacts:R}:{},source:$,startedAt:R?.manifest.started_at??J,updatedAt:R?.manifest.ended_at??R?.manifest.started_at??J,pendingPrompt:V.prompt,runtime:L,agent:Gf,started:!1,status:R?.manifest.status??"running",aborting:!1,interactive:f.interactive===!0,persistedMessages:Z,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:_.pluginSandboxShutdown,submitAndExitObserved:!1};if(this.sessions.set(H,i),this.emitStatus(H,"running"),Z.length>0&&!R){if(await this.ensureSessionPersisted(i),await this.invoke("persistSessionMessages",i.sessionId,Z,i.config.systemPrompt),!Q.prompt?.trim())await this.updateStatus(i,"completed",0)}let P0;try{if(Q.prompt?.trim())if(P0=await this.executeTurn(i,{prompt:Q.prompt,userImages:Q.userImages,userFiles:Q.userFiles}),!i.interactive)await this.finalizeSingleRun(i,P0.finishReason);else await this.completeInteractiveTurn(i,P0.finishReason)}catch(S){if(i.interactive&&i.aborting)P0=await this.completeAbortedInteractiveTurn(i);else throw await this.failSession(i),S}return{sessionId:H,manifest:V,manifestPath:B,messagesPath:P,result:P0}}async restoreSession(f){return this.sessionVersioning.restoreCheckpoint({...f,getSession:($)=>this.getSession($),readMessages:($)=>this.readSessionMessages($),buildStartInput:($,J)=>{let W=$.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:$.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...W?{sessionMetadata:W}:{},initialMessages:$.initialMessages}},startSession:($)=>this.startSession($),getStartedSessionId:($)=>$.sessionId,readRestoredSession:($)=>this.getSession($)})}async runTurn(f){let $=this.getSessionOrThrow(f.sessionId),J=$.agent.canStartRun(),W=f.delivery??($.interactive&&!J?"queue":void 0);if($.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:f.sessionId,promptLength:f.prompt.length,userImageCount:f.userImages?.length??0,userFileCount:f.userFiles?.length??0,delivery:W??"immediate"}}),W==="queue"||W==="steer"){this.pendingPromptsController.enqueue(f.sessionId,{prompt:f.prompt,delivery:W,userImages:f.userImages,userFiles:f.userFiles});return}try{let H=await this.executeTurn($,{prompt:f.prompt,userImages:f.userImages,userFiles:f.userFiles});if(!$.interactive)await this.finalizeSingleRun($,H.finishReason);else await this.completeInteractiveTurn($,H.finishReason);if(H.finishReason==="error"||H.finishReason==="aborted")return H;return queueMicrotask(()=>{this.pendingPromptsController.drain(f.sessionId)}),H}catch(H){if($.interactive&&$.aborting)return await this.completeAbortedInteractiveTurn($);throw await this.failSession($),H}}async getAccumulatedUsage(f){let $=gH(this.usageBySession.get(f)),J=gH(this.aggregateUsageBySession.get(f));return $||J?{usage:$,aggregateUsage:J}:void 0}async abort(f,$){let J=this.sessions.get(f);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:f}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort($)}async stopSession(f){let $=this.sessions.get(f);if(!$)return;if($.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:f}}),$.interactive&&$.status!=="running"){await this.releaseSessionRuntime($,"session_stop");return}$.aborting=!0,$.agent.abort(Error("session_stop")),await this.shutdownSession($,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose(f="session_manager_dispose"){let $=[...this.sessions.values()];if($.length===0)return;await Promise.allSettled($.map((J)=>J.interactive&&J.status!=="running"?this.releaseSessionRuntime(J,f):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:f,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession(f){let $=this.sessions.get(f);if($)return Z3($);let J=f.trim();if(!J)return;let W=await this.getRow(J);if(W)return V8(W);let H=await this.readManifest(J);return H?LJ(H):void 0}async listSessions(f=200){let J=(await this.listRows(f)).map(V8),W=new Set(J.map((H)=>H.sessionId));for(let H of this.sessions.values()){if(W.has(H.sessionId))continue;J.unshift(Z3(H))}return J.slice(0,f)}async deleteSession(f){if(this.sessions.has(f))await this.stopSession(f);let $=await this.invoke("deleteSession",f);if($.deleted)this.usageBySession.delete(f),this.aggregateUsageBySession.delete(f);return $.deleted}async updateSession(f,$){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:f,prompt:$.prompt,metadata:$.metadata,title:$.title}))?.updated===!0}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.getRow($);if(J?.messagesPath)return X$(J.messagesPath);let W=await this.readManifest($);return X$(W?.messages_path)}async dispatchHookEvent(f){await OX(f,{queueSpawnRequest:($)=>this.invokeOptional("queueSpawnRequest",$),upsertSubagentSessionFromHook:($)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",$),appendSubagentHookAudit:($,J)=>this.invokeOptional("appendSubagentHookAudit",$,J),applySubagentStatus:($,J)=>this.invokeOptional("applySubagentStatus",$,J)})}subscribe(f,$){return this.events.subscribe(f,$)}async updateSessionModel(f,$){let J=this.getSessionOrThrow(f);J.config.modelId=$,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:$}),J.agent.updateConnection({modelId:$})}handlePluginEvent(f,$,J){return this.eventBridge.handlePluginEvent(f,$,J)}async executeTurn(f,$){let J=await this.prepareTurnInput(f,$),W=J.prompt.trim();if(!W)throw Error("prompt cannot be empty");if(!f.artifacts&&!f.pendingPrompt)f.pendingPrompt=W;await this.ensureSessionPersisted(f),await this.syncOAuthCredentials(f),await this.markTurnRunning(f);let H=await this.executeAgentTurn(f,W,J.userImages,J.userFiles);while(oH(f,H.finishReason)){let Q=await eH(f);if(Q.length===0)break;let Z=f9(f,Q);H=await this.executeAgentTurn(f,Z)}return H}async completeInteractiveTurn(f,$){if(B4(f))return;let J=$==="aborted"||f.aborting,W=$==="error";await this.updateStatus(f,J?"cancelled":W?"failed":"completed",W?1:0),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$,ts:Date.now()}}),f.aborting=!1}async completeAbortedInteractiveTurn(f){let $=new Date,J=f.agent.getMessages();return f.persistedMessages=J,f.started=f.started||J.length>0,await this.completeInteractiveTurn(f,"aborted"),{text:"",usage:Pf(),messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:f.config.modelId,provider:f.config.providerId},startedAt:$,endedAt:$,durationMs:0}}async executeAgentTurn(f,$,J,W){let H=f.started||f.agent.getMessages().length>0,Q=f.persistedMessages??f.agent.getMessages(),Z=this.usageBySession.get(f.sessionId)??Pf(),j=this.aggregateUsageBySession.get(f.sessionId)??Z;f.turnUsageBaseline=Z,f.turnAggregateUsageBaseline=j,f.turnPrimaryUsage=Pf(),f.turnUsageByAgent=new Map,r4(f.config.telemetry,f.sessionId,f.config.mode),X1(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,model:f.config.modelId,source:"user",mode:f.config.mode,...this.getSessionAgentTelemetryIdentity(f)});try{let X=H?()=>f.agent.continue($,J,W):()=>f.agent.run($,J,W),A=await this.runWithAuthRetry(f,X,Q);f.started=!0;let P=z6(A.messages,A,Q);f.persistedMessages=P;let B=F8(f.turnUsageByAgent?.values()??[]),Y=Xf(Z,A.usage),V=Xf(Xf(Pf(),A.usage),B),R=Xf(j,V);return this.usageBySession.set(f.sessionId,Y),this.aggregateUsageBySession.set(f.sessionId,R),await this.persistSessionMetadata(f.sessionId,(U)=>({...U??{},totalCost:Y.totalCost,aggregatedAgentsCost:R.totalCost,usage:Y,aggregateUsage:R})),await this.invoke("persistSessionMessages",f.sessionId,P,f.config.systemPrompt),this.observeTaskCompletionTool(f,A),A}catch(X){throw await this.invoke("persistSessionMessages",f.sessionId,f.agent.getMessages(),f.config.systemPrompt),X}finally{f.turnUsageBaseline=void 0,f.turnAggregateUsageBaseline=void 0,f.turnPrimaryUsage=void 0,f.turnUsageByAgent=void 0}}observeTaskCompletionTool(f,$){if(f.submitAndExitObserved)return;if(!$.toolCalls.some((W)=>W.name===Jf.SUBMIT_AND_EXIT&&W.error===void 0))return;f.submitAndExitObserved=!0,O2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity(f)})}async prepareTurnInput(f,$){let J=o0(f.config),W=ph($.prompt).trim();if(!W)return{prompt:"",userImages:$.userImages,userFiles:this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles)};let H=await y1(W,J);qj(f.config.telemetry,H);let Q=Y4(H.prompt,f.config.mode),Z=this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles),j=this.resolveAbsoluteFilePaths(J,H.matchedFiles),X=Array.from(new Set([...Z,...j]));return{prompt:Q,userImages:$.userImages,userFiles:X.length>0?X:void 0}}async ensureSessionPersisted(f){if(f.artifacts)return;let $=o0(f.config);f.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:f.sessionId,source:f.source,pid:process.pid,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:$,teamName:f.config.teamName,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,prompt:f.pendingPrompt,metadata:f.sessionMetadata,startedAt:f.startedAt})}async markTurnRunning(f){if(f.status==="running")return;await this.updateStatus(f,"running",null)}async persistSessionMetadata(f,$){let J=this.sessions.get(f),W=await this.invokeOptionalValue("readSessionManifest",f)??J?.artifacts?.manifest,H=$(W?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:f,metadata:H}))?.updated===!1)return;J.sessionMetadata=H,J.artifacts.manifest.metadata=H}async finalizeSingleRun(f,$){if(B4(f))return;let J=$==="aborted"||f.aborting,W=$==="error";await this.shutdownSession(f,{status:J?"cancelled":W?"failed":"completed",exitCode:W?1:0,shutdownReason:W?"session_error":"session_complete",endReason:$})}async failSession(f){await this.shutdownSession(f,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession(f,$){if($.status==="completed"&&!f.submitAndExitObserved)O2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity(f)});qJ(f);let J=[],W=(H,Q)=>{J.push(Q),f.config.logger?.log("Session shutdown cleanup failed",{sessionId:f.sessionId,stage:H,error:Q,severity:"warn"})};if(f.artifacts){try{await this.updateStatus(f,$.status,$.exitCode)}catch(H){W("update_status",H)}try{await f.agent.shutdown($.shutdownReason)}catch(H){W("agent_shutdown",H)}}try{await Promise.resolve(f.runtime.shutdown($.shutdownReason))}catch(H){W("runtime_shutdown",H)}try{await f.pluginSandboxShutdown?.()}catch(H){W("plugin_sandbox_shutdown",H)}if(this.sessions.delete(f.sessionId),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$.endReason,ts:Date.now()}}),J.length>0&&$.status==="failed")throw J[0]}async releaseSessionRuntime(f,$){let J=[],W=(H,Q)=>{J.push(Q),f.config.logger?.log("Session runtime cleanup failed",{sessionId:f.sessionId,stage:H,error:Q,severity:"warn"})};try{await f.agent.shutdown($)}catch(H){W("agent_shutdown",H)}try{await Promise.resolve(f.runtime.shutdown($))}catch(H){W("runtime_shutdown",H)}try{await f.pluginSandboxShutdown?.()}catch(H){W("plugin_sandbox_shutdown",H)}if(this.sessions.delete(f.sessionId),J.length>0)throw J[0]}async updateStatus(f,$,J){if(!f.artifacts)return;let W=await this.invoke("updateSessionStatus",f.sessionId,$,J);if(!W.updated)return;let H=await this.invokeOptionalValue("readSessionManifest",f.sessionId)??f.artifacts.manifest;if(H.status=$,$==="running")delete H.ended_at,H.exit_code=null;else H.ended_at=W.endedAt??s(),H.exit_code=typeof J==="number"?J:null;f.artifacts.manifest=H,f.status=$,f.updatedAt=W.endedAt??s(),f.endedAt=$==="running"?null:H.ended_at,f.exitCode=H.exit_code,await this.invoke("writeSessionManifest",f.artifacts.manifestPath,H),this.emitStatus(f.sessionId,$)}async runWithAuthRetry(f,$,J){try{return await $()}catch(W){if(!lh(W,f.config.providerId))throw W;return await this.syncOAuthCredentials(f,{forceRefresh:!0}),f.agent.restore(J),$()}}async syncOAuthCredentials(f,$){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:f.config.providerId,forceRefresh:$?.forceRefresh})}catch(W){if(W instanceof f5)throw Error(`${W.providerId} requires re-authentication.`);throw W}if(!J?.apiKey||f.config.apiKey===J.apiKey)return;f.config.apiKey=J.apiKey,f.agent.updateConnection({apiKey:J.apiKey}),f.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),f.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow(f){let $=this.sessions.get(f);if(!$)throw Error(`session not found: ${f}`);return $}resolveAbsoluteFilePaths(f,$){if(!$||$.length===0)return[];let J=$.map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>dh(W)?W:P3(f,W));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity(f){return O0({agentId:f.agent.getAgentId(),conversationId:f.agent.getConversationId(),teamId:f.runtime.teamRuntime?.getTeamId(),teamName:f.runtime.teamRuntime?.getTeamName(),teamRole:f.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts(f){let $=await this.summarizePersistedTeammateUsage(f.sessionDir,f.rootMessagesPath,f.manifest.session_id),J=Xf(f.initialUsage,$);return this.withPersistedAggregateUsageFloor(J,f.manifest)}async summarizePersistedTeammateUsage(f,$,J){let W=P3($),H=`${J}.messages.json`,Q;try{Q=uh(f)}catch{return Pf()}let Z=Pf();for(let j of Q){if(!j.endsWith(".messages.json"))continue;if(j===H)continue;let X=P3(f,j);if(X===W)continue;let A=await X$(X);if(A.length===0)continue;Z=Xf(Z,q1(A))}return Z}withPersistedAggregateUsageFloor(f,$){let J=nh($.metadata?.aggregateUsage);if(J)return ah(f,J);let W=$.metadata?.aggregatedAgentsCost;if(typeof W!=="number"||!Number.isFinite(W)||W<=f.totalCost)return f;return{...f,totalCost:W}}emitStatus(f,$){this.emitSessionSnapshot(f),this.emit({type:"status",payload:{sessionId:f,status:$}})}async emitSessionSnapshot(f){let $=await this.getSession(f);if(!$)return;this.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:W0({session:$,messages:await this.readSessionMessages(f),usage:this.usageBySession.get(f),aggregateUsage:this.aggregateUsageBySession.get(f)})}})}emit(f){this.events.emit(f)}async listRows(f){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor(f)),IP))}async getRow(f){let $=f.trim();if(!$)return;return(await this.listRows(IP)).find((W)=>W.sessionId===$)}async readManifest(f){let $=f.trim();if(!$)return;return await this.invokeOptionalValue("readSessionManifest",$)}invoke(f,...$){return CP(this.sessionService,f,...$)}invokeOptional(f,...$){return EP(this.sessionService,f,...$)}invokeOptionalValue(f,...$){return SP(this.sessionService,f,...$)}}function sh(f){return{text:f.text,usage:f.usage,inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function oh(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}function hP(f={}){let $=new X0({sessionService:new j0(new Q0),fetch:f.fetch,telemetry:f.telemetry});return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),H=await $.startSession({source:J.source?.trim()||Ff.CLI,interactive:!1,config:{providerId:th(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:oh(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:H.sessionId,startResult:{sessionId:H.sessionId,manifestPath:H.manifestPath,messagesPath:H.messagesPath}}},async sendSession(J,W){let H=await $.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content)});if(!H)throw Error("local hub schedule runtime returned no turn result");return{result:sh(H)}},async abortSession(J){return await $.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function eh(f){if(typeof f==="string")return f.trim()||void 0;if(!Array.isArray(f))return;return f.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
700
+ `).trim()||void 0}var mP=120,B3="...";function h4(f){let $=f.trim();if(!$)return"";if(Buffer.byteLength($,"utf8")<=mP)return $;let J=mP-Buffer.byteLength(B3,"utf8");if(J<=0)return B3;let W="";for(let H of $){if(Buffer.byteLength(W+H,"utf8")>J)break;W+=H}return`${W}${B3}`}async function xP(f){let $=f?.sessionId?.trim()||"unknown",J=typeof f?.metadata?.messagesPath==="string"?f.metadata.messagesPath:void 0,H=[...await X$(J)].reverse().find((X)=>X.role==="assistant"),Q=H?eh(H.content):void 0,Z=f?.workspaceRoot?.trim()||"workspace",j=typeof f?.metadata?.prompt==="string"?f.metadata.prompt.trim():Z;return{title:`Task completed (${$})`,body:h4(Q&&Q.length>0?Q:j.length>0?j:Z),severity:"info"}}import{createSessionId as zO}from"@cline/shared";import{createSessionId as WO}from"@cline/shared";import{createSessionId as JO}from"@cline/shared";function fO(f){switch(f){case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function $O(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):{};if(f.parentSessionId?.trim())$.parentSessionId=f.parentSessionId;if(f.parentAgentId?.trim())$.parentAgentId=f.parentAgentId;if(f.agentId?.trim())$.agentId=f.agentId;if(f.conversationId?.trim())$.conversationId=f.conversationId;if(f.messagesPath?.trim())$.messagesPath=f.messagesPath;if(f.prompt?.trim())$.prompt=f.prompt;if(f.provider?.trim())$.provider=f.provider;if(f.model?.trim())$.model=f.model;if(f.source?.trim())$.source=f.source;if(typeof f.pid==="number")$.pid=f.pid;return Object.keys($).length>0?$:void 0}function J5(f,$,J,W){return{sessionId:f.sessionId,workspaceRoot:f.workspaceRoot,cwd:f.cwd,createdAt:Date.parse(f.startedAt),updatedAt:Date.parse(f.updatedAt),createdByClientId:$?.createdByClientId??"hub",status:fO(f.status),participants:$?[...$.participants.values()]:[],metadata:$O(f),runtimeOptions:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,mode:typeof f.metadata?.mode==="string"?f.metadata.mode:void 0,systemPrompt:typeof f.metadata?.systemPrompt==="string"?f.metadata.systemPrompt:void 0},runtimeSession:f.agentId?{agentId:f.agentId,team:f.teamName?{teamId:f.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...W?{aggregateUsage:{...W}}:{}}}function u(f,$){return{version:f.version,requestId:f.requestId,ok:!0,...$!==void 0?{payload:$}:{}}}function m(f,$,J){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:$,message:J}}}function W5(f){return f&&typeof f==="object"&&!Array.isArray(f)?f:void 0}function Nf(f){if(typeof f.payload?.sessionId==="string")return f.payload.sessionId.trim();return f.sessionId?.trim()??""}function o$(f,$,J){return{version:"v1",event:f,eventId:JO("hevt_"),sessionId:J,timestamp:Date.now(),payload:$}}async function cf(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let W=await f.sessionHost.getAccumulatedUsage?.($);return J5(J,f.sessionState.get($),W?.usage,W?.aggregateUsage)}async function df(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let[W,H]=await Promise.all([typeof f.sessionHost.readSessionMessages==="function"?f.sessionHost.readSessionMessages($):[],f.sessionHost.getAccumulatedUsage?.($)]);return W0({session:J,messages:W,usage:H?.usage,aggregateUsage:H?.aggregateUsage})}function H5(f,$,J,W,H={}){let Q=f.sessionState.get($);if(Q){if(H.interactive!==void 0)Q.interactive=H.interactive;if(!Q.participants.has(J))Q.participants.set(J,{clientId:J,attachedAt:Date.now(),role:W});return Q}let Z={createdByClientId:J,interactive:H.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:W}]])};return f.sessionState.set($,Z),Z}async function Y3(f,$){let J=WO("approval_"),W=$.sessionId;if(f.sessionState.get(W)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((Q)=>{f.pendingApprovals.set(J,{sessionId:W,resolve:Q}),f.publish(f.buildEvent("approval.requested",{approvalId:J,sessionId:$.sessionId,agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:JSON.stringify($.input??null),policy:$.policy},W))})}function V3(f,$,J){let W=f.pendingApprovals.get($);if(!W)return;return f.pendingApprovals.delete($),W.resolve(J),{sessionId:W.sessionId}}function R3(f,$,J){let W=0;for(let[H,Q]of[...f.pendingApprovals.entries()]){if(!$({approvalId:H,sessionId:Q.sessionId}))continue;f.pendingApprovals.delete(H),Q.resolve({approved:!1,reason:J}),f.publish(f.buildEvent("approval.resolved",{approvalId:H,approved:!1,cancelled:!0,reason:J},Q.sessionId)),W+=1}return W}async function gP(f,$){let J=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"";if(!f.pendingApprovals.get(J))return m($,"approval_not_found",`Unknown approval: ${J}`);let H=typeof $.payload?.reason==="string"?$.payload.reason:$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)&&typeof $.payload.payload.reason==="string"?$.payload.payload.reason:void 0,Q=$.payload?.approved===!0,Z=V3(f,J,{approved:Q,reason:H});if(!Z)return m($,"approval_not_found",`Unknown approval: ${J}`);return f.publish(f.buildEvent("approval.resolved",{approvalId:J,approved:Q,reason:H},Z.sessionId)),u($,{approvalId:J,approved:Q})}import{createSessionId as ZO}from"@cline/shared";function HO(f){if(f instanceof Error)return{name:f.name,message:f.message,stack:f.stack};if(f===void 0)return;return f}var vP={debug:10,info:20,warn:30,error:40,silent:50};function QO(){let f=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if(f==="debug"||f==="info"||f==="warn"||f==="error"||f==="silent")return f;return process.env.VITEST?"error":"info"}function g(f,$,J={}){if(vP[f]<vP[QO()])return;let W=JSON.stringify({ts:new Date().toISOString(),level:f,component:"hub",message:$,...Object.fromEntries(Object.entries(J).map(([H,Q])=>[H,HO(Q)]).filter(([,H])=>H!==void 0))});if(f==="error"||f==="warn"){console.error(`[hub] ${W}`);return}console.log(`[hub] ${W}`)}function F3(f,$){let J=$ instanceof Error?$.stack||$.message:String($);g("error",f,{error:J})}async function uP(f,$,J,W,H,Q){let Z=ZO("capreq_"),j=performance.now();return g("info","capability.request.start",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H}),await new Promise((X,A)=>{f.pendingCapabilityRequests.set(Z,{sessionId:$,targetClientId:H,capabilityName:J,onProgress:Q,resolve:(P)=>{if(g(P.ok?"info":"warn","capability.request.end",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H,ok:P.ok,error:P.error,durationMs:Math.round(performance.now()-j)}),!P.ok){A(Error(P.error||`Capability ${J} was rejected by ${H}.`));return}X(P.payload)}}),f.publish(f.buildEvent("capability.requested",{requestId:Z,targetClientId:H,capabilityName:J,payload:W},$)),g("info","capability.request.published",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H})})}function cP(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",W=f.pendingCapabilityRequests.get(J);if(!W)return m($,"capability_not_found",`Unknown capability request: ${J}`);if(($.clientId?.trim()||"")!==W.targetClientId)return m($,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==W.sessionId)return m($,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{};return W.onProgress?.(Q),u($,{requestId:J})}function Y$(f,$,J){let W=0;for(let[H,Q]of[...f.pendingCapabilityRequests.entries()]){if(!$({requestId:H,...Q}))continue;f.pendingCapabilityRequests.delete(H),g("warn","capability.request.cancelled",{requestId:H,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,reason:J}),Q.resolve({ok:!1,error:J}),f.publish(f.buildEvent("capability.resolved",{requestId:H,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,ok:!1,cancelled:!0,error:J},Q.sessionId)),W+=1}return W}async function dP(f,$){let J=typeof $.payload?.sessionId==="string"?$.payload.sessionId.trim():$.sessionId?.trim()||"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName.trim():"",H=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId.trim():"";if(!J||!W||!H)return m($,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},Z=await f.requestCapability(J,W,Q,H);return u($,Z)}catch(Q){return m($,"capability_request_failed",Q instanceof Error?Q.message:String(Q))}}function rP(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",W=f.pendingCapabilityRequests.get(J);if(!W)return m($,"capability_not_found",`Unknown capability request: ${J}`);let H=$.clientId?.trim()||"";if(H!==W.targetClientId)return m($,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==W.sessionId)return m($,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);f.pendingCapabilityRequests.delete(J);let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:void 0,Z=typeof $.payload?.error==="string"?$.payload.error:void 0,j=$.payload?.ok===!0;return g(j?"info":"warn","capability.respond",{requestId:J,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:H,ok:j,error:Z}),W.resolve({ok:j,payload:Q,error:Z}),f.publish(f.buildEvent("capability.resolved",{requestId:J,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:H,ok:j,payload:Q,error:Z},W.sessionId)),u($,{requestId:J,ok:j})}import{createSessionId as jO}from"@cline/shared";function lP(f,$){let J=$.payload,W=J?.clientId?.trim()||$.clientId?.trim()||jO("client_");return f.clients.set(W,{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),f.publish(f.buildEvent("hub.client.registered",{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),u($,{clientId:W})}function pP(f,$){let J=$.clientId?.trim(),W=J?f.clients.get(J):void 0;if(!J||!W)return m($,"client_not_found","Client is not registered with this hub.");let H=W5($.payload?.metadata);if(W.lastSeenAt=Date.now(),H)W.metadata=JSON.parse(JSON.stringify(H));return u($)}function iP(f,$,J){let W=$.clientId?.trim();if(W)f.clients.delete(W),J(W),f.publish(f.buildEvent("hub.client.disconnected",{clientId:W}));return u($)}function nP(f,$){return u($,{clients:[...f.clients.values()]})}var XO=30000;function AO(f){if(f==="aborted")return"run.aborted";if(f==="error"||f==="failed")return"run.failed";return"run.completed"}function PO(f){if(f.finishReason!=="error")return;return f.text.trim()||void 0}function BO(f){let $=typeof f.timeoutMs==="number"?f.timeoutMs:typeof f.timeout_ms==="number"?f.timeout_ms:void 0;if($&&Number.isFinite($)&&$>0)return Math.floor($);let J=typeof f.timeoutSeconds==="number"?f.timeoutSeconds:typeof f.timeout_seconds==="number"?f.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function YO(f,$,J,W){let H=performance.now(),Q=!1,Z={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:J.sessionId,timeoutMs:W},j=setInterval(()=>{if(Q)return;let P=Math.round(performance.now()-H);g("warn","run.heartbeat",{...Z,elapsedMs:P}),f.publish(f.buildEvent("run.heartbeat",{requestId:$.requestId,elapsedMs:P,...W?{timeoutMs:W}:{}},J.sessionId))},XO),X=f.sessionHost.runTurn(J);X.then((P)=>{if(!Q)return;g("warn","run.late_end",{...Z,elapsedMs:Math.round(performance.now()-H),finishReason:P?.finishReason})},(P)=>{if(!Q)return;g("error","run.late_error",{...Z,elapsedMs:Math.round(performance.now()-H),error:P})});let A;try{if(!W)return await X;return await Promise.race([X,new Promise((P,B)=>{A=setTimeout(()=>{let Y=`Hub run ${$.command} timed out after ${W}ms.`;Q=!0,clearInterval(j),B(Error(Y)),g("error","run.timeout",{...Z,elapsedMs:Math.round(performance.now()-H)}),R3(f,(V)=>V.sessionId===J.sessionId,Y),Y$(f,(V)=>V.sessionId===J.sessionId,Y),f.sessionHost.abort(J.sessionId,Y).catch((V)=>{g("error","run.timeout_abort_failed",{...Z,error:V})})},W)})])}finally{if(Q=!0,clearInterval(j),A)clearTimeout(A)}}async function aP(f,$){let J=Nf($),W=$.payload&&typeof $.payload==="object"?$.payload:{},H=typeof W.prompt==="string"?W.prompt:typeof W.input==="string"?W.input:"";if(!H.trim())return m($,"invalid_session_input","session input requires a prompt string");f.publish(f.buildEvent("run.started",void 0,J));let Q=W.attachments&&typeof W.attachments==="object"&&!Array.isArray(W.attachments)?W.attachments:void 0,Z=Array.isArray(Q?.userFiles)?Q.userFiles.filter((P)=>typeof P==="string"):void 0,j=BO(W);f.suppressNextTerminalEventBySession.set(J,"run.start.reply");let X;try{X=await YO(f,$,{sessionId:J,prompt:H,delivery:W.delivery==="queue"||W.delivery==="steer"?W.delivery:void 0,userImages:Array.isArray(Q?.userImages)?Q.userImages:void 0,userFiles:Z,timeoutMs:j},j)}catch(P){if(f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J);throw f.publish(f.buildEvent("run.failed",{reason:"error",error:P instanceof Error?P.message:String(P)},J)),P}if(X){let P=await df(f,J),B=PO(X);if(f.publish(f.buildEvent(AO(X.finishReason),{reason:X.finishReason,...B?{error:B}:{},result:X,...P?{snapshot:P}:{}},J)),f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J)}else f.suppressNextTerminalEventBySession.delete(J);let A=await df(f,J);return u($,X||A?{...X?{result:X}:{},...A?{snapshot:A}:{}}:void 0)}async function tP(f,$){let J=Nf($),W=typeof $.payload?.reason==="string"?$.payload.reason:"Run was aborted before pending approval or capability request was resolved.";return R3(f,(H)=>H.sessionId===J,W),await f.sessionHost.abort(J,$.payload?.reason),Y$(f,(H)=>H.sessionId===J,W),f.publish(f.buildEvent("run.aborted",{reason:W},J)),u($,{applied:!0})}async function sP(f,$){let J=X2($.payload?.payload);if(!J)return m($,"invalid_hook_payload","session.hook requires a valid hook event payload");return await f.sessionHost.dispatchHookEvent(J),u($,{applied:!0})}async function oP(f,$){switch($.type){case"chunk":return;case"agent_event":await VO(f,$);return;case"hook":if($.payload.hookEventName==="tool_call")f.publish(f.buildEvent("tool.started",{toolName:$.payload.toolName},$.payload.sessionId));else if($.payload.hookEventName==="tool_result")f.publish(f.buildEvent("tool.finished",{toolName:$.payload.toolName},$.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:$.payload.sessionId,summary:$.payload.summary,lastEvent:$.payload.lifecycle};f.publish(f.buildEvent("team.progress",J,$.payload.sessionId));return}case"pending_prompts":f.publish(f.buildEvent("session.pending_prompts",{sessionId:$.payload.sessionId,prompts:$.payload.prompts},$.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:$.payload.id,prompt:$.payload.prompt,delivery:$.payload.delivery,attachmentCount:$.payload.attachmentCount};f.publish(f.buildEvent("session.pending_prompt_submitted",{sessionId:$.payload.sessionId,prompt:J},$.payload.sessionId));return}case"session_snapshot":f.publish(f.buildEvent("session.updated",{sessionId:$.payload.sessionId,snapshot:$.payload.snapshot},$.payload.sessionId));return;case"status":{let[J,W]=await Promise.all([cf(f,$.payload.sessionId),df(f,$.payload.sessionId)]);if(J)f.publish(f.buildEvent("session.updated",{session:J,...W?{snapshot:W}:{}},$.payload.sessionId));return}case"ended":await RO(f,$);return;default:return}}async function VO(f,$){let{sessionId:J,event:W}=$.payload;if(W.type==="iteration_start"){f.publish(f.buildEvent("iteration.started",{iteration:W.iteration},J));return}if(W.type==="iteration_end"){f.publish(f.buildEvent("iteration.finished",{iteration:W.iteration,hadToolCalls:W.hadToolCalls,toolCallCount:W.toolCallCount},J));return}if(W.type==="content_start"){if(W.contentType==="text"&&typeof W.text==="string"&&W.text.length>0){f.publish(f.buildEvent("assistant.delta",{text:W.text},J));return}if(W.contentType==="reasoning"){if(W.redacted&&!W.reasoning){f.publish(f.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof W.reasoning==="string"&&W.reasoning.length>0)f.publish(f.buildEvent("reasoning.delta",{text:W.reasoning,redacted:W.redacted===!0},J));return}if(W.contentType==="tool"){f.publish(f.buildEvent("tool.started",{toolCallId:W.toolCallId,toolName:W.toolName,input:W.input},J));return}}if(W.type==="content_end"){switch(W.contentType){case"text":f.publish(f.buildEvent("assistant.finished",{text:W.text},J));break;case"reasoning":f.publish(f.buildEvent("reasoning.finished",{reasoning:W.reasoning},J));break;case"tool":f.publish(f.buildEvent("tool.finished",{toolCallId:W.toolCallId,toolName:W.toolName,output:W.output,error:W.error},J));break}return}if(W.type==="usage"){let H;try{H=await f.sessionHost.getAccumulatedUsage?.(J)}catch{H=void 0}f.publish(f.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:W.inputTokens,outputTokens:W.outputTokens,cacheReadTokens:W.cacheReadTokens??0,cacheWriteTokens:W.cacheWriteTokens??0,totalCost:W.cost??0},totals:{inputTokens:W.totalInputTokens,outputTokens:W.totalOutputTokens,cacheReadTokens:W.totalCacheReadTokens??0,cacheWriteTokens:W.totalCacheWriteTokens??0,totalCost:W.totalCost??0},usage:H?.usage,aggregateUsage:H?.aggregateUsage,agent:{kind:$.payload.teamRole==="teammate"?"teammate":W.parentAgentId?"subagent":"lead",agentId:W.agentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamAgentId:$.payload.teamAgentId,teamRole:$.payload.teamRole}},J));return}if(W.type==="done")f.publish(f.buildEvent("agent.done",{reason:W.reason,text:W.text,iterations:W.iterations,usage:W.usage},J))}async function RO(f,$){let J=f.suppressNextTerminalEventBySession.get($.payload.sessionId),W=J===$.payload.reason||J==="run.start.reply";if(W)f.suppressNextTerminalEventBySession.delete($.payload.sessionId);let[H,Q]=await Promise.all([cf(f,$.payload.sessionId),df(f,$.payload.sessionId)]);if($.payload.reason==="completed"){let Z=await xP(H);f.publish(f.buildEvent("ui.notify",Z,$.payload.sessionId))}if(W)return;f.publish(f.buildEvent($.payload.reason==="aborted"?"run.aborted":$.payload.reason==="error"||$.payload.reason==="failed"?"run.failed":"run.completed",{reason:$.payload.reason,...Q?{snapshot:Q}:{}},$.payload.sessionId))}import{createSessionId as fB,parseRuntimeConfigExtensions as $B}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as av,HUB_COMPACTION_CAPABILITY as tv,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as sv,HUB_HOOK_CAPABILITY_PREFIX as ov,HUB_MISTAKE_LIMIT_CAPABILITY as ev,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as fu,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as $u,isHubToolExecutorName as FO}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Zu,HUB_COMPACTION_CAPABILITY as ju,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Xu,HUB_HOOK_CAPABILITY_PREFIX as Au,HUB_MISTAKE_LIMIT_CAPABILITY as Pu,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Bu,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Yu}from"@cline/shared";var KO=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function e$(f){return f&&typeof f==="object"&&!Array.isArray(f)?JSON.parse(JSON.stringify(f)):void 0}function yO(f,$){let J=typeof f.name==="string"?f.name.trim():"",W=typeof f.description==="string"?f.description:"",H=typeof f.capabilityName==="string"?f.capabilityName.trim():"",Q=e$(f.inputSchema);if(!J||!W||!Q||!H||$.has(H))return;return $.add(H),{kind:"tool",capabilityName:H,name:J,description:W,inputSchema:Q,...e$(f.lifecycle)?{lifecycle:e$(f.lifecycle)}:{}}}function y3(f){if(!Array.isArray(f))return[];let $=[],J=new Set;for(let W of f){if(!W||typeof W!=="object"||Array.isArray(W))continue;let H=W,Q=H.kind,Z=typeof H.capabilityName==="string"?H.capabilityName.trim():"";if(!Z||J.has(Z))continue;if(Q==="tool"){let j=yO(H,J);if(j)$.push(j);continue}if(Q==="toolExecutor"){let j=H.executor;if(!FO(j))continue;J.add(Z),$.push({kind:"toolExecutor",capabilityName:Z,executor:j});continue}if(Q==="hook"){let j=typeof H.name==="string"?H.name.trim():"";if(!j)continue;J.add(Z),$.push({kind:"hook",capabilityName:Z,name:j});continue}if(Q==="compaction"){J.add(Z),$.push({kind:"compaction",capabilityName:Z,...e$(H.config)?{config:e$(H.config)}:{}});continue}if(Q==="checkpoint"){J.add(Z),$.push({kind:"checkpoint",capabilityName:Z,...e$(H.config)?{config:e$(H.config)}:{}});continue}if(Q==="mistakeLimit"){J.add(Z),$.push({kind:"mistakeLimit",capabilityName:Z});continue}if(Q==="userInstructionService")J.add(Z),$.push({kind:"userInstructionService",capabilityName:Z})}return $}function eP(f){return{agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,metadata:f.metadata}}function UO(f){return Object.hasOwn(f,"update")?f.update:f}function w4(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function GO(f){let $=(f??[]).map(w4).filter(Boolean);return $.length>0?new Set($):void 0}function TO(f,$,J){if(!J)return!0;let W=w4(f),H=w4($),Q=W.includes(":")?W.split(":").at(-1)??W:W,Z=H.includes(":")?H.split(":").at(-1)??H:H;return J.has(W)||J.has(H)||J.has(Q)||J.has(Z)}function K3(f,$){let J=GO($);return f.records.skill.map((W)=>({id:W.id,name:W.item.name,description:"description"in W.item&&typeof W.item.description==="string"?W.item.description:void 0,disabled:W.item.disabled===!0,skill:W.item})).filter((W)=>TO(W.id,W.name,J))}function DO(f,$){let J=async(W,H)=>{let Q=w4(W),j=K3(f,$).filter((Y)=>Y.id===Q||w4(Y.name)===Q||Y.id.endsWith(`:${Q}`)).filter((Y)=>!Y.disabled);if(j.length!==1)return j.length>1?`Skill "${W}" is ambiguous. Use one of: ${j.map((Y)=>Y.id).join(", ")}`:`Skill "${W}" not found.`;let X=j[0].skill,A=H?.trim(),P=A?`
701
+ <command-args>${A}</command-args>`:"",B=X.description?.trim()?`Description: ${X.description.trim()}
702
+
703
+ `:"";return`<command-name>${X.name}</command-name>${P}
704
704
  <command-instructions>
705
- ${Y}${P.instructions}
706
- </command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>W3(f,$).map(({skill:H,...W})=>W),enumerable:!0}),J}function SL(f,$,J,H){let W={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},Q=async()=>{let Z=await H(f,J.capabilityName,{},$);if(Z?.snapshot)W=Z.snapshot};return{start:Q,stop:()=>{},refreshType:async()=>{await Q()},listRecords:(Z)=>[...W.records[Z]],listRuntimeCommands:()=>[...W.runtimeCommands],resolveRuntimeSlashCommand:(Z)=>{if(!Z.startsWith("/")||Z.length<2)return Z;let P=Z.match(/^\/(\S+)/)?.[1];if(!P)return Z;let X=W.runtimeCommands.find((V)=>V.name===P);return X?`${X.instructions}${Z.slice(P.length+1)}`:Z},hasConfiguredSkills:(Z)=>W3(W,Z).some((j)=>!j.disabled),createExtension:(Z)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[Z.includeRules?"rules":void 0,Z.registerSkillsTool?"tools":void 0,Z.includeSkills||Z.includeWorkflows?"commands":void 0].filter((j)=>Boolean(j))},setup(j){if(Z.includeRules)j.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>J1(W.records.rule.map((P)=>P.item).filter((P)=>P.disabled!==!0))});if(Z.registerSkillsTool)j.registerTool(h$(EL(W,Z.allowedSkillNames)));for(let P of W.runtimeCommands.filter((X)=>X.kind==="skill"&&Z.includeSkills||X.kind==="workflow"&&Z.includeWorkflows))j.registerCommand({name:P.name,description:P.description,handler:(X)=>{let V=X.trim();return V?`${P.instructions}
705
+ ${B}${X.instructions}
706
+ </command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>K3(f,$).map(({skill:W,...H})=>H),enumerable:!0}),J}function _O(f,$,J,W){let H={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},Q=async()=>{let Z=await W(f,J.capabilityName,{},$);if(Z?.snapshot)H=Z.snapshot};return{start:Q,stop:()=>{},refreshType:async()=>{await Q()},listRecords:(Z)=>[...H.records[Z]],listRuntimeCommands:()=>[...H.runtimeCommands],resolveRuntimeSlashCommand:(Z)=>{if(!Z.startsWith("/")||Z.length<2)return Z;let X=Z.match(/^\/(\S+)/)?.[1];if(!X)return Z;let A=H.runtimeCommands.find((P)=>P.name===X);return A?`${A.instructions}${Z.slice(X.length+1)}`:Z},hasConfiguredSkills:(Z)=>K3(H,Z).some((j)=>!j.disabled),createExtension:(Z)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[Z.includeRules?"rules":void 0,Z.registerSkillsTool?"tools":void 0,Z.includeSkills||Z.includeWorkflows?"commands":void 0].filter((j)=>Boolean(j))},setup(j){if(Z.includeRules)j.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>H1(H.records.rule.map((X)=>X.item).filter((X)=>X.disabled!==!0))});if(Z.registerSkillsTool)j.registerTool(M$(DO(H,Z.allowedSkillNames)));for(let X of H.runtimeCommands.filter((A)=>A.kind==="skill"&&Z.includeSkills||A.kind==="workflow"&&Z.includeWorkflows))j.registerCommand({name:X.name,description:X.description,handler:(A)=>{let P=A.trim();return P?`${X.instructions}
707
707
 
708
- ${V}`:P.instructions}})}})}}function kL(f,$,J,H){let W=J.map((Q)=>[Q.executor,async(...Z)=>{let j=Z.at(-1),P=Z.slice(0,-1);return(await H(f,Q.capabilityName,{executor:Q.executor,args:P,context:EV(j)},$))?.result}]);return W.length>0?Object.fromEntries(W):void 0}function mL(f,$,J,H){if(J.length===0)return;return J.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema,lifecycle:W.lifecycle,async execute(Q,Z){return(await H(f,W.capabilityName,{toolName:W.name,input:Q,context:EV(Z)},$,Z.emitUpdate?(P)=>{Z.emitUpdate?.(bL(P))}:void 0))?.result}}))}function IL(f,$,J,H){let W=new Map(J.map((Z)=>[Z.name,Z])),Q={};for(let Z of NL){let j=W.get(Z);if(!j)continue;Q[Z]=async(P)=>{return(await H(f,j.capabilityName,{context:P},$))?.control}}return Object.keys(Q).length>0?Q:void 0}function Z3(f){let $=f.contributions.filter((P)=>P.kind==="toolExecutor"),J=f.contributions.filter((P)=>P.kind==="tool"),H=f.contributions.filter((P)=>P.kind==="hook"),W=f.contributions.find((P)=>P.kind==="compaction"),Q=f.contributions.find((P)=>P.kind==="checkpoint"),Z=f.contributions.find((P)=>P.kind==="mistakeLimit"),j=f.contributions.find((P)=>P.kind==="userInstructionService");return{hasClientContributions:f.contributions.length>0,toolExecutors:kL(f.sessionId,f.targetClientId,$,f.requestCapability),localRuntime:{...H.length>0?{hooks:IL(f.sessionId,f.targetClientId,H,f.requestCapability)}:{},...J.length>0?{extraTools:mL(f.sessionId,f.targetClientId,J,f.requestCapability)}:{},...W?{compaction:{...f.sessionConfig?.compaction??{},...W.config,compact:async(P)=>{return(await f.requestCapability(f.sessionId,W.capabilityName,{context:P},f.targetClientId))?.result}}}:{},...Q?{checkpoint:{...f.sessionConfig?.checkpoint??{},...Q.config,createCheckpoint:async(P)=>{return(await f.requestCapability(f.sessionId,Q.capabilityName,{context:P},f.targetClientId))?.result}}}:{},...Z?{onConsecutiveMistakeLimitReached:async(P)=>{return(await f.requestCapability(f.sessionId,Z.capabilityName,{context:P},f.targetClientId))?.result}}:{},...j?{userInstructionService:SL(f.sessionId,f.targetClientId,j,f.requestCapability)}:{}}}}var mV="hubCapabilityOwnerClientId";function IV(f,$){f[mV]=$}function xL(f){let $=f?.[mV];return typeof $==="string"&&$.trim()?$.trim():void 0}async function xV(f,$,J){let H=performance.now(),W={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:$.sessionId};x("info","session.create.begin",W);let Q=$.payload&&typeof $.payload==="object"?$.payload:{},Z=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{},j=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0,P=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{};if(typeof j?.mode==="string")Z.mode=j.mode;else if(typeof P.mode==="string")Z.mode=P.mode;if(typeof j?.systemPrompt==="string")Z.systemPrompt=j.systemPrompt;else if(typeof P.systemPrompt==="string")Z.systemPrompt=P.systemPrompt;if(j?.checkpoint?.enabled===!0)Z.checkpointEnabled=!0;else if(P.checkpointEnabled===!0)Z.checkpointEnabled=!0;let X=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},V=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():"";if(!V)return x("warn","session.create.invalid",{...W,reason:"missing_workspace_root"}),m($,"invalid_session_create","session.create requires workspaceRoot or cwd");let Y=$.clientId?.trim()||"hub-client",B=Q3(P.clientContributions);if(x("info","session.create.contributions_parsed",{...W,clientId:Y,workspaceRoot:V,cwd:typeof Q.cwd==="string"?Q.cwd:void 0,contributionCount:B.length}),B.length>0)IV(Z,Y);let R=(typeof j?.sessionId==="string"?j.sessionId.trim():"")||SV(),U=kV(P.configExtensions);x("info","session.create.runtime_build.begin",{...W,sessionId:R,configExtensionCount:U?.length??0});let y=Z3({sessionId:R,targetClientId:Y,contributions:B,sessionConfig:j,requestCapability:f.requestCapability});x("info","session.create.start_session.begin",{...W,sessionId:R,provider:j?.providerId??(typeof X.provider==="string"?X.provider:typeof Z.provider==="string"?Z.provider:"hub"),model:j?.modelId??(typeof X.model==="string"?X.model:typeof Z.model==="string"?Z.model:"hub")});let F=await f.sessionHost.startSession({source:typeof Z.source==="string"?Z.source:void 0,interactive:Z.interactive!==!1,sessionMetadata:Object.keys(Z).length>0?Z:void 0,initialMessages:Array.isArray(Q.initialMessages)?Q.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:U,...y.localRuntime},capabilities:{toolExecutors:y.toolExecutors,requestToolApproval:J},config:{...j??{},sessionId:R,providerId:j?.providerId??(typeof X.provider==="string"?X.provider:typeof Z.provider==="string"?Z.provider:"hub"),modelId:j?.modelId??(typeof X.model==="string"?X.model:typeof Z.model==="string"?Z.model:"hub"),apiKey:j?.apiKey??(typeof X.apiKey==="string"?X.apiKey:void 0),cwd:j?.cwd??(typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():V),workspaceRoot:j?.workspaceRoot??V,systemPrompt:j?.systemPrompt??(typeof P.systemPrompt==="string"?P.systemPrompt:""),mode:j?.mode??(P.mode==="plan"||P.mode==="yolo"?P.mode:"act"),maxIterations:j?.maxIterations??(typeof P.maxIterations==="number"?P.maxIterations:void 0),enableTools:j?.enableTools??P.enableTools!==!1,enableSpawnAgent:j?.enableSpawnAgent??P.enableSpawn!==!1,enableAgentTeams:j?.enableAgentTeams??P.enableTeams!==!1,checkpoint:j?.checkpoint??(P.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:j?.teamName??(typeof Z.teamName==="string"?Z.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):P.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});x("info","session.create.start_session.end",{...W,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-H),hasImmediateResult:!!F.result}),HH(f,F.sessionId,Y,"creator",{interactive:Z.interactive!==!1}),x("info","session.create.read_records.begin",{...W,sessionId:F.sessionId});let[K,M]=await Promise.all([If(f,F.sessionId),xf(f,F.sessionId)]);if(x("info","session.create.read_records.end",{...W,sessionId:F.sessionId,hasSession:!!K,hasSnapshot:!!M,elapsedMs:Math.round(performance.now()-H)}),K)f.publish(f.buildEvent("session.created",{session:K,...M?{snapshot:M}:{}},F.sessionId));return x("info","session.create.reply",{...W,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-H)}),v($,{session:K,...M?{snapshot:M}:{}})}async function gV(f,$,J){let H=$.payload&&typeof $.payload==="object"?$.payload:{},W=typeof H.sessionId==="string"?H.sessionId.trim():$.sessionId?.trim()||"",Q=H.checkpointRunCount;if(!W)return m($,"invalid_restore","session.restore requires a session id");let Z=H.restore&&typeof H.restore==="object"?H.restore:{},j=Z.messages!==!1;if(typeof Q!=="number")return m($,"invalid_restore","checkpointRunCount must be a positive integer");try{let P=H.sessionConfig&&typeof H.sessionConfig==="object"?JSON.parse(JSON.stringify(H.sessionConfig)):void 0;if(j&&!P)return m($,"invalid_restore","sessionConfig is required when restore.messages is true");let X=H.runtimeOptions&&typeof H.runtimeOptions==="object"?H.runtimeOptions:{},V=H.metadata&&typeof H.metadata==="object"?JSON.parse(JSON.stringify(H.metadata)):{};if(typeof P?.mode==="string")V.mode=P.mode;else if(typeof X.mode==="string")V.mode=X.mode;if(typeof P?.systemPrompt==="string")V.systemPrompt=P.systemPrompt;else if(typeof X.systemPrompt==="string")V.systemPrompt=X.systemPrompt;if(P?.checkpoint?.enabled===!0)V.checkpointEnabled=!0;else if(X.checkpointEnabled===!0)V.checkpointEnabled=!0;let Y=H.modelSelection&&typeof H.modelSelection==="object"?H.modelSelection:{},B=$.clientId?.trim()||"hub-client",A=Q3(X.clientContributions);if(A.length>0)IV(V,B);let U=(typeof P?.sessionId==="string"?P.sessionId.trim():"")||SV(),y=kV(X.configExtensions),F=Z3({sessionId:U,targetClientId:B,contributions:A,sessionConfig:P,requestCapability:f.requestCapability}),M=await new Z$().restoreCheckpoint({sessionId:W,checkpointRunCount:Q,restore:{messages:Z.messages,workspace:Z.workspace,omitCheckpointMessageFromSession:Z.omitCheckpointMessageFromSession===!0},start:P,cwd:typeof P?.cwd==="string"&&P.cwd.trim()||typeof P?.workspaceRoot==="string"&&P.workspaceRoot.trim()||void 0,getSession:(z)=>f.sessionHost.getSession(z),readMessages:(z)=>f.sessionHost.readSessionMessages(z),buildStartInput:(z)=>{if(z.restoredCheckpointMetadata)V.checkpoint=z.restoredCheckpointMetadata;let u=typeof H.workspaceRoot==="string"&&H.workspaceRoot.trim()?H.workspaceRoot.trim():typeof H.cwd==="string"&&H.cwd.trim()?H.cwd.trim():z.sourceSession.workspaceRoot||z.sourceSession.cwd;return{source:typeof V.source==="string"?V.source:void 0,interactive:V.interactive!==!1,sessionMetadata:{...V,restoredFromSessionId:W,restoredCheckpointRunCount:Q},initialMessages:z.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:y,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...P??{},sessionId:U,providerId:P?.providerId??(typeof Y.provider==="string"?Y.provider:z.sourceSession.provider),modelId:P?.modelId??(typeof Y.model==="string"?Y.model:z.sourceSession.model),apiKey:P?.apiKey??(typeof Y.apiKey==="string"?Y.apiKey:""),cwd:P?.cwd??z.plan.cwd,workspaceRoot:P?.workspaceRoot??u,systemPrompt:P?.systemPrompt??(typeof X.systemPrompt==="string"?X.systemPrompt:""),mode:P?.mode??(X.mode==="plan"||X.mode==="yolo"?X.mode:"act"),maxIterations:P?.maxIterations??(typeof X.maxIterations==="number"?X.maxIterations:void 0),enableTools:P?.enableTools??X.enableTools!==!1,enableSpawnAgent:P?.enableSpawnAgent??X.enableSpawn!==!1,enableAgentTeams:P?.enableAgentTeams??X.enableTeams!==!1,checkpoint:P?.checkpoint??(X.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:P?.teamName??(typeof V.teamName==="string"?V.teamName:void 0)},toolPolicies:H.toolPolicies&&typeof H.toolPolicies==="object"&&!Array.isArray(H.toolPolicies)?JSON.parse(JSON.stringify(H.toolPolicies)):X.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(z)=>f.sessionHost.startSession(z),getStartedSessionId:(z)=>z.sessionId,readRestoredSession:(z)=>f.sessionHost.getSession(z)});if(!j)return v($,{checkpoint:M.checkpoint});let T=M.startResult;if(!T)return m($,"restore_failed","Checkpoint restore did not start a session");HH(f,T.sessionId,B,"creator",{interactive:V.interactive!==!1});let[G,h]=await Promise.all([If(f,T.sessionId),xf(f,T.sessionId)]);if(G)f.publish(f.buildEvent("session.created",{session:G,...h?{snapshot:h}:{}},T.sessionId));return v($,{session:G,...h?{snapshot:h}:{},messages:M.messages??[],checkpoint:M.checkpoint})}catch(P){if(P instanceof Df)return m($,P.code,P.code==="session_not_found"?`Unknown session: ${W}`:P.message);return m($,"restore_failed",P instanceof Error?P.message:String(P))}}async function vV(f,$){let J=Mf($);if(!J)return m($,"invalid_session_attach","session.attach requires a session id");HH(f,J,$.clientId?.trim()||"hub-client","participant");let H=await If(f,J);if(H)f.publish(f.buildEvent("session.attached",{session:H},J));return H?v($,{session:H}):m($,"session_not_found",`Unknown session: ${J}`)}async function uV(f,$){let J=Mf($);if(!J)return m($,"invalid_session_detach","session.detach requires a session id");let H=$.clientId?.trim()||"hub-client",[W]=await Promise.all([If(f,J)]),Q=xL(W?.metadata)??H,Z=f.sessionState.get(J);if(Z){if(Z.participants.delete(H),Z.createdByClientId===H)Z.createdByClientId=Q;if(Z.participants.size===0)f.sessionState.delete(J)}j$(f,(X)=>X.sessionId===J&&X.targetClientId===H,`Capability owner client ${H} detached before request was resolved.`);let[j,P]=await Promise.all([If(f,J),xf(f,J)]);return f.publish(f.buildEvent("session.detached",j?{session:j,...P?{snapshot:P}:{},clientId:H}:{clientId:H},J)),v($)}async function cV(f,$){let J=Mf($),H=$.payload?.includeSnapshot===!0,[W,Q]=await Promise.all([If(f,J),H?xf(f,J):Promise.resolve(void 0)]);return W?v($,{session:W,...Q?{snapshot:Q}:{}}):m($,"session_not_found",`Unknown session: ${J}`)}async function dV(f,$){let J=Mf($);if(!J)return m($,"invalid_session_id","session.messages requires a session id");if(!await If(f,J))return m($,"session_not_found",`Unknown session: ${J}`);let W=await f.sessionHost.readSessionMessages(J);return v($,{sessionId:J,messages:W})}async function rV(f,$){let J=typeof $.payload?.limit==="number"?$.payload.limit:200,W=(await f.sessionHost.listSessions(J)).map((Q)=>$H(Q,f.sessionState.get(Q.sessionId)));return v($,{sessions:W})}async function lV(f,$){let J=Mf($),H=JH($.payload?.metadata),W=await f.sessionHost.updateSession(J,{metadata:H}),[Q,Z]=await Promise.all([If(f,J),xf(f,J)]);if(Q)f.publish(f.buildEvent("session.updated",{session:Q,...Z?{snapshot:Z}:{}},J));return{version:$.version,requestId:$.requestId,ok:W.updated,payload:{updated:W.updated,session:Q,...Z?{snapshot:Z}:{}}}}async function pV(f,$){let J=Mf($),H=await f.sessionHost.deleteSession(J);return f.sessionState.delete(J),v($,{deleted:H})}async function iV(f,$){let J=Mf($),H=f.sessionHost.pendingPrompts;if(!H)return m($,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await H.list({sessionId:J});return v($,{sessionId:J,prompts:W})}async function nV(f,$){let J=Mf($),H=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",W=typeof $.payload?.prompt==="string"?$.payload.prompt:void 0,Q=$.payload?.delivery==="queue"||$.payload?.delivery==="steer"?$.payload.delivery:void 0,Z=f.sessionHost.pendingPrompts;if(!Z)return m($,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await Z.update({sessionId:J,promptId:H,prompt:W,delivery:Q});return v($,j)}async function aV(f,$){let J=Mf($),H=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",W=f.sessionHost.pendingPrompts;if(!W)return m($,"pending_prompts_unavailable","Pending prompt service is not available.");let Q=await W.delete({sessionId:J,promptId:H});return v($,Q)}function tV(f){switch(f){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var vL=new Set(["skills","workflows","rules","tools"]);function j3(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function L4(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${$}' must be a string.`);return J}function uL(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${$}' must be a boolean.`);return J}function sV(f){if(f===void 0)return{};if(!j3(f))throw Error("settings.list payload must be an object.");return{cwd:L4(f,"cwd"),workspaceRoot:L4(f,"workspaceRoot"),availabilityContext:j3(f.availabilityContext)?f.availabilityContext:void 0}}function cL(f){if(!j3(f))throw Error("settings.toggle payload must be an object.");let{type:$}=f;if(typeof $!=="string"||!vL.has($))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools.");return{...sV(f),type:$,id:L4(f,"id"),path:L4(f,"path"),name:L4(f,"name"),enabled:uL(f,"enabled")}}class B2{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=gL("hub_");ctx;constructor(f){this.options=f;if(this.sessionHost=f.sessionHost??new j0({sessionService:new Z0(new W0),fetch:f.fetch,telemetry:f.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,sessionHost:this.sessionHost,publish:($)=>this.publish($),buildEvent:t$,requestCapability:($,J,H,W,Q)=>TV(this.ctx,$,J,H,W,Q)},this.schedules=new Q1({...f.scheduleOptions,runtimeHandlers:f.runtimeHandlers,eventPublisher:($,J)=>{let H=$==="schedule.execution.completed"?"schedule.execution_completed":$==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!H)return;this.publish(t$(H,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new $1(this.schedules),this.settings=f.settingsService??new W$,f.cronOptions)this.cronService=new $4({runtimeHandlers:f.runtimeHandlers,...f.cronOptions});this.sessionHost.subscribe(($)=>{CV(this.ctx,$).catch((J)=>{H3("session event handling failed",J)})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch(f){console.error("[hub] cron service start failed",f)}}async stop(){for(let f of this.pendingApprovals.keys())$3(this.ctx,f,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(j$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch(f){console.error("[hub] cron service stop failed",f)}}async handleCommand(f){switch(f.command){case"client.register":return LV(this.ctx,f);case"client.update":return zV(this.ctx,f);case"client.unregister":return OV(this.ctx,f,($)=>{this.listeners.delete($),this.detachClientFromSessions($)});case"client.list":return NV(this.ctx,f);case"session.create":return await xV(this.ctx,f,($)=>f3(this.ctx,$));case"session.restore":return await gV(this.ctx,f,($)=>f3(this.ctx,$));case"session.attach":return await vV(this.ctx,f);case"session.detach":return await uV(this.ctx,f);case"session.get":return await cV(this.ctx,f);case"session.messages":return await dV(this.ctx,f);case"session.list":return await rV(this.ctx,f);case"session.update":return await lV(this.ctx,f);case"session.pending_prompts":return await iV(this.ctx,f);case"session.update_pending_prompt":return await nV(this.ctx,f);case"session.remove_pending_prompt":return await aV(this.ctx,f);case"session.delete":return await pV(this.ctx,f);case"session.hook":return await wV(this.ctx,f);case"run.start":case"session.send_input":return await qV(this.ctx,f);case"run.abort":return await bV(this.ctx,f);case"capability.request":return await MV(this.ctx,f);case"approval.respond":return await GV(this.ctx,f);case"capability.respond":return _V(this.ctx,f);case"capability.progress":return DV(this.ctx,f);case"ui.notify":return this.publish(t$("ui.notify",f.payload??{})),v(f);case"ui.show_window":return this.publish(t$("ui.show_window",f.payload??{})),v(f);case"settings.list":return await this.handleSettingsList(f);case"settings.toggle":return await this.handleSettingsToggle(f);case"settings.get":case"settings.patch":return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"not_implemented",message:`${f.command} is not implemented yet.`}};default:{let $=await this.scheduleCommands.handleCommand(f);if($.ok){let J=tV(f.command);if(J)this.publish(t$(J,$.payload))}return $}}}async handleSettingsList(f){try{let $=await this.settings.list(sV(f.payload));return{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_list_failed",message:$ instanceof Error?$.message:String($)}}}}async handleSettingsToggle(f){try{let $=await this.settings.toggle(cL(f.payload));return this.publish(t$("settings.changed",{types:$.changedTypes,snapshot:$.snapshot})),{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$.snapshot,changedTypes:$.changedTypes}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_toggle_failed",message:$ instanceof Error?$.message:String($)}}}}subscribe(f,$,J){let H=this.listeners.get(f)??new Set,W={sessionId:J?.sessionId,listener:$};return H.add(W),this.listeners.set(f,H),()=>{let Q=this.listeners.get(f);if(!Q)return;if(Q.delete(W),Q.size===0)this.listeners.delete(f)}}detachClientFromSessions(f){for(let[$,J]of this.sessionState.entries())if(J.participants.delete(f),J.participants.size===0)this.sessionState.delete($);j$(this.ctx,($)=>$.targetClientId===f,`Capability owner client ${f} disconnected before request was resolved.`)}publish(f){for(let $ of this.listeners.values())for(let J of $){if(J.sessionId&&J.sessionId!==f.sessionId)continue;try{J.listener(f)}catch(H){H3(`listener threw while publishing ${f.event}`,H)}}}}import{timingSafeEqual as pL}from"node:crypto";import iL from"node:http";import nL from"node:net";import{URL as fY}from"node:url";import{WebSocketServer as aL}from"ws";import{HUB_COMMAND_SLOW_LOG_MS as dL,resolveHubCommandTimeoutMs as rL,safeJsonParse as lL}from"@cline/shared";function oV(f){return{command:f.envelope.command,requestId:f.envelope.requestId,clientId:f.envelope.clientId,sessionId:f.envelope.sessionId}}function eV(f,$,J){return{version:f.envelope.version,requestId:f.envelope.requestId,ok:!1,error:{code:$,message:J}}}class T4{transport;constructor(f){this.transport=f}attach(f){let $=new Map,J=new Set,H=!1,W=(P)=>{try{f.send(JSON.stringify(P))}catch(X){console.error(`[hub] failed to send websocket frame: ${X instanceof Error?X.stack||X.message:String(X)}`)}},Q=(P)=>{W({kind:"event",envelope:P})},Z=async(P)=>{try{let X=JSON.parse(P.data);switch(X.kind){case"command":{let V=performance.now(),Y=!1,B=oV(X);x("info","command.start",B);let A=setTimeout(()=>{if(Y)return;x("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-V)})},dL),R=this.transport.command(X.envelope);R.then((T)=>{if(!Y)return;x(T.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-V),ok:T.ok,errorCode:T.error?.code,errorMessage:T.error?.message})},(T)=>{if(!Y)return;x("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-V),error:T})});let U=!1,y,F,K=rL(X.envelope.command,X.envelope.timeoutMs);try{F=K===null?await R:await Promise.race([R,new Promise((T)=>{y=setTimeout(()=>{U=!0,T(eV(X,"hub_command_timeout",`Hub command ${X.envelope.command} did not complete within ${K}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${X.envelope.requestId}.`))},K)})])}catch(T){if(clearTimeout(A),y)clearTimeout(y);throw T}if(Y=U,clearTimeout(A),y)clearTimeout(y);let M=Math.round(performance.now()-V);if(U)x("error","command.timeout",{...B,durationMs:M,timeoutMs:K});else x(F.ok?"info":"warn","command.end",{...B,durationMs:M,ok:F.ok,errorCode:F.error?.code,errorMessage:F.error?.message});if(X.envelope.command==="client.register"&&F.ok){let G=(X.envelope.payload??{}).clientId?.trim()||X.envelope.clientId?.trim();if(G)J.add(G)}else if(X.envelope.command==="client.unregister"&&F.ok){let T=X.envelope.clientId?.trim();if(T)J.delete(T)}W({kind:"reply",envelope:F});break}case"stream.subscribe":{let V=`${X.clientId}:${X.sessionId??"*"}`;if($.has(V))break;let Y=await this.transport.subscribe(X.clientId,Q,{sessionId:X.sessionId});$.set(V,Y);break}case"stream.unsubscribe":{let V=`${X.clientId}:${X.sessionId??"*"}`;$.get(V)?.(),$.delete(V);break}case"reply":case"event":break}}catch(X){let V=typeof P.data==="string"?lL(P.data):void 0;if(!V||V.kind!=="command"){x("error","rejected malformed websocket frame",{error:X});return}x("error","command.error",{...oV(V),error:X}),W({kind:"reply",envelope:eV(V,"command_failed",X instanceof Error?X.message:"Unknown hub error")})}},j=()=>{if(H)return;H=!0;for(let P of $.values())P();$.clear();for(let P of J)this.transport.command({version:"v1",command:"client.unregister",clientId:P});J.clear(),f.removeEventListener("message",Z),f.removeEventListener("close",j)};return f.addEventListener("message",Z),f.addEventListener("close",j),j}}class D4{transport;constructor(f){this.transport=f}command(f){return this.transport.handleCommand(f)}subscribe(f,$,J){return this.transport.subscribe(f,$,J)}}function tL(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();return String(f)}function sL(f){return{send($){f.send($)},addEventListener($,J){if($==="message"){f.on("message",(H)=>{J({data:tL(H)})});return}f.on("close",J)},removeEventListener(){}}}function oL(f){try{f.write(`HTTP/1.1 400 Bad Request\r
708
+ ${P}`:X.instructions}})}})}}function MO(f,$,J,W){let H=J.map((Q)=>[Q.executor,async(...Z)=>{let j=Z.at(-1),X=Z.slice(0,-1);return(await W(f,Q.capabilityName,{executor:Q.executor,args:X,context:eP(j)},$))?.result}]);return H.length>0?Object.fromEntries(H):void 0}function LO(f,$,J,W){if(J.length===0)return;return J.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema,lifecycle:H.lifecycle,async execute(Q,Z){return(await W(f,H.capabilityName,{toolName:H.name,input:Q,context:eP(Z)},$,Z.emitUpdate?(X)=>{Z.emitUpdate?.(UO(X))}:void 0))?.result}}))}function hO(f,$,J,W){let H=new Map(J.map((Z)=>[Z.name,Z])),Q={};for(let Z of KO){let j=H.get(Z);if(!j)continue;Q[Z]=async(X)=>{return(await W(f,j.capabilityName,{context:X},$))?.control}}return Object.keys(Q).length>0?Q:void 0}function U3(f){let $=f.contributions.filter((X)=>X.kind==="toolExecutor"),J=f.contributions.filter((X)=>X.kind==="tool"),W=f.contributions.filter((X)=>X.kind==="hook"),H=f.contributions.find((X)=>X.kind==="compaction"),Q=f.contributions.find((X)=>X.kind==="checkpoint"),Z=f.contributions.find((X)=>X.kind==="mistakeLimit"),j=f.contributions.find((X)=>X.kind==="userInstructionService");return{hasClientContributions:f.contributions.length>0,toolExecutors:MO(f.sessionId,f.targetClientId,$,f.requestCapability),localRuntime:{...W.length>0?{hooks:hO(f.sessionId,f.targetClientId,W,f.requestCapability)}:{},...J.length>0?{extraTools:LO(f.sessionId,f.targetClientId,J,f.requestCapability)}:{},...H?{compaction:{...f.sessionConfig?.compaction??{},...H.config,compact:async(X)=>{return(await f.requestCapability(f.sessionId,H.capabilityName,{context:X},f.targetClientId))?.result}}}:{},...Q?{checkpoint:{...f.sessionConfig?.checkpoint??{},...Q.config,createCheckpoint:async(X)=>{return(await f.requestCapability(f.sessionId,Q.capabilityName,{context:X},f.targetClientId))?.result}}}:{},...Z?{onConsecutiveMistakeLimitReached:async(X)=>{return(await f.requestCapability(f.sessionId,Z.capabilityName,{context:X},f.targetClientId))?.result}}:{},...j?{userInstructionService:_O(f.sessionId,f.targetClientId,j,f.requestCapability)}:{}}}}var JB="hubCapabilityOwnerClientId";function WB(f,$){f[JB]=$}function OO(f){let $=f?.[JB];return typeof $==="string"&&$.trim()?$.trim():void 0}async function HB(f,$,J){let W=performance.now(),H={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:$.sessionId};g("info","session.create.begin",H);let Q=$.payload&&typeof $.payload==="object"?$.payload:{},Z=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{},j=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0,X=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{};if(typeof j?.mode==="string")Z.mode=j.mode;else if(typeof X.mode==="string")Z.mode=X.mode;if(typeof j?.systemPrompt==="string")Z.systemPrompt=j.systemPrompt;else if(typeof X.systemPrompt==="string")Z.systemPrompt=X.systemPrompt;if(j?.checkpoint?.enabled===!0)Z.checkpointEnabled=!0;else if(X.checkpointEnabled===!0)Z.checkpointEnabled=!0;let A=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},P=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():"";if(!P)return g("warn","session.create.invalid",{...H,reason:"missing_workspace_root"}),m($,"invalid_session_create","session.create requires workspaceRoot or cwd");let B=$.clientId?.trim()||"hub-client",Y=y3(X.clientContributions);if(g("info","session.create.contributions_parsed",{...H,clientId:B,workspaceRoot:P,cwd:typeof Q.cwd==="string"?Q.cwd:void 0,contributionCount:Y.length}),Y.length>0)WB(Z,B);let R=(typeof j?.sessionId==="string"?j.sessionId.trim():"")||fB(),U=$B(X.configExtensions);g("info","session.create.runtime_build.begin",{...H,sessionId:R,configExtensionCount:U?.length??0});let K=U3({sessionId:R,targetClientId:B,contributions:Y,sessionConfig:j,requestCapability:f.requestCapability});g("info","session.create.start_session.begin",{...H,sessionId:R,provider:j?.providerId??(typeof A.provider==="string"?A.provider:typeof Z.provider==="string"?Z.provider:"hub"),model:j?.modelId??(typeof A.model==="string"?A.model:typeof Z.model==="string"?Z.model:"hub")});let F=await f.sessionHost.startSession({source:typeof Z.source==="string"?Z.source:void 0,interactive:Z.interactive!==!1,sessionMetadata:Object.keys(Z).length>0?Z:void 0,initialMessages:Array.isArray(Q.initialMessages)?Q.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:U,...K.localRuntime},capabilities:{toolExecutors:K.toolExecutors,requestToolApproval:J},config:{...j??{},sessionId:R,providerId:j?.providerId??(typeof A.provider==="string"?A.provider:typeof Z.provider==="string"?Z.provider:"hub"),modelId:j?.modelId??(typeof A.model==="string"?A.model:typeof Z.model==="string"?Z.model:"hub"),apiKey:j?.apiKey??(typeof A.apiKey==="string"?A.apiKey:void 0),cwd:j?.cwd??(typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():P),workspaceRoot:j?.workspaceRoot??P,systemPrompt:j?.systemPrompt??(typeof X.systemPrompt==="string"?X.systemPrompt:""),mode:j?.mode??(X.mode==="plan"||X.mode==="yolo"?X.mode:"act"),maxIterations:j?.maxIterations??(typeof X.maxIterations==="number"?X.maxIterations:void 0),enableTools:j?.enableTools??X.enableTools!==!1,enableSpawnAgent:j?.enableSpawnAgent??X.enableSpawn!==!1,enableAgentTeams:j?.enableAgentTeams??X.enableTeams!==!1,checkpoint:j?.checkpoint??(X.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:j?.teamName??(typeof Z.teamName==="string"?Z.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):X.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});g("info","session.create.start_session.end",{...H,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-W),hasImmediateResult:!!F.result}),H5(f,F.sessionId,B,"creator",{interactive:Z.interactive!==!1}),g("info","session.create.read_records.begin",{...H,sessionId:F.sessionId});let[y,D]=await Promise.all([cf(f,F.sessionId),df(f,F.sessionId)]);if(g("info","session.create.read_records.end",{...H,sessionId:F.sessionId,hasSession:!!y,hasSnapshot:!!D,elapsedMs:Math.round(performance.now()-W)}),y)f.publish(f.buildEvent("session.created",{session:y,...D?{snapshot:D}:{}},F.sessionId));return g("info","session.create.reply",{...H,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-W)}),u($,{session:y,...D?{snapshot:D}:{}})}async function QB(f,$,J){let W=$.payload&&typeof $.payload==="object"?$.payload:{},H=typeof W.sessionId==="string"?W.sessionId.trim():$.sessionId?.trim()||"",Q=W.checkpointRunCount;if(!H)return m($,"invalid_restore","session.restore requires a session id");let Z=W.restore&&typeof W.restore==="object"?W.restore:{},j=Z.messages!==!1;if(typeof Q!=="number")return m($,"invalid_restore","checkpointRunCount must be a positive integer");try{let X=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0;if(j&&!X)return m($,"invalid_restore","sessionConfig is required when restore.messages is true");let A=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{},P=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{};if(typeof X?.mode==="string")P.mode=X.mode;else if(typeof A.mode==="string")P.mode=A.mode;if(typeof X?.systemPrompt==="string")P.systemPrompt=X.systemPrompt;else if(typeof A.systemPrompt==="string")P.systemPrompt=A.systemPrompt;if(X?.checkpoint?.enabled===!0)P.checkpointEnabled=!0;else if(A.checkpointEnabled===!0)P.checkpointEnabled=!0;let B=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},Y=$.clientId?.trim()||"hub-client",V=y3(A.clientContributions);if(V.length>0)WB(P,Y);let U=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||fB(),K=$B(A.configExtensions),F=U3({sessionId:U,targetClientId:Y,contributions:V,sessionConfig:X,requestCapability:f.requestCapability}),D=await new B$().restoreCheckpoint({sessionId:H,checkpointRunCount:Q,restore:{messages:Z.messages,workspace:Z.workspace,omitCheckpointMessageFromSession:Z.omitCheckpointMessageFromSession===!0},start:X,cwd:typeof X?.cwd==="string"&&X.cwd.trim()||typeof X?.workspaceRoot==="string"&&X.workspaceRoot.trim()||void 0,getSession:(L)=>f.sessionHost.getSession(L),readMessages:(L)=>f.sessionHost.readSessionMessages(L),buildStartInput:(L)=>{if(L.restoredCheckpointMetadata)P.checkpoint=L.restoredCheckpointMetadata;let q=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():L.sourceSession.workspaceRoot||L.sourceSession.cwd;return{source:typeof P.source==="string"?P.source:void 0,interactive:P.interactive!==!1,sessionMetadata:{...P,restoredFromSessionId:H,restoredCheckpointRunCount:Q},initialMessages:L.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:K,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:U,providerId:X?.providerId??(typeof B.provider==="string"?B.provider:L.sourceSession.provider),modelId:X?.modelId??(typeof B.model==="string"?B.model:L.sourceSession.model),apiKey:X?.apiKey??(typeof B.apiKey==="string"?B.apiKey:""),cwd:X?.cwd??L.plan.cwd,workspaceRoot:X?.workspaceRoot??q,systemPrompt:X?.systemPrompt??(typeof A.systemPrompt==="string"?A.systemPrompt:""),mode:X?.mode??(A.mode==="plan"||A.mode==="yolo"?A.mode:"act"),maxIterations:X?.maxIterations??(typeof A.maxIterations==="number"?A.maxIterations:void 0),enableTools:X?.enableTools??A.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??A.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??A.enableTeams!==!1,checkpoint:X?.checkpoint??(A.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof P.teamName==="string"?P.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):A.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(L)=>f.sessionHost.startSession(L),getStartedSessionId:(L)=>L.sessionId,readRestoredSession:(L)=>f.sessionHost.getSession(L)});if(!j)return u($,{checkpoint:D.checkpoint});let M=D.startResult;if(!M)return m($,"restore_failed","Checkpoint restore did not start a session");H5(f,M.sessionId,Y,"creator",{interactive:P.interactive!==!1});let[T,_]=await Promise.all([cf(f,M.sessionId),df(f,M.sessionId)]);if(T)f.publish(f.buildEvent("session.created",{session:T,..._?{snapshot:_}:{}},M.sessionId));return u($,{session:T,..._?{snapshot:_}:{},messages:D.messages??[],checkpoint:D.checkpoint})}catch(X){if(X instanceof zf)return m($,X.code,X.code==="session_not_found"?`Unknown session: ${H}`:X.message);return m($,"restore_failed",X instanceof Error?X.message:String(X))}}async function ZB(f,$){let J=Nf($);if(!J)return m($,"invalid_session_attach","session.attach requires a session id");H5(f,J,$.clientId?.trim()||"hub-client","participant");let W=await cf(f,J);if(W)f.publish(f.buildEvent("session.attached",{session:W},J));return W?u($,{session:W}):m($,"session_not_found",`Unknown session: ${J}`)}async function jB(f,$){let J=Nf($);if(!J)return m($,"invalid_session_detach","session.detach requires a session id");let W=$.clientId?.trim()||"hub-client",[H]=await Promise.all([cf(f,J)]),Q=OO(H?.metadata)??W,Z=f.sessionState.get(J);if(Z){if(Z.participants.delete(W),Z.createdByClientId===W)Z.createdByClientId=Q;if(Z.participants.size===0)f.sessionState.delete(J)}Y$(f,(A)=>A.sessionId===J&&A.targetClientId===W,`Capability owner client ${W} detached before request was resolved.`);let[j,X]=await Promise.all([cf(f,J),df(f,J)]);return f.publish(f.buildEvent("session.detached",j?{session:j,...X?{snapshot:X}:{},clientId:W}:{clientId:W},J)),u($)}async function XB(f,$){let J=Nf($),W=$.payload?.includeSnapshot===!0,[H,Q]=await Promise.all([cf(f,J),W?df(f,J):Promise.resolve(void 0)]);return H?u($,{session:H,...Q?{snapshot:Q}:{}}):m($,"session_not_found",`Unknown session: ${J}`)}async function AB(f,$){let J=Nf($);if(!J)return m($,"invalid_session_id","session.messages requires a session id");if(!await cf(f,J))return m($,"session_not_found",`Unknown session: ${J}`);let H=await f.sessionHost.readSessionMessages(J);return u($,{sessionId:J,messages:H})}async function PB(f,$){let J=typeof $.payload?.limit==="number"?$.payload.limit:200,H=(await f.sessionHost.listSessions(J)).map((Q)=>J5(Q,f.sessionState.get(Q.sessionId)));return u($,{sessions:H})}async function BB(f,$){let J=Nf($),W=W5($.payload?.metadata),H=await f.sessionHost.updateSession(J,{metadata:W}),[Q,Z]=await Promise.all([cf(f,J),df(f,J)]);if(Q)f.publish(f.buildEvent("session.updated",{session:Q,...Z?{snapshot:Z}:{}},J));return{version:$.version,requestId:$.requestId,ok:H.updated,payload:{updated:H.updated,session:Q,...Z?{snapshot:Z}:{}}}}async function YB(f,$){let J=Nf($),W=await f.sessionHost.deleteSession(J);return f.sessionState.delete(J),u($,{deleted:W})}async function VB(f,$){let J=Nf($),W=f.sessionHost.pendingPrompts;if(!W)return m($,"pending_prompts_unavailable","Pending prompt service is not available.");let H=await W.list({sessionId:J});return u($,{sessionId:J,prompts:H})}async function RB(f,$){let J=Nf($),W=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",H=typeof $.payload?.prompt==="string"?$.payload.prompt:void 0,Q=$.payload?.delivery==="queue"||$.payload?.delivery==="steer"?$.payload.delivery:void 0,Z=f.sessionHost.pendingPrompts;if(!Z)return m($,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await Z.update({sessionId:J,promptId:W,prompt:H,delivery:Q});return u($,j)}async function FB(f,$){let J=Nf($),W=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",H=f.sessionHost.pendingPrompts;if(!H)return m($,"pending_prompts_unavailable","Pending prompt service is not available.");let Q=await H.delete({sessionId:J,promptId:W});return u($,Q)}function KB(f){switch(f){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var NO=new Set(["skills","workflows","rules","tools"]);function G3(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function b4(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${$}' must be a string.`);return J}function qO(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${$}' must be a boolean.`);return J}function yB(f){if(f===void 0)return{};if(!G3(f))throw Error("settings.list payload must be an object.");return{cwd:b4(f,"cwd"),workspaceRoot:b4(f,"workspaceRoot"),availabilityContext:G3(f.availabilityContext)?f.availabilityContext:void 0}}function wO(f){if(!G3(f))throw Error("settings.toggle payload must be an object.");let{type:$}=f;if(typeof $!=="string"||!NO.has($))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools.");return{...yB(f),type:$,id:b4(f,"id"),path:b4(f,"path"),name:b4(f,"name"),enabled:qO(f,"enabled")}}class F2{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=zO("hub_");ctx;constructor(f){this.options=f;if(this.sessionHost=f.sessionHost??new X0({sessionService:new j0(new Q0),fetch:f.fetch,telemetry:f.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,sessionHost:this.sessionHost,publish:($)=>this.publish($),buildEvent:o$,requestCapability:($,J,W,H,Q)=>uP(this.ctx,$,J,W,H,Q)},this.schedules=new j1({...f.scheduleOptions,runtimeHandlers:f.runtimeHandlers,eventPublisher:($,J)=>{let W=$==="schedule.execution.completed"?"schedule.execution_completed":$==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!W)return;this.publish(o$(W,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new W1(this.schedules),this.settings=f.settingsService??new j$,f.cronOptions)this.cronService=new Z4({runtimeHandlers:f.runtimeHandlers,...f.cronOptions});this.sessionHost.subscribe(($)=>{oP(this.ctx,$).catch((J)=>{F3("session event handling failed",J)})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch(f){console.error("[hub] cron service start failed",f)}}async stop(){for(let f of this.pendingApprovals.keys())V3(this.ctx,f,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(Y$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch(f){console.error("[hub] cron service stop failed",f)}}async handleCommand(f){switch(f.command){case"client.register":return lP(this.ctx,f);case"client.update":return pP(this.ctx,f);case"client.unregister":return iP(this.ctx,f,($)=>{this.listeners.delete($),this.detachClientFromSessions($)});case"client.list":return nP(this.ctx,f);case"session.create":return await HB(this.ctx,f,($)=>Y3(this.ctx,$));case"session.restore":return await QB(this.ctx,f,($)=>Y3(this.ctx,$));case"session.attach":return await ZB(this.ctx,f);case"session.detach":return await jB(this.ctx,f);case"session.get":return await XB(this.ctx,f);case"session.messages":return await AB(this.ctx,f);case"session.list":return await PB(this.ctx,f);case"session.update":return await BB(this.ctx,f);case"session.pending_prompts":return await VB(this.ctx,f);case"session.update_pending_prompt":return await RB(this.ctx,f);case"session.remove_pending_prompt":return await FB(this.ctx,f);case"session.delete":return await YB(this.ctx,f);case"session.hook":return await sP(this.ctx,f);case"run.start":case"session.send_input":return await aP(this.ctx,f);case"run.abort":return await tP(this.ctx,f);case"capability.request":return await dP(this.ctx,f);case"approval.respond":return await gP(this.ctx,f);case"capability.respond":return rP(this.ctx,f);case"capability.progress":return cP(this.ctx,f);case"ui.notify":return this.publish(o$("ui.notify",f.payload??{})),u(f);case"ui.show_window":return this.publish(o$("ui.show_window",f.payload??{})),u(f);case"settings.list":return await this.handleSettingsList(f);case"settings.toggle":return await this.handleSettingsToggle(f);case"settings.get":case"settings.patch":return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"not_implemented",message:`${f.command} is not implemented yet.`}};default:{let $=await this.scheduleCommands.handleCommand(f);if($.ok){let J=KB(f.command);if(J)this.publish(o$(J,$.payload))}return $}}}async handleSettingsList(f){try{let $=await this.settings.list(yB(f.payload));return{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_list_failed",message:$ instanceof Error?$.message:String($)}}}}async handleSettingsToggle(f){try{let $=await this.settings.toggle(wO(f.payload));return this.publish(o$("settings.changed",{types:$.changedTypes,snapshot:$.snapshot})),{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$.snapshot,changedTypes:$.changedTypes}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_toggle_failed",message:$ instanceof Error?$.message:String($)}}}}subscribe(f,$,J){let W=this.listeners.get(f)??new Set,H={sessionId:J?.sessionId,listener:$};return W.add(H),this.listeners.set(f,W),()=>{let Q=this.listeners.get(f);if(!Q)return;if(Q.delete(H),Q.size===0)this.listeners.delete(f)}}detachClientFromSessions(f){for(let[$,J]of this.sessionState.entries())if(J.participants.delete(f),J.participants.size===0)this.sessionState.delete($);Y$(this.ctx,($)=>$.targetClientId===f,`Capability owner client ${f} disconnected before request was resolved.`)}publish(f){for(let $ of this.listeners.values())for(let J of $){if(J.sessionId&&J.sessionId!==f.sessionId)continue;try{J.listener(f)}catch(W){F3(`listener threw while publishing ${f.event}`,W)}}}}import{timingSafeEqual as SO}from"node:crypto";import kO from"node:http";import IO from"node:net";import{URL as TB}from"node:url";import{WebSocketServer as mO}from"ws";import{HUB_COMMAND_SLOW_LOG_MS as bO,resolveHubCommandTimeoutMs as CO,safeJsonParse as EO}from"@cline/shared";function UB(f){return{command:f.envelope.command,requestId:f.envelope.requestId,clientId:f.envelope.clientId,sessionId:f.envelope.sessionId}}function GB(f,$,J){return{version:f.envelope.version,requestId:f.envelope.requestId,ok:!1,error:{code:$,message:J}}}class O4{transport;constructor(f){this.transport=f}attach(f){let $=new Map,J=new Set,W=!1,H=(X)=>{try{f.send(JSON.stringify(X))}catch(A){console.error(`[hub] failed to send websocket frame: ${A instanceof Error?A.stack||A.message:String(A)}`)}},Q=(X)=>{H({kind:"event",envelope:X})},Z=async(X)=>{try{let A=JSON.parse(X.data);switch(A.kind){case"command":{let P=performance.now(),B=!1,Y=UB(A);g("info","command.start",Y);let V=setTimeout(()=>{if(B)return;g("warn","command.slow",{...Y,elapsedMs:Math.round(performance.now()-P)})},bO),R=this.transport.command(A.envelope);R.then((M)=>{if(!B)return;g(M.ok?"warn":"error","command.late_end",{...Y,elapsedMs:Math.round(performance.now()-P),ok:M.ok,errorCode:M.error?.code,errorMessage:M.error?.message})},(M)=>{if(!B)return;g("error","command.late_error",{...Y,elapsedMs:Math.round(performance.now()-P),error:M})});let U=!1,K,F,y=CO(A.envelope.command,A.envelope.timeoutMs);try{F=y===null?await R:await Promise.race([R,new Promise((M)=>{K=setTimeout(()=>{U=!0,M(GB(A,"hub_command_timeout",`Hub command ${A.envelope.command} did not complete within ${y}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${A.envelope.requestId}.`))},y)})])}catch(M){if(clearTimeout(V),K)clearTimeout(K);throw M}if(B=U,clearTimeout(V),K)clearTimeout(K);let D=Math.round(performance.now()-P);if(U)g("error","command.timeout",{...Y,durationMs:D,timeoutMs:y});else g(F.ok?"info":"warn","command.end",{...Y,durationMs:D,ok:F.ok,errorCode:F.error?.code,errorMessage:F.error?.message});if(A.envelope.command==="client.register"&&F.ok){let T=(A.envelope.payload??{}).clientId?.trim()||A.envelope.clientId?.trim();if(T)J.add(T)}else if(A.envelope.command==="client.unregister"&&F.ok){let M=A.envelope.clientId?.trim();if(M)J.delete(M)}H({kind:"reply",envelope:F});break}case"stream.subscribe":{let P=`${A.clientId}:${A.sessionId??"*"}`;if($.has(P))break;let B=await this.transport.subscribe(A.clientId,Q,{sessionId:A.sessionId});$.set(P,B);break}case"stream.unsubscribe":{let P=`${A.clientId}:${A.sessionId??"*"}`;$.get(P)?.(),$.delete(P);break}case"reply":case"event":break}}catch(A){let P=typeof X.data==="string"?EO(X.data):void 0;if(!P||P.kind!=="command"){g("error","rejected malformed websocket frame",{error:A});return}g("error","command.error",{...UB(P),error:A}),H({kind:"reply",envelope:GB(P,"command_failed",A instanceof Error?A.message:"Unknown hub error")})}},j=()=>{if(W)return;W=!0;for(let X of $.values())X();$.clear();for(let X of J)this.transport.command({version:"v1",command:"client.unregister",clientId:X});J.clear(),f.removeEventListener("message",Z),f.removeEventListener("close",j)};return f.addEventListener("message",Z),f.addEventListener("close",j),j}}class z4{transport;constructor(f){this.transport=f}command(f){return this.transport.handleCommand(f)}subscribe(f,$,J){return this.transport.subscribe(f,$,J)}}function xO(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();return String(f)}function gO(f){return{send($){f.send($)},addEventListener($,J){if($==="message"){f.on("message",(W)=>{J({data:xO(W)})});return}f.on("close",J)},removeEventListener(){}}}function vO(f){try{f.write(`HTTP/1.1 400 Bad Request\r
709
709
  Connection: close\r
710
710
  Content-Length: 0\r
711
711
  \r
712
- `),f.end()}catch{f.destroy()}}function eL(f){try{f.write(`HTTP/1.1 401 Unauthorized\r
712
+ `),f.end()}catch{f.destroy()}}function uO(f){try{f.write(`HTTP/1.1 401 Unauthorized\r
713
713
  Connection: close\r
714
714
  Content-Length: 0\r
715
715
  \r
716
- `),f.end()}catch{f.destroy()}}function $Y(f,$){if(!f||!$)return!1;let J=Buffer.from(f,"utf8"),H=Buffer.from($,"utf8");return J.length===H.length&&pL(J,H)}function JY(f,$){let J=f&&typeof f==="object"&&"code"in f&&typeof f.code==="string"?f.code:void 0,H=f instanceof Error?f.message:typeof f==="string"?f:"Unknown startup error",W=`Failed to start hub server on ${$.host}:${$.port}${$.pathname}: ${H}`,Q=Error(J?`${W} (${J})`:W);if(J)f.code=J,Q.code=J;if(f instanceof Error&&f.stack)Q.stack=`${Q.name}: ${Q.message}
717
- Caused by: ${f.stack}`;return Q}async function fz(f){return await new Promise(($,J)=>{let H=nL.createServer();H.once("error",J),H.listen(0,f,()=>{let W=H.address();if(!W||typeof W==="string"){H.close(()=>J(Error("Failed to resolve free port")));return}let Q=W.port;H.close((Z)=>{if(Z){J(Z);return}$(Q)})})})}function $z(f){return f instanceof Error&&"code"in f&&f.code==="EADDRINUSE"}var P3=new Map,HY="cline-hub-auth.",Jz=30000;function WY(f){return Array.isArray(f)?f.join(","):f??""}function Hz(f){let $=WY(f).trim();return/^Bearer\s+(.+)$/i.exec($)?.[1]?.trim()||null}function Wz(f){for(let $ of WY(f).split(",")){let J=$.trim();if(J.startsWith(HY))return J.slice(HY.length).trim()||null}return null}async function M4(f){let $=f.owner??y0(),J=f.host??"127.0.0.1",H=f.pathname??"/hub",W=f.port??V1(),Q=W===0?await fz(J):W,Z=Q,j=cf(J,Q,H),P=S0(),X=e4(),V=new B2(f);await V.start();let Y=new T4(new D4(V)),B=new Set,A=new Date().toISOString(),R={protocolVersion:"v1",buildId:P,pid:process.pid,startedAt:A},U=new Set,y,F,K=async()=>{if(F)return F;return F=(async()=>{if(y)clearInterval(y),y=void 0;for(let h of U)h.terminate?.();U.clear();for(let h of B)h();if(B.clear(),await new Promise((h,z)=>{T.close((u)=>{if(u){z(u);return}h()})}),await new Promise((h,z)=>{M.close((u)=>{if(u){z(u);return}h()})}),await V.stop(),(await Qf($.discoveryPath))?.url===j)await zf($.discoveryPath)})(),F},M=iL.createServer((G,h)=>{if((G.url??"/")==="/health"){let u=JSON.stringify({hubId:V.getHubId(),...R,authToken:"",host:J,port:Z,url:j,updatedAt:new Date().toISOString()});h.statusCode=200,h.setHeader("content-type","application/json"),h.end(u);return}if((G.url??"/")==="/version"){h.statusCode=200,h.setHeader("content-type","application/json"),h.end(JSON.stringify(R));return}if(new fY(G.url??"/",`http://${J}:${Z}`).pathname==="/shutdown"&&G.method==="POST"){if(!$Y(Hz(G.headers.authorization),X)){h.statusCode=401,h.end("Unauthorized");return}h.statusCode=202,h.setHeader("content-type","application/json"),h.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{K()});return}h.statusCode=404,h.end("Not found")}),T=new aL({noServer:!0});y=setInterval(()=>{for(let G of U){if(G.isAlive===!1){try{G.terminate?.()}catch{}U.delete(G);continue}G.isAlive=!1;try{G.ping?.()}catch{try{G.terminate?.()}catch{}U.delete(G)}}},Jz),M.on("upgrade",(G,h,z)=>{if(new fY(G.url??"/",`http://${J}:${Z}`).pathname!==H){h.destroy();return}if(!$Y(Wz(G.headers["sec-websocket-protocol"]),X)){eL(h);return}try{T.handleUpgrade(G,h,z,(gf)=>{let a=gf;a.isAlive=!0,a.on("pong",()=>{a.isAlive=!0}),U.add(a);let c=Y.attach(sL(gf));B.add(c),gf.once("close",()=>{U.delete(a),c(),B.delete(c)})})}catch{oL(h)}});try{await new Promise((G,h)=>{M.once("error",(z)=>{h(JY(z,{host:J,port:Q,pathname:H}))}),M.listen(Q,J,()=>{let z=M.address();if(!z||typeof z==="string"){h(JY(Error("Failed to resolve hub port"),{host:J,port:Q,pathname:H}));return}Z=z.port,j=cf(J,Z,H),G()})})}catch(G){if(y)clearInterval(y),y=void 0;throw await V.stop().catch(()=>{return}),G}return await f6($.discoveryPath,{hubId:V.getHubId(),protocolVersion:"v1",buildId:P,authToken:X,host:J,port:Z,url:j,pid:process.pid,startedAt:A,updatedAt:A}),{host:J,port:Z,url:j,authToken:X,close:K}}async function oJ(f){let $=f.owner??y0(),J=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),H=f.host??"127.0.0.1",W=f.port??V1(),Q=f.pathname??"/hub",Z=cf(H,W,Q),j=$.discoveryPath,P=(V)=>{if(!J)k0(V.url,V.authToken);return V},X=P3.get(j);if(X){let V=await X;if(V.url===Z)return P({server:V,url:V.url,authToken:V.authToken,action:"reuse"})}return await $6($.discoveryPath,async()=>{let V=await Qf($.discoveryPath);if(V?.url&&(V.url===Z||f.allowPortFallback===!0)){let R=await Pf(V.url);if(R?.url&&await sf(R.url,{authToken:V.authToken}))return P({url:R.url,authToken:V.authToken,action:"reuse"})}if((await Pf(Z))?.url||V?.url)await zf($.discoveryPath);let A=async(R)=>{let U=M4({...R,owner:$});P3.set(j,U);try{let y=await U;return P({server:y,url:y.url,authToken:y.authToken,action:"started"})}catch(y){throw P3.delete(j),y}};try{return await A(f)}catch(R){if(!f.allowPortFallback||!$z(R))throw R;return await A({...f,port:0})}})}async function QV(f){let $=tf({host:f.host,port:f.port,pathname:f.pathname});return await M4({...f,...$,owner:Xf()})}async function ZV(f){let $=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=tf({host:f.host,port:f.port,pathname:f.pathname});return await oJ({...f,...J,allowPortFallback:f.allowPortFallback??!$,owner:Xf()})}export{f6 as writeHubDiscovery,$6 as withHubStartupLock,sf as verifyHubConnection,h4 as truncateNotificationBody,LH as toHubHealthUrl,mH as stopLocalHubServerGracefully,M4 as startHubWebSocketServer,QV as startHubServer,Y1 as spawnDetachedHubServer,K7 as sendHubCommand,W6 as restartLocalHubIfIdleAfterStartupTimeout,Q7 as resolveWorkspaceHubOwnerContext,Xf as resolveSharedHubOwnerContext,IH as resolveHubUrl,y0 as resolveHubOwnerContext,tf as resolveHubEndpointOptions,S0 as resolveHubBuildId,V1 as resolveDefaultHubPort,bH as resolveDefaultHubPathname,qH as resolveDefaultHubHost,x2 as resolveCompatibleLocalHubUrl,$7 as resolveClineDir,S2 as resolveClineDataDir,I2 as requestHubShutdown,k0 as rememberRecoverableLocalHubUrl,Qf as readHubDiscovery,Pf as probeHubServer,y7 as probeHubConnection,J6 as prewarmDetachedHubServer,m0 as normalizeHubWebSocketUrl,SH as isHubReconnectableTransportError,H6 as isHubCommandTimeoutError,H7 as isDiscoveryFilePresent,oJ as ensureHubWebSocketServer,ZV as ensureHubServer,j7 as ensureDetachedHubServer,K$ as ensureCompatibleLocalHubUrl,WV as createLocalHubScheduleRuntimeHandlers,J7 as createInMemoryHubOwnerContext,cf as createHubServerUrl,e4 as createHubAuthToken,y$ as createConfiguredTelemetryService,X1 as createConfiguredTelemetryHandle,Q6 as connectToHub,zf as clearHubDiscovery,df as NodeHubClient,D4 as NativeHubTransportAdapter,gH as HubUIClient,Rf as HubTransportError,xH as HubSessionClient,B2 as HubServerTransport,Q1 as HubScheduleService,$1 as HubScheduleCommandService,B1 as HubCommandError,OH as DEFAULT_HUB_PORT,NH as DEFAULT_HUB_PATHNAME,zH as DEFAULT_HUB_HOST,T4 as BrowserWebSocketHubAdapter};
716
+ `),f.end()}catch{f.destroy()}}function DB(f,$){if(!f||!$)return!1;let J=Buffer.from(f,"utf8"),W=Buffer.from($,"utf8");return J.length===W.length&&SO(J,W)}function _B(f,$){let J=f&&typeof f==="object"&&"code"in f&&typeof f.code==="string"?f.code:void 0,W=f instanceof Error?f.message:typeof f==="string"?f:"Unknown startup error",H=`Failed to start hub server on ${$.host}:${$.port}${$.pathname}: ${W}`,Q=Error(J?`${H} (${J})`:H);if(J)f.code=J,Q.code=J;if(f instanceof Error&&f.stack)Q.stack=`${Q.name}: ${Q.message}
717
+ Caused by: ${f.stack}`;return Q}async function cO(f){return await new Promise(($,J)=>{let W=IO.createServer();W.once("error",J),W.listen(0,f,()=>{let H=W.address();if(!H||typeof H==="string"){W.close(()=>J(Error("Failed to resolve free port")));return}let Q=H.port;W.close((Z)=>{if(Z){J(Z);return}$(Q)})})})}function dO(f){return f instanceof Error&&"code"in f&&f.code==="EADDRINUSE"}var T3=new Map,MB="cline-hub-auth.",rO=30000;function LB(f){return Array.isArray(f)?f.join(","):f??""}function lO(f){let $=LB(f).trim();return/^Bearer\s+(.+)$/i.exec($)?.[1]?.trim()||null}function pO(f){for(let $ of LB(f).split(",")){let J=$.trim();if(J.startsWith(MB))return J.slice(MB.length).trim()||null}return null}async function N4(f){let $=f.owner??D0(),J=f.host??"127.0.0.1",W=f.pathname??"/hub",H=f.port??Y1(),Q=H===0?await cO(J):H,Z=Q,j=lf(J,Q,W),X=v0(),A=Q6(),P=new F2(f);await P.start();let B=new O4(new z4(P)),Y=new Set,V=new Date().toISOString(),R={protocolVersion:"v1",buildId:X,pid:process.pid,startedAt:V},U=new Set,K,F,y=async()=>{if(F)return F;return F=(async()=>{if(K)clearInterval(K),K=void 0;for(let _ of U)_.terminate?.();U.clear();for(let _ of Y)_();if(Y.clear(),await new Promise((_,L)=>{M.close((q)=>{if(q){L(q);return}_()})}),await new Promise((_,L)=>{D.close((q)=>{if(q){L(q);return}_()})}),await P.stop(),(await Af($.discoveryPath))?.url===j)await bf($.discoveryPath)})(),F},D=kO.createServer((T,_)=>{if((T.url??"/")==="/health"){let q=JSON.stringify({hubId:P.getHubId(),...R,authToken:"",host:J,port:Z,url:j,updatedAt:new Date().toISOString()});_.statusCode=200,_.setHeader("content-type","application/json"),_.end(q);return}if((T.url??"/")==="/version"){_.statusCode=200,_.setHeader("content-type","application/json"),_.end(JSON.stringify(R));return}if(new TB(T.url??"/",`http://${J}:${Z}`).pathname==="/shutdown"&&T.method==="POST"){if(!DB(lO(T.headers.authorization),A)){_.statusCode=401,_.end("Unauthorized");return}_.statusCode=202,_.setHeader("content-type","application/json"),_.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{y()});return}_.statusCode=404,_.end("Not found")}),M=new mO({noServer:!0});K=setInterval(()=>{for(let T of U){if(T.isAlive===!1){try{T.terminate?.()}catch{}U.delete(T);continue}T.isAlive=!1;try{T.ping?.()}catch{try{T.terminate?.()}catch{}U.delete(T)}}},rO),D.on("upgrade",(T,_,L)=>{if(new TB(T.url??"/",`http://${J}:${Z}`).pathname!==W){_.destroy();return}if(!DB(pO(T.headers["sec-websocket-protocol"]),A)){uO(_);return}try{M.handleUpgrade(T,_,L,(Wf)=>{let Hf=Wf;Hf.isAlive=!0,Hf.on("pong",()=>{Hf.isAlive=!0}),U.add(Hf);let o=B.attach(gO(Wf));Y.add(o),Wf.once("close",()=>{U.delete(Hf),o(),Y.delete(o)})})}catch{vO(_)}});try{await new Promise((T,_)=>{D.once("error",(L)=>{_(_B(L,{host:J,port:Q,pathname:W}))}),D.listen(Q,J,()=>{let L=D.address();if(!L||typeof L==="string"){_(_B(Error("Failed to resolve hub port"),{host:J,port:Q,pathname:W}));return}Z=L.port,j=lf(J,Z,W),T()})})}catch(T){if(K)clearInterval(K),K=void 0;throw await P.stop().catch(()=>{return}),T}return await Z6($.discoveryPath,{hubId:P.getHubId(),protocolVersion:"v1",buildId:X,authToken:A,host:J,port:Z,url:j,pid:process.pid,startedAt:V,updatedAt:V}),{host:J,port:Z,url:j,authToken:A,close:y}}async function eJ(f){let $=f.owner??D0(),J=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=f.host??"127.0.0.1",H=f.port??Y1(),Q=f.pathname??"/hub",Z=lf(W,H,Q),j=$.discoveryPath,X=(P)=>{if(!J)u0(P.url,P.authToken);return P},A=T3.get(j);if(A){let P=await A;if(P.url===Z)return X({server:P,url:P.url,authToken:P.authToken,action:"reuse"})}return await j6($.discoveryPath,async()=>{let P=await Af($.discoveryPath);if(P?.url&&(P.url===Z||f.allowPortFallback===!0)){let R=await Vf(P.url);if(R?.url&&await ef(R.url,{authToken:P.authToken}))return X({url:R.url,authToken:P.authToken,action:"reuse"})}if((await Vf(Z))?.url||P?.url)await bf($.discoveryPath);let V=async(R)=>{let U=N4({...R,owner:$});T3.set(j,U);try{let K=await U;return X({server:K,url:K.url,authToken:K.authToken,action:"started"})}catch(K){throw T3.delete(j),K}};try{return await V(f)}catch(R){if(!f.allowPortFallback||!dO(R))throw R;return await V({...f,port:0})}})}async function OP(f){let $=of({host:f.host,port:f.port,pathname:f.pathname});return await N4({...f,...$,owner:Rf()})}async function zP(f){let $=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=of({host:f.host,port:f.port,pathname:f.pathname});return await eJ({...f,...J,allowPortFallback:f.allowPortFallback??!$,owner:Rf()})}export{Z6 as writeHubDiscovery,j6 as withHubStartupLock,ef as verifyHubConnection,h4 as truncateNotificationBody,O5 as toHubHealthUrl,x5 as stopLocalHubServerGracefully,N4 as startHubWebSocketServer,OP as startHubServer,V1 as spawnDetachedHubServerWithRetry,C5 as spawnDetachedHubServer,qQ as sendHubCommand,P6 as restartLocalHubIfIdleAfterStartupTimeout,yQ as resolveWorkspaceHubOwnerContext,Rf as resolveSharedHubOwnerContext,g5 as resolveHubUrl,D0 as resolveHubOwnerContext,of as resolveHubEndpointOptions,v0 as resolveHubBuildId,Y1 as resolveDefaultHubPort,b5 as resolveDefaultHubPathname,w5 as resolveDefaultHubHost,v2 as resolveCompatibleLocalHubUrl,VQ as resolveClineDir,I2 as resolveClineDataDir,g2 as requestHubShutdown,u0 as rememberRecoverableLocalHubUrl,Af as readHubDiscovery,Vf as probeHubServer,NQ as probeHubConnection,X6 as prewarmDetachedHubServer,c0 as normalizeHubWebSocketUrl,I5 as isHubReconnectableTransportError,A6 as isHubCommandTimeoutError,FQ as isDiscoveryFilePresent,eJ as ensureHubWebSocketServer,zP as ensureHubServer,GQ as ensureDetachedHubServer,T$ as ensureCompatibleLocalHubUrl,hP as createLocalHubScheduleRuntimeHandlers,RQ as createInMemoryHubOwnerContext,lf as createHubServerUrl,Q6 as createHubAuthToken,T0 as createConfiguredTelemetryService,B1 as createConfiguredTelemetryHandle,B6 as connectToHub,bf as clearHubDiscovery,pf as NodeHubClient,z4 as NativeHubTransportAdapter,u5 as HubUIClient,Df as HubTransportError,v5 as HubSessionClient,F2 as HubServerTransport,j1 as HubScheduleService,W1 as HubScheduleCommandService,R1 as HubCommandError,N5 as DEFAULT_HUB_PORT,q5 as DEFAULT_HUB_PATHNAME,z5 as DEFAULT_HUB_HOST,O4 as BrowserWebSocketHubAdapter};