@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/README.md +1 -1
- package/dist/ClineCore.d.ts +4 -3
- package/dist/auth/cline.d.ts +1 -1
- package/dist/extensions/plugin-sandbox-bootstrap.js +1 -1
- package/dist/extensions/tools/team/spawn-agent-tool.d.ts +1 -0
- package/dist/hub/daemon/entry.js +145 -145
- package/dist/hub/daemon/index.d.ts +1 -0
- package/dist/hub/index.js +162 -162
- package/dist/hub/runtime-host/hub-runtime-host.d.ts +2 -2
- package/dist/hub/server/hub-session-records.d.ts +2 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.js +162 -162
- package/dist/remote-config/integration.d.ts +17 -0
- package/dist/runtime/host/local/agent-event-bridge.d.ts +1 -0
- package/dist/runtime/host/local-runtime-host.d.ts +6 -2
- package/dist/runtime/host/runtime-host.d.ts +5 -1
- package/dist/services/agent-events.d.ts +1 -0
- package/dist/services/llms/provider-settings.d.ts +15 -15
- package/dist/services/usage.d.ts +1 -0
- package/dist/session/models/session-manifest.d.ts +2 -2
- package/dist/session/session-snapshot.d.ts +2 -0
- package/dist/types/chat-schema.d.ts +12 -12
- package/dist/types/session.d.ts +3 -0
- package/dist/types/sessions.d.ts +10 -0
- package/dist/types.d.ts +1 -1
- package/package.json +4 -8
package/dist/hub/daemon/entry.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`)}function
|
|
3
|
-
`,"utf8")}function Z6(){return of().telemetryOptOut}function YQ(f,$={}){L$({...of(),telemetryOptOut:f},$)}function rf(f){return new Set(f??of().disabledTools??[])}function o2(f){return new Set(f??of().disabledPlugins??[])}function BQ(f){return rf().has(f)}function j6(f){let $=rf(),J=of();if($.has(f))return $.delete(f),L$({...J,disabledTools:[...$]}),!1;return $.add(f),L$({...J,disabledTools:[...$]}),!0}function tW(f,$){let J=[...new Set(f.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let W=of(),H=rf(W.disabledTools);for(let Q of J)if($)H.add(Q);else H.delete(Q);L$({...W,disabledTools:[...H]})}function AQ(f,$){return tW([f],$),$}function RQ(f){return o2().has(f)}function FQ(f,$){let J=f.trim();if(!J)return;let W=of(),H=o2(W.disabledPlugins);if($)H.add(J);else H.delete(J);L$({...W,disabledPlugins:[...H]})}function P6(f,$){let J=o2($);if(J.size===0)return[...f];return f.filter((W)=>!J.has(W))}function z$(f,$){let J=rf($);if(J.size===0)return[...f];return f.filter((W)=>!J.has(W.name))}function X6(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 PQ,s2;var G0=$1(()=>{Gf();PQ=t2.preprocess((f)=>Array.isArray(f)?f.filter(($)=>typeof $==="string").map(($)=>$.trim()).filter(Boolean):void 0,t2.array(t2.string()).optional()).transform((f)=>{if(!f)return;let $=[...new Set(f)].sort((J,W)=>J.localeCompare(W));return $.length>0?$:void 0}),s2=t2.object({telemetryOptOut:t2.boolean().default(!1).catch(!1),disabledTools:PQ.optional(),disabledPlugins:PQ.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 GT,mkdirSync as TT,readFileSync as hT,writeFileSync as DT}from"node:fs";import{resolve as MT}from"node:path";import{resolveSessionDataDir as _T}from"@cline/shared/storage";import{nanoid as LT}from"nanoid";import*as zT from"node-machine-id";function c$(f){let $=f?.trim();if($)return $;let J=qT();if(J)return J;return bT()}function NT(){let f=zT;return f.machineIdSync??f.default?.machineIdSync}function qT(){try{let f=NT();if(!f)return;return f().trim()||void 0}catch{return}}function bT(){let f=_T(),$=MT(f,OT);try{if(GT($)){let W=hT($,"utf8").trim();if(W.length>0)return W}}catch{}let J=`cl-${LT()}`;try{TT(f,{recursive:!0}),DT($,J,"utf8")}catch{}return J}var OT="machine-id";var _J=()=>{};class A4{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 P=j;if(!P)P=new Map,this.gaugeValues.set(f,P);if(!this.gauges.has(f)){let X=this.meter.createObservableGauge(f,W?{description:W}: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 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,P]of Object.entries(f)){if(j==="__proto__"||j==="constructor"||j==="prototype")continue;let X=$?`${$}.${j}`:j;if(P===null||P===void 0){H[X]=String(P);continue}if(Array.isArray(P)){let V=P.length>Q?P.slice(0,Q):P;try{H[X]=JSON.stringify(V)}catch{H[X]="[UnserializableArray]"}if(P.length>Q)H[`${X}_truncated`]=!0,H[`${X}_original_length`]=P.length;continue}if(typeof P==="object"){if(P instanceof Date){H[X]=P.toISOString();continue}if(P instanceof Error){H[X]=P.message;continue}if(J.has(P)){H[X]="[Circular]";continue}if(W>=Z){H[X]="[MaxDepthExceeded]";continue}J.add(P),Object.assign(H,this.flattenProperties(P,X,J,W+1));continue}if(th(P)){H[X]=P;continue}try{H[X]=JSON.stringify(P)}catch{H[X]=String(P)}}return H}}function th(f){return typeof f==="string"||typeof f==="number"||typeof f==="boolean"}class R4{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 Q2{adapters;metadata;distinctId;commonProperties;constructor(f={}){if(this.adapters=[...f.adapters??[]],f.logger)this.adapters.push(new R4({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 $9=()=>{};import{metrics as sh,trace as oh}from"@opentelemetry/api";import{logs as eh}from"@opentelemetry/api-logs";import{OTLPLogExporter as fD}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as $D}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as JD}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as WD}from"@opentelemetry/resources";import{BatchLogRecordProcessor as HD,ConsoleLogRecordExporter as QD,LoggerProvider as ZD}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as jD,MeterProvider as PD,PeriodicExportingMetricReader as $X}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as XD,ConsoleSpanExporter as VD,SimpleSpanProcessor as YD}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as BD}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as AD,ATTR_SERVICE_VERSION as RD}from"@opentelemetry/semantic-conventions";class JX{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 Z2{meterProvider;loggerProvider;tracerProvider;options;constructor(f={}){this.options=f;let $=WD({[AD]:f.serviceName??"cline",...f.serviceVersion?{[RD]:f.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)sh.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)eh.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(f="cline",$){return oh.getTracer(f,$??this.options.serviceVersion)}createAdapter(f){return new A4({...f,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(f){let $=this.createAdapter({name:f.name,enabled:this.options.enabled,metadata:f.metadata});return new Q2({...f,adapters:[$],distinctId:c$(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 $=J9(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)=>KD(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 PD({resource:f,readers:H})}createTracerProvider(f){let $=J9(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=yD(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 BD({resource:f,spanProcessors:H})}createLoggerProvider(f){let $=J9(this.options.logsExporter);if($.length===0)return null;let J=$.map((W)=>{let H=FD(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!H)return null;return new HD(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 ZD({resource:f,processors:J})}}function F4(f){let $=new Z2(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 i$(f){if(Z6())return{telemetry:new JX(f)};if(f.enabled!==!0)return{telemetry:new Q2({...f,distinctId:c$(f.distinctId)})};return F4(f)}function j2(f){let{telemetry:$,provider:J}=i$(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 J9(f){if(!f)return[];return(Array.isArray(f)?f:f.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function FD(f,$){if(f==="console")return new QD;if(!$.endpoint)return null;let J=W9($.endpoint,"/v1/logs");return new fD({url:J,headers:$.headers})}function yD(f,$){if(f==="console")return new YD(new VD);if(!$.endpoint)return null;let J=W9($.endpoint,"/v1/traces");return new XD(new JD({url:J,headers:$.headers}))}function KD(f,$){if(f==="console")return new $X({exporter:new jD,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let J=W9($.endpoint,"/v1/metrics");return new $X({exporter:new $D({url:J,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function W9(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 SJ=$1(()=>{G0();_J();$9()});var pV={};N(pV,{createOpenTelemetryTelemetryService:()=>F4,createConfiguredTelemetryService:()=>i$,createConfiguredTelemetryHandle:()=>j2,OpenTelemetryProvider:()=>Z2,OpenTelemetryAdapter:()=>A4});var iV=$1(()=>{SJ()});import{initVcr as Qz}from"@cline/shared";import{normalizeProviderId as Jz}from"@cline/llms";var aV={};N(aV,{LocalRuntimeHost:()=>Z0});import{homedir as aL}from"node:os";import{isAbsolute as tL,join as X3,resolve as sL}from"node:path";import{createSessionId as oL,isLikelyAuthError as eL,normalizeUserInput as fz}from"@cline/shared";import{setHomeDirIfUnset as $z}from"@cline/shared/storage";var m3={};N(m3,{createContextCompactionPrepareTurn:()=>h2});import{createHandler as FY}from"@cline/llms";var F3=200000,y3=0.95;var PW=20000;var K3=8;function VY(f){return Math.max(1,Math.ceil(f.length/4))}function V$(f,$){if(f.length<=$)return f;return`${f.slice(0,$)}
|
|
4
|
-
...[truncated ${f.length-$} chars]`}function
|
|
5
|
-
${
|
|
1
|
+
import{createRequire as qB}from"node:module";var{defineProperty:X5,getOwnPropertyNames:OB}=Object;var L3=Object.prototype.hasOwnProperty;function h3(f){return this[f]}var z=(f,$,J)=>{var W=OB($);for(let H of W)if(!L3.call(f,H)&&H!=="default")X5(f,H,{get:h3.bind($,H),enumerable:!0});if(J){for(let H of W)if(!L3.call(J,H)&&H!=="default")X5(J,H,{get:h3.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 $)X5(f,J,{get:$[J],enumerable:!0,configurable:!0,set:NB.bind($,J)})};var W1=(f,$)=>()=>(f&&($=f(f=0)),$);var O3=qB(import.meta.url);var bQ={};N(bQ,{normalizeUserMessage:()=>UV,buildInitialUserContent:()=>yV});async function yV(f,$,J,W){let H=GV($),Q=await DV(J,W);if(H.length===0&&!Q)return f;let Z=[{type:"text",text:f},...H];if(Q)Z.push(...Q);return Z}function UV(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(`
|
|
2
|
+
`)}function GV(f){if(!f||f.length===0)return[];let $=[];for(let J of f){let W=TV(J);if(W)$.push(W)}return $}function TV(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 DV(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}function l(f,$,J){f?.capture({event:$,properties:J})}function n4(f){if(!f)return;return f.substring(0,500)}function BR(f){if(typeof f==="string")return"Error";return f.name?.trim()||f.constructor?.name||"Error"}function YR(f){return typeof f==="string"?f:f.message}function F7(f,$){return f.some((J)=>$.has(J.trim().toLowerCase()))}function K7(f){l(f,v.CLIENT.EXTENSION_ACTIVATED)}function a4(f,$){let J=[...$.vcs_types],W={root_count:$.root_count,vcs_types:J,is_multi_root:$.root_count>1,has_git:F7(J,new Set(["git"])),has_mercurial:F7(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 t4(f,$,J){l(f,v.WORKSPACE.INIT_ERROR,{error_type:BR($),error_message:n4(YR($)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function y7(f,$){l(f,v.WORKSPACE.PATH_RESOLVED,{...$})}function U0(f,$){l(f,v.USER.AUTH_STARTED,{provider:$})}function G0(f,$){l(f,v.USER.AUTH_SUCCEEDED,{provider:$})}function T0(f,$,J){l(f,v.USER.AUTH_FAILED,{provider:$,errorMessage:n4(J)})}function l0(f,$,J){l(f,v.USER.AUTH_LOGGED_OUT,{provider:$,reason:J})}function U7(f,$){f?.captureRequired(v.USER.TELEMETRY_OPT_OUT,$)}function D0(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 s4(f,$){l(f,v.TASK.CREATED,$)}function o4(f,$){l(f,v.TASK.RESTARTED,$)}function n2(f,$){l(f,v.TASK.COMPLETED,$)}function y1(f,$){l(f,v.TASK.CONVERSATION_TURN,{...$,timestamp:new Date().toISOString()})}function e4(f,$){l(f,v.TASK.TOKEN_USAGE,$)}function f6(f,$,J){l(f,v.TASK.MODE_SWITCH,{ulid:$,mode:J})}function $6(f,$){l(f,v.TASK.TOOL_USED,$)}function J6(f,$){l(f,v.TASK.SKILL_USED,$)}function W6(f,$){l(f,v.TASK.DIFF_EDIT_FAILED,$)}function a2(f,$){l(f,v.TASK.PROVIDER_API_ERROR,{...$,errorMessage:n4($.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function H6(f,$,J){l(f,v.TASK.MENTION_USED,{mentionType:$,contentLength:J,timestamp:new Date().toISOString()})}function Q6(f,$,J,W){l(f,v.TASK.MENTION_FAILED,{mentionType:$,errorType:J,errorMessage:n4(W),timestamp:new Date().toISOString()})}function Z6(f,$,J,W,H){l(f,v.TASK.MENTION_SEARCH_RESULTS,{queryLength:$.length,resultCount:J,searchType:W,isEmpty:H,timestamp:new Date().toISOString()})}function p0(f,$){l(f,v.TASK.AGENT_CREATED,{...$,timestamp:new Date().toISOString()})}function j6(f,$){l(f,v.TASK.AGENT_TEAM_CREATED,{...$,timestamp:new Date().toISOString()})}function t2(f,$){l(f,$.event==="ended"?v.TASK.SUBAGENT_COMPLETED:v.TASK.SUBAGENT_STARTED,{...$,timestamp:new Date().toISOString()})}function X6(f,$,J,W){l(f,v.HOOKS.DISCOVERY_COMPLETED,{hookName:$,globalCount:J,workspaceCount:W,totalCount:J+W,timestamp:new Date().toISOString()})}var v;var Lf=W1(()=>{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 GR,readFileSync as TR,writeFileSync as DR}from"node:fs";import{dirname as _R}from"node:path";import{resolveGlobalSettingsPath as M7}from"@cline/shared/storage";import{z as o2}from"zod";function _7(){return e2.parse({})}function f0(){let f=M7(),$;try{$=JSON.parse(TR(f,"utf8"))}catch{return _7()}let J=e2.safeParse($);return J.success?J.data:_7()}function q$(f,$={}){let J=M7(),W=f0();GR(_R(J),{recursive:!0});let H=e2.parse(f);if(!W.telemetryOptOut&&H.telemetryOptOut)U7($.telemetry);DR(J,`${JSON.stringify(H,null,2)}
|
|
3
|
+
`,"utf8")}function B6(){return f0().telemetryOptOut}function L7(f,$={}){q$({...f0(),telemetryOptOut:f},$)}function nf(f){return new Set(f??f0().disabledTools??[])}function f8(f){return new Set(f??f0().disabledPlugins??[])}function h7(f){return nf().has(f)}function Y6(f){let $=nf(),J=f0();if($.has(f))return $.delete(f),q$({...J,disabledTools:[...$]}),!1;return $.add(f),q$({...J,disabledTools:[...$]}),!0}function s5(f,$){let J=[...new Set(f.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let W=f0(),H=nf(W.disabledTools);for(let Q of J)if($)H.add(Q);else H.delete(Q);q$({...W,disabledTools:[...H]})}function O7(f,$){return s5([f],$),$}function z7(f){return f8().has(f)}function N7(f,$){let J=f.trim();if(!J)return;let W=f0(),H=f8(W.disabledPlugins);if($)H.add(J);else H.delete(J);q$({...W,disabledPlugins:[...H]})}function V6(f,$){let J=f8($);if(J.size===0)return[...f];return f.filter((W)=>!J.has(W))}function w$(f,$){let J=nf($);if(J.size===0)return[...f];return f.filter((W)=>!J.has(W.name))}function R6(f,$){if(!f||f.length===0)return f;let J=nf($);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 D7,e2;var M0=W1(()=>{Lf();D7=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,W)=>J.localeCompare(W));return $.length>0?$:void 0}),e2=o2.object({telemetryOptOut:o2.boolean().default(!1).catch(!1),disabledTools:D7.optional(),disabledPlugins:D7.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 sT,mkdirSync as oT,readFileSync as eT,writeFileSync as fD}from"node:fs";import{resolve as $D}from"node:path";import{resolveSessionDataDir as JD}from"@cline/shared/storage";import{nanoid as WD}from"nanoid";import*as HD from"node-machine-id";function l$(f){let $=f?.trim();if($)return $;let J=jD();if(J)return J;return XD()}function ZD(){let f=HD;return f.machineIdSync??f.default?.machineIdSync}function jD(){try{let f=ZD();if(!f)return;return f().trim()||void 0}catch{return}}function XD(){let f=JD(),$=$D(f,QD);try{if(sT($)){let W=eT($,"utf8").trim();if(W.length>0)return W}}catch{}let J=`cl-${WD()}`;try{oT(f,{recursive:!0}),fD($,J,"utf8")}catch{}return J}var QD="machine-id";var _J=()=>{};class U4{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(N_(X)){H[A]=X;continue}try{H[A]=JSON.stringify(X)}catch{H[A]=String(X)}}return H}}function N_(f){return typeof f==="string"||typeof f==="number"||typeof f==="boolean"}class G4{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 X2{adapters;metadata;distinctId;commonProperties;constructor(f={}){if(this.adapters=[...f.adapters??[]],f.logger)this.adapters.push(new G4({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 jH=()=>{};import{metrics as q_,trace as w_}from"@opentelemetry/api";import{logs as b_}from"@opentelemetry/api-logs";import{OTLPLogExporter as C_}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as E_}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as S_}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as k_}from"@opentelemetry/resources";import{BatchLogRecordProcessor as I_,ConsoleLogRecordExporter as m_,LoggerProvider as x_}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as g_,MeterProvider as v_,PeriodicExportingMetricReader as MA}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as u_,ConsoleSpanExporter as c_,SimpleSpanProcessor as d_}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as r_}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as l_,ATTR_SERVICE_VERSION as p_}from"@opentelemetry/semantic-conventions";class LA{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 A2{meterProvider;loggerProvider;tracerProvider;options;constructor(f={}){this.options=f;let $=k_({[l_]:f.serviceName??"cline",...f.serviceVersion?{[p_]:f.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)q_.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)b_.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(f="cline",$){return w_.getTracer(f,$??this.options.serviceVersion)}createAdapter(f){return new U4({...f,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(f){let $=this.createAdapter({name:f.name,enabled:this.options.enabled,metadata:f.metadata});return new X2({...f,adapters:[$],distinctId:l$(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 $=XH(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)=>a_(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 v_({resource:f,readers:H})}createTracerProvider(f){let $=XH(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=n_(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 r_({resource:f,spanProcessors:H})}createLoggerProvider(f){let $=XH(this.options.logsExporter);if($.length===0)return null;let J=$.map((W)=>{let H=i_(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!H)return null;return new I_(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 x_({resource:f,processors:J})}}function T4(f){let $=new A2(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 C0(f){if(B6())return{telemetry:new LA(f)};if(f.enabled!==!0)return{telemetry:new X2({...f,distinctId:l$(f.distinctId)})};return T4(f)}function P2(f){let{telemetry:$,provider:J}=C0(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 XH(f){if(!f)return[];return(Array.isArray(f)?f:f.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function i_(f,$){if(f==="console")return new m_;if(!$.endpoint)return null;let J=AH($.endpoint,"/v1/logs");return new C_({url:J,headers:$.headers})}function n_(f,$){if(f==="console")return new d_(new c_);if(!$.endpoint)return null;let J=AH($.endpoint,"/v1/traces");return new u_(new S_({url:J,headers:$.headers}))}function a_(f,$){if(f==="console")return new MA({exporter:new g_,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let J=AH($.endpoint,"/v1/metrics");return new MA({exporter:new E_({url:J,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function AH(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 CJ=W1(()=>{M0();_J();jH()});var MP={};N(MP,{createOpenTelemetryTelemetryService:()=>T4,createConfiguredTelemetryService:()=>C0,createConfiguredTelemetryHandle:()=>P2,OpenTelemetryProvider:()=>A2,OpenTelemetryAdapter:()=>U4});var zH=W1(()=>{CJ()});import{initVcr as iO}from"@cline/shared";import{normalizeProviderId as rO}from"@cline/llms";var KB={};N(KB,{LocalRuntimeHost:()=>X0});import{readdirSync as kO}from"node:fs";import{homedir as IO}from"node:os";import{isAbsolute as mO,join as T3,resolve as D3}from"node:path";import{createSessionId as xO,isLikelyAuthError as gO,normalizeUserInput as vO}from"@cline/shared";import{setHomeDirIfUnset as uO}from"@cline/shared/storage";var n3={};N(n3,{createContextCompactionPrepareTurn:()=>M2});import{createHandler as kB}from"@cline/llms";var z3=200000,N3=0.95;var A5=20000;var q3=8;function wB(f){return Math.max(1,Math.ceil(f.length/4))}function R$(f,$){if(f.length<=$)return f;return`${f.slice(0,$)}
|
|
4
|
+
...[truncated ${f.length-$} chars]`}function bB(f){if(typeof f==="string")return R$(f,2000);return f.map(($)=>{switch($.type){case"text":return $.text;case"file":return`<file path="${$.path}">
|
|
5
|
+
${R$($.content,2000)}
|
|
6
6
|
</file>`;case"image":return`[image:${$.mediaType}]`;default:return""}}).join(`
|
|
7
|
-
`)}function
|
|
8
|
-
`)}function
|
|
7
|
+
`)}function CB(f){return Object.entries(f).map(([$,J])=>`${$}=${JSON.stringify(J)}`).join(", ")}function w3(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]: ${R$(J.thinking,2000)}`);break;case"redacted_thinking":$.push("[Bot thinking]: [redacted]");break;case"tool_use":$.push(`[Bot tool calls]: ${J.name}(${CB(J.input)})`);break;case"tool_result":$.push(`[Tool result]: ${bB(J.content)}`);break;case"file":$.push(`[${f.role==="user"?"User":"Bot"} file ${J.path}]: ${R$(J.content,2000)}`);break;case"image":$.push(`[${f.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return $.join(`
|
|
8
|
+
`)}function b3(f){return f.map(w3).join(`
|
|
9
9
|
|
|
10
|
-
`).trim()}function
|
|
10
|
+
`).trim()}function C3(){let f=new WeakMap;return($)=>{let J=$,W=f.get(J);if(typeof W==="number")return W;let H=wB(w3($));return f.set(J,H),H}}function D2(f){return f.metadata?.kind==="compaction_summary"}function P5(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 EB(f){if(f.role!=="user"||!Array.isArray(f.content))return!1;return f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}function E3(f){return f.role==="user"&&!EB(f)&&!D2(f)}function S3(f){for(let $=0;$<f.length;$+=1)if(E3(f[$]))return $;return-1}function B5(f){for(let $=f.length-1;$>=0;$-=1)if(E3(f[$]))return $;return 0}function k3(f){for(let $=f.length-1;$>=0;$-=1)if(f[$].role==="assistant")return $;return-1}function I3(f){for(let $=f.length-1;$>=0;$-=1)if(D2(f[$]))return $;return-1}function m3(f,$,J){let W=B5(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 T2(f){if(typeof f==="string"&&f.trim().length>0)return[f];if(Array.isArray(f))return f.flatMap(($)=>T2($));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(...T2($[W]));if(Array.isArray($.files)){for(let W of $.files)if(W&&typeof W==="object")J.push(...T2(W.path))}if(Array.isArray($.file_paths))J.push(...T2($.file_paths));return J}return[]}function G2(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 x3(f){let $=[],J=[];for(let W of f){let H=P5(W);if(H){$=G2($,H.details.readFiles),J=G2(J,H.details.modifiedFiles);continue}if(!Array.isArray(W.content))continue;for(let Q of W.content){if(Q.type==="file"){$=G2($,[Q.path]);continue}if(Q.type!=="tool_use")continue;let Z=T2(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 SB(f){let $=f.readFiles.length>0?f.readFiles.map((W)=>`- ${W}`).join(`
|
|
11
11
|
`):"- none",J=f.modifiedFiles.length>0?f.modifiedFiles.map((W)=>`- ${W}`).join(`
|
|
12
12
|
`):"- none";return`## Files
|
|
13
13
|
Read:
|
|
14
14
|
${$}
|
|
15
15
|
Modified:
|
|
16
|
-
${J}`}function
|
|
16
|
+
${J}`}function g3(f,$){if(/^## Files$/im.test(f))return f.trim();return`${f.trim()}
|
|
17
17
|
|
|
18
|
-
${
|
|
18
|
+
${SB($)}`.trim()}function v3(f){let $=[`Summarize this session for continuation. Be concise and factual.
|
|
19
19
|
|
|
20
20
|
## Goal
|
|
21
21
|
One sentence: what is being built or fixed.
|
|
@@ -37,11 +37,11 @@ Edited: ${f.fileOps.modifiedFiles.join(", ")||"none"}`];if(f.previousSummary?.tr
|
|
|
37
37
|
${f.previousSummary.trim()}`);return $.push(`Conversation:
|
|
38
38
|
${f.conversationText||"(empty)"}`),$.join(`
|
|
39
39
|
|
|
40
|
-
`)}function
|
|
40
|
+
`)}function u3(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 c3(f){return{role:"user",content:`Context summary:
|
|
41
41
|
|
|
42
|
-
${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fileOps,tokensBefore:f.tokensBefore,generatedAt:Date.now()}}}async function yY(f){let $=FY(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 w3(f){let $=f.context.messages;if($.length<2)return;let J=L3($,f.preserveRecentTokens,f.estimateMessageTokens);if(J<=0||J>=$.length)return;let W=$.slice(0,J),H=_3(W),Q=H>=0?XW(W[H])?.summary:void 0,Z=H>=0?W.slice(H+1):W;if(Z.length===0)return;let j=z3(W),P=G3(Z),X=await yY({providerConfig:q3({activeProviderConfig:f.providerConfig,summarizer:f.summarizer}),request:N3({previousSummary:Q,conversationText:P,fileOps:j}),logger:f.logger});if(!X.trim())return;let V=O3(X,j),Y=$.reduce((R,U)=>R+f.estimateMessageTokens(U),0),B=[b3({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 S3(f){if(G2(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 T2(f,$){return f.reduce((J,W)=>J+$(W),0)}function C3(f,$){let J=Math.max(1,$),W=Math.max(16,J*4);if(typeof f.content==="string"){let Z=V$(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=V$(Z.text,H).trim();return H-=j.length,{...Z,text:j||"..."}});return{...f,content:Q}}function KY(f,$){let J=D3(f),W=VW(f),H=M3(f),Q=[];for(let Z=0;Z<f.length;Z+=1){let j=S3(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 E3(f,$,J,W){let H=f[$];H.message=J,H.estimatedTokens=W(J)}function O4(f,$,J,W){let H=T2(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 UY(f,$,J){let W=T2(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(K3,Z.estimatedTokens-(W-$));if(j>=Z.estimatedTokens)continue;E3(f,Q,C3(Z.message,j),J),W=T2(f.map((P)=>P.message),J)}if(W<=$)return;let H=f.findIndex((Q)=>Q.isFirstUser);if(H>=0){let Q=Math.max(1,f[H].estimatedTokens-(W-$));E3(f,H,C3(f[H].message,Q),J)}}function GY(f,$){return JSON.stringify(f)!==JSON.stringify($)}function k3(f){let $=Math.max(1,Math.min(f.context.triggerTokens,f.context.contextWindowTokens)),J=KY(f.context.messages,f.estimateMessageTokens);if(J.length===0)return;O4(J,(Z)=>Z.message.role==="assistant"&&!Z.isLastAssistant,$,f.estimateMessageTokens),O4(J,(Z)=>Z.message.role==="user"&&!Z.isFirstUser&&!Z.isLastUser,$,f.estimateMessageTokens),O4(J,(Z)=>Z.message.role==="assistant"&&Z.isLastAssistant,$,f.estimateMessageTokens),O4(J,(Z)=>Z.message.role==="user"&&Z.isLastUser&&!Z.isFirstUser,$,f.estimateMessageTokens),UY(J,$,f.estimateMessageTokens);let W=J.map((Z)=>Z.message);if(!GY(f.context.messages,W))return;let H=T2(f.context.messages.map((Z)=>S3(Z)??Z),f.estimateMessageTokens),Q=T2(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 TY={basic:({context:f,estimateMessageTokens:$,logger:J})=>k3({context:f,estimateMessageTokens:$,logger:J}),agentic:({context:f,providerConfig:$,compaction:J,mode:W,estimateMessageTokens:H,logger:Q})=>w3({context:f,providerConfig:$,summarizer:J?.summarizer,preserveRecentTokens:W==="manual"?Math.min(J?.preserveRecentTokens??PW,f.triggerTokens):J?.preserveRecentTokens??PW,estimateMessageTokens:H,logger:Q})};function hY(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??y3,J=f.contextWindowTokens*$;return{shouldCompact:f.inputTokens>J,triggerTokens:J,thresholdRatio:$}}function DY(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 h2(f,$={}){let J=f.compaction;if(J?.enabled!==!0)return;let W=f.providerConfig??{providerId:f.providerId,modelId:f.modelId},H=T3(),Q=J?.strategy??"basic",Z=TY[Q],j=$.mode??"auto";return async(P)=>{let X=P.apiMessages.reduce((F,K)=>F+H(K),0),V=J?.contextWindowTokens??P.model.info?.contextWindow??F3;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let Y=hY({inputTokens:X,contextWindowTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if(j==="auto"&&!Y.shouldCompact)return;let B=j==="manual"?DY({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:{...W,abortSignal:P.abortSignal},compaction:J,mode:j,estimateMessageTokens:H,logger:f.logger});if(y?.messages){let F=y.messages.reduce((K,M)=>K+H(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 n7={};N(n7,{zodToJsonSchema:()=>kA,validateWithZod:()=>SA,resolveToolRoutingConfig:()=>j1,resolveToolPresetName:()=>B0,resolveCoreSelectedToolIds:()=>g4,getCoreHeadlessToolNames:()=>g2,getCoreDefaultEnabledToolIds:()=>x4,getCoreBuiltinToolCatalog:()=>G$,getCoreAcpToolNames:()=>v4,createWindowsShellTool:()=>GW,createWebFetchTool:()=>TW,createWebFetchExecutor:()=>m2,createToolPoliciesWithPreset:()=>C4,createSubmitAndExitTool:()=>_W,createSkillsTool:()=>B$,createSearchTool:()=>KW,createSearchExecutor:()=>k2,createReadFilesTool:()=>yW,createFileReadExecutor:()=>S2,createEditorTool:()=>DW,createEditorExecutor:()=>C2,createDefaultToolsWithPreset:()=>E4,createDefaultTools:()=>S0,createDefaultExecutors:()=>Q1,createBuiltinTools:()=>T$,createBashTool:()=>UW,createBashExecutor:()=>w2,createAskQuestionTool:()=>MW,createApplyPatchTool:()=>hW,createApplyPatchExecutor:()=>b2,WebFetchRequestSchema:()=>RW,ToolPresets:()=>Nf,TEAM_TOOL_NAMES:()=>Y1,SubmitInputSchema:()=>q2,SkillsInputSchema:()=>O2,SearchCodebaseInputSchema:()=>M2,RunCommandsInputSchema:()=>J1,ReadFilesInputSchema:()=>D2,ReadFileRequestSchema:()=>b0,FetchWebContentInputSchema:()=>_2,EditFileInputSchema:()=>L2,DefaultToolNames:()=>ff,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>Z1,AskQuestionInputSchema:()=>N2,ApplyPatchInputSchema:()=>z2,ALL_DEFAULT_TOOL_NAMES:()=>q0});import{validateWithZod as SA,zodToJsonSchema as kA}from"@cline/shared";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];import{createTool as V0,validateWithZod as E0,zodToJsonSchema as sf}from"@cline/shared";import{validateWithZod as r3}from"@cline/shared";import{z as D}from"zod";var w0=6000,YW=D.string().describe("The absolute file path of a text file to read content from"),I3=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"),b0=D.object({path:YW,start_line:I3.shape.start_line,end_line:I3.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),D2=D.object({files:D.array(b0).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.")}),x3=D.union([D2,b0,D.array(b0),D.array(D.string()),D.string(),D.object({files:b0}),D.object({file_paths:D.array(YW)}),D.object({file_paths:D.string()}),D.object({paths:D.array(D.union([YW,b0]))}),D.object({paths:b0}),D.object({paths:D.string()})]),M2=D.object({queries:D.array(D.string()).describe("Array of regex search queries to execute")}),g3=D.union([M2,D.array(D.string()),D.string(),D.object({queries:D.string()})]),Y$=D.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${w0*2} characters) to avoid timeouts.`),J1=D.object({commands:D.array(Y$).describe("Array of shell commands to execute")}),v3=D.union([J1,D.object({commands:Y$}),D.object({command:Y$}),D.object({cmd:Y$}),D.array(D.string()),D.string()]),BW=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.")}),u3=D.union([Y$,BW]),AW=D.object({commands:D.array(u3).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.")}),c3=D.union([J1,AW,D.object({commands:u3}),D.array(BW),BW,D.object({command:Y$}),D.object({cmd:Y$}),D.array(D.string()),D.string()]),RW=D.object({url:D.string().describe("The URL to fetch"),prompt:D.string().min(2).describe("Analysis prompt for the fetched content")}),_2=D.object({requests:D.array(RW).describe("Array of the URLs for the web fetch requests")}),L2=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 ${w0} 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 ${w0} 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."),z2=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."),d3=D.union([z2,D.string()]),O2=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")}),N2=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")}),q2=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.
|
|
42
|
+
${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fileOps,tokensBefore:f.tokensBefore,generatedAt:Date.now()}}}async function IB(f){let $=kB(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 d3(f){let $=f.context.messages;if($.length<2)return;let J=m3($,f.preserveRecentTokens,f.estimateMessageTokens);if(J<=0||J>=$.length)return;let W=$.slice(0,J),H=I3(W),Q=H>=0?P5(W[H])?.summary:void 0,Z=H>=0?W.slice(H+1):W;if(Z.length===0)return;let j=x3(W),X=b3(Z),A=await IB({providerConfig:u3({activeProviderConfig:f.providerConfig,summarizer:f.summarizer}),request:v3({previousSummary:Q,conversationText:X,fileOps:j}),logger:f.logger});if(!A.trim())return;let P=g3(A,j),B=$.reduce((R,U)=>R+f.estimateMessageTokens(U),0),Y=[c3({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 p3(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 _2(f,$){return f.reduce((J,W)=>J+$(W),0)}function r3(f,$){let J=Math.max(1,$),W=Math.max(16,J*4);if(typeof f.content==="string"){let Z=R$(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=R$(Z.text,H).trim();return H-=j.length,{...Z,text:j||"..."}});return{...f,content:Q}}function mB(f,$){let J=S3(f),W=B5(f),H=k3(f),Q=[];for(let Z=0;Z<f.length;Z+=1){let j=p3(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 l3(f,$,J,W){let H=f[$];H.message=J,H.estimatedTokens=W(J)}function E4(f,$,J,W){let H=_2(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 xB(f,$,J){let W=_2(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(q3,Z.estimatedTokens-(W-$));if(j>=Z.estimatedTokens)continue;l3(f,Q,r3(Z.message,j),J),W=_2(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-$));l3(f,H,r3(f[H].message,Q),J)}}function gB(f,$){return JSON.stringify(f)!==JSON.stringify($)}function i3(f){let $=Math.max(1,Math.min(f.context.triggerTokens,f.context.contextWindowTokens)),J=mB(f.context.messages,f.estimateMessageTokens);if(J.length===0)return;E4(J,(Z)=>Z.message.role==="assistant"&&!Z.isLastAssistant,$,f.estimateMessageTokens),E4(J,(Z)=>Z.message.role==="user"&&!Z.isFirstUser&&!Z.isLastUser,$,f.estimateMessageTokens),E4(J,(Z)=>Z.message.role==="assistant"&&Z.isLastAssistant,$,f.estimateMessageTokens),E4(J,(Z)=>Z.message.role==="user"&&Z.isLastUser&&!Z.isFirstUser,$,f.estimateMessageTokens),xB(J,$,f.estimateMessageTokens);let W=J.map((Z)=>Z.message);if(!gB(f.context.messages,W))return;let H=_2(f.context.messages.map((Z)=>p3(Z)??Z),f.estimateMessageTokens),Q=_2(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 vB={basic:({context:f,estimateMessageTokens:$,logger:J})=>i3({context:f,estimateMessageTokens:$,logger:J}),agentic:({context:f,providerConfig:$,compaction:J,mode:W,estimateMessageTokens:H,logger:Q})=>d3({context:f,providerConfig:$,summarizer:J?.summarizer,preserveRecentTokens:W==="manual"?Math.min(J?.preserveRecentTokens??A5,f.triggerTokens):J?.preserveRecentTokens??A5,estimateMessageTokens:H,logger:Q})};function uB(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??N3,J=f.contextWindowTokens*$;return{shouldCompact:f.inputTokens>J,triggerTokens:J,thresholdRatio:$}}function cB(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 M2(f,$={}){let J=f.compaction;if(J?.enabled!==!0)return;let W=f.providerConfig??{providerId:f.providerId,modelId:f.modelId},H=C3(),Q=J?.strategy??"basic",Z=vB[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??z3;if(typeof P!=="number"||!Number.isFinite(P)||P<=0)return;let B=uB({inputTokens:A,contextWindowTokens:P,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if(j==="auto"&&!B.shouldCompact)return;let Y=j==="manual"?cB({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 j7={};N(j7,{zodToJsonSchema:()=>$R,validateWithZod:()=>fR,resolveToolRoutingConfig:()=>A1,resolveToolPresetName:()=>K0,resolveCoreSelectedToolIds:()=>r4,getCoreHeadlessToolNames:()=>u2,getCoreDefaultEnabledToolIds:()=>d4,getCoreBuiltinToolCatalog:()=>M$,getCoreAcpToolNames:()=>l4,createWindowsShellTool:()=>T5,createWebFetchTool:()=>D5,createWebFetchExecutor:()=>x2,createToolPoliciesWithPreset:()=>x4,createSubmitAndExitTool:()=>h5,createSkillsTool:()=>K$,createSearchTool:()=>U5,createSearchExecutor:()=>m2,createReadFilesTool:()=>y5,createFileReadExecutor:()=>I2,createEditorTool:()=>M5,createEditorExecutor:()=>S2,createDefaultToolsWithPreset:()=>g4,createDefaultTools:()=>v0,createDefaultExecutors:()=>j1,createBuiltinTools:()=>L$,createBashTool:()=>G5,createBashExecutor:()=>E2,createAskQuestionTool:()=>L5,createApplyPatchTool:()=>_5,createApplyPatchExecutor:()=>C2,WebFetchRequestSchema:()=>F5,ToolPresets:()=>Ef,TEAM_TOOL_NAMES:()=>V1,SubmitInputSchema:()=>b2,SkillsInputSchema:()=>q2,SearchCodebaseInputSchema:()=>h2,RunCommandsInputSchema:()=>H1,ReadFilesInputSchema:()=>L2,ReadFileRequestSchema:()=>I0,FetchWebContentInputSchema:()=>O2,EditFileInputSchema:()=>z2,DefaultToolNames:()=>Jf,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>X1,AskQuestionInputSchema:()=>w2,ApplyPatchInputSchema:()=>N2,ALL_DEFAULT_TOOL_NAMES:()=>k0});import{validateWithZod as fR,zodToJsonSchema as $R}from"@cline/shared";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];import{createTool as R0,validateWithZod as g0,zodToJsonSchema as ef}from"@cline/shared";import{validateWithZod as JQ}from"@cline/shared";import{z as G}from"zod";var m0=6000,Y5=G.string().describe("The absolute file path of a text file to read content from"),a3=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"),I0=G.object({path:Y5,start_line:a3.shape.start_line,end_line:a3.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),L2=G.object({files:G.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.")}),t3=G.union([L2,I0,G.array(I0),G.array(G.string()),G.string(),G.object({files:I0}),G.object({file_paths:G.array(Y5)}),G.object({file_paths:G.string()}),G.object({paths:G.array(G.union([Y5,I0]))}),G.object({paths:I0}),G.object({paths:G.string()})]),h2=G.object({queries:G.array(G.string()).describe("Array of regex search queries to execute")}),s3=G.union([h2,G.array(G.string()),G.string(),G.object({queries:G.string()})]),F$=G.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${m0*2} characters) to avoid timeouts.`),H1=G.object({commands:G.array(F$).describe("Array of shell commands to execute")}),o3=G.union([H1,G.object({commands:F$}),G.object({command:F$}),G.object({cmd:F$}),G.array(G.string()),G.string()]),V5=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.")}),e3=G.union([F$,V5]),R5=G.object({commands:G.array(e3).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.")}),fQ=G.union([H1,R5,G.object({commands:e3}),G.array(V5),V5,G.object({command:F$}),G.object({cmd:F$}),G.array(G.string()),G.string()]),F5=G.object({url:G.string().describe("The URL to fetch"),prompt:G.string().min(2).describe("Analysis prompt for the fetched content")}),O2=G.object({requests:G.array(F5).describe("Array of the URLs for the web fetch requests")}),z2=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 ${m0} 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 ${m0} 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."),N2=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."),$Q=G.union([N2,G.string()]),q2=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")}),w2=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")}),b2=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.
|
|
43
43
|
'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
|
|
44
|
-
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
|
|
44
|
+
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 x0(f){if(f instanceof Error)return f.message;return String(f)}function WQ(f){if(typeof f.old_text==="string"&&f.old_text.length>m0)return`Editor input too large: old_text was ${f.old_text.length} characters, exceeding the recommended limit of ${m0}. 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>m0)return`Editor input too large: new_text was ${f.new_text.length} characters, exceeding the recommended limit of ${m0}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}function of(f,$,J){return Promise.race([f,new Promise((W,H)=>{setTimeout(()=>H(Error(J)),$)})])}function HQ(f){let $=JQ(t3,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 S4(f){let{path:$,start_line:J,end_line:W}=f;if(J==null&&W==null)return $;return`${$}:${J??1}-${W??"EOF"}`}function QQ(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 ZQ(f){let $=JQ(fQ,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 K5(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 y5(f,$={}){let J=$.fileReadTimeoutMs??1e4;return R0({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:ef(L2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(W,H)=>{let Q=HQ(W);return Promise.all(Q.map(async(Z)=>{let j=QQ(Z);if(j)return{query:S4(Z),result:"",error:`Invalid file range: ${j}`,success:!1};try{let X=await of(f(Z,H),J,`File read timed out after ${J}ms`);return{query:S4(Z),result:X,success:!0}}catch(X){let A=x0(X);return{query:S4(Z),result:"",error:`Error reading file: ${A}`,success:!1}}}))}})}function U5(f,$={}){let J=$.searchTimeoutMs??30000,W=$.cwd??process.cwd();return R0({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:ef(h2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(H,Q)=>{let Z=g0(s3,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 of(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=x0(A);return{query:X,result:"",error:`Search failed: ${P}`,success:!1}}}))}})}function G5(f,$={}){let J=$.bashTimeoutMs??30000,W=$.cwd??process.cwd();return R0({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:ef(H1),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=g0(o3,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 of(f(X,W,Q),J,`Command timed out after ${J}ms`);return{query:X,result:A,success:!0}}catch(A){let P=x0(A);return{query:X,result:"",error:`Command failed: ${P}`,success:!1}}}))}})}function T5(f,$={}){let J=$.bashTimeoutMs??30000,W=$.cwd??process.cwd();return R0({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:ef(R5),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=ZQ(H);return Promise.all(Z.map(async(j)=>{try{let X=await of(f(j,W,Q),J,`Command timed out after ${J}ms`);return{query:K5(j),result:X,success:!0}}catch(X){let A=x0(X);return{query:K5(j),result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function D5(f,$={}){let J=$.webFetchTimeoutMs??30000;return R0({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:ef(O2),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(W,H)=>{let Q=g0(O2,W);return Promise.all(Q.requests.map(async(Z)=>{try{let j=await of(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=x0(j);return{query:Z.url,result:"",error:`Error fetching web content: ${X}`,success:!1}}}))}})}var dB=`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:
|
|
45
45
|
|
|
46
46
|
*** Begin Patch
|
|
47
47
|
*** Update File: path/to/file.ts
|
|
@@ -77,68 +77,68 @@ Example:
|
|
|
77
77
|
</div>
|
|
78
78
|
);
|
|
79
79
|
}
|
|
80
|
-
*** End Patch`;function
|
|
81
|
-
`),H=0,Q=[
|
|
82
|
-
${this.lines[this.index]}`);if(j?.trim()){let
|
|
83
|
-
`);this.addWarning({path:this.currentPath||$,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${U.toFixed(2)}). Chunk skipped.`,context:
|
|
84
|
-
`),chunks:[]}}}function
|
|
85
|
-
`));for(let
|
|
86
|
-
`));if(
|
|
87
|
-
`)),
|
|
88
|
-
`));if(
|
|
89
|
-
`)),
|
|
90
|
-
`));if(
|
|
91
|
-
`)),
|
|
92
|
-
`).map(($)=>$.replace(/\r$/,""))}function
|
|
93
|
-
`),H=[],Q=0;for(let Z of $){if(Z.origIndex>W.length)throw new
|
|
94
|
-
`)}async function
|
|
95
|
-
`)}return Q}function
|
|
96
|
-
`)}}import{spawn as
|
|
80
|
+
*** End Patch`;function _5(f,$={}){let J=$.applyPatchTimeoutMs??30000,W=$.cwd??process.cwd();return R0({name:"apply_patch",description:dB,inputSchema:ef(N2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=g0($Q,H),j=typeof Z==="string"?Z:Z.input;try{return{query:"apply_patch",result:await of(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: ${x0(X)}`,success:!1}}}})}function M5(f,$={}){let J=$.editorTimeoutMs??30000,W=$.cwd??process.cwd();return R0({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:ef(z2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=g0(z2,H),j=Z.insert_line==null?"edit":"insert",X=WQ(Z);if(X)return{query:`${j}:${Z.path}`,result:"",error:X,success:!1};try{let A=await of(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=x0(A);return{query:`${j}:${Z.path}`,result:"",error:`Editor operation failed: ${P}`,success:!1}}}})}function K$(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=R0({name:"skills",description:W,inputSchema:ef(q2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,Z)=>{let j=g0(q2,Q);return of(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 L5(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:ef(w2),retryable:!1,maxRetries:0,execute:async($,J)=>{let W=g0(w2,$);return f(W.question,W.options,J)}}}function h5(f,$={}){let J=$.submitTimeoutMs??15000;return R0({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:ef(b2),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,H)=>{let Q=g0(b2,W);return of(f(Q.summary,Q.verified,H),J,`submit_and_exit timed out after ${J}ms`)}})}function v0(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(y5($.readFile,B));if(W&&$.search)Y.push(U5($.search,B));if(H&&$.bash)if(process.platform==="win32")Y.push(T5($.bash,B));else Y.push(G5($.bash,B));if(Q&&$.webFetch)Y.push(D5($.webFetch,B));if(j&&$.editor)Y.push(M5($.editor,B));else if(Z&&$.applyPatch)Y.push(_5($.applyPatch,B));if(X&&$.skills)Y.push(K$($.skills,B));let V=P?$.submit:void 0;if(A&&$.askQuestion&&!V)Y.push(L5($.askQuestion));if(V)Y.push(h5(V,B));return Y}import*as bf from"node:fs/promises";import*as Cf 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"},XQ=["%%bash","apply_patch","EOF","```"];class Qf extends Error{constructor(f){super(f);this.name="DiffError"}}function wf(f){let $={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return f.normalize("NFC").replace(/./gu,(J)=>$[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class O5{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(`
|
|
81
|
+
`),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:
|
|
82
|
+
${this.lines[this.index]}`);if(j?.trim()){let K=wf(j.trim());for(let F=H;F<W.length;F++){let y=W[F];if(y&&(wf(y)===K||wf(y.trim())===K)){if(H=F+1,wf(y.trim())===K&&wf(y)!==K)this.fuzz++;break}}}let[A,P,B,Y]=pB(this.lines,this.index),[V,R,U]=lB(W,A,H,Y);if(V===-1){let K=A.join(`
|
|
83
|
+
`);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(`
|
|
84
|
+
`),chunks:[]}}}function jQ(f,$){let J=f.length>$.length?f:$,W=f.length>$.length?$:f;if(J.length===0)return 1;let H=rB(W,J);return(J.length-H)/J.length}function rB(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 lB(f,$,J,W){if($.length===0)return[J,0,1];let H=0,Q=(Z)=>{let j=wf($.join(`
|
|
85
|
+
`));for(let A=Z;A<f.length;A++){let P=wf(f.slice(A,A+$.length).join(`
|
|
86
|
+
`));if(P===j)return[A,0,1];let B=jQ(P,j);if(B>H)H=B}for(let A=Z;A<f.length;A++){let P=wf(f.slice(A,A+$.length).map((Y)=>Y.trimEnd()).join(`
|
|
87
|
+
`)),B=wf($.map((Y)=>Y.trimEnd()).join(`
|
|
88
|
+
`));if(P===B)return[A,1,1]}for(let A=Z;A<f.length;A++){let P=wf(f.slice(A,A+$.length).map((Y)=>Y.trim()).join(`
|
|
89
|
+
`)),B=wf($.map((Y)=>Y.trim()).join(`
|
|
90
|
+
`));if(P===B)return[A,100,1]}let X=0.66;for(let A=Z;A<f.length;A++){let P=wf(f.slice(A,A+$.length).join(`
|
|
91
|
+
`)),B=jQ(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 pB(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 z5(f,$,J){let W=Cf.isAbsolute($),H=W?Cf.normalize($):Cf.resolve(f,$);if(!J||W)return H;let Q=Cf.relative(f,H);if(Q.startsWith("..")||Cf.isAbsolute(Q))throw new Qf(`Path must stay within cwd: ${$}`);return H}function iB(f){return f.split(`
|
|
92
|
+
`).map(($)=>$.replace(/\r$/,""))}function AQ(f){if(f.trim()==="")return!1;return XQ.some(($)=>f.startsWith($))}function nB(f){let $=0,J=f.length;while($<J&&AQ(f[$]??""))$++;while(J>$&&AQ(f[J-1]??""))J--;return f.slice($,J)}function aB(f){let $=iB(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=nB($);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 tB(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 sB(f,$,J){if($.length===0)return f;let W=f.split(`
|
|
93
|
+
`),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(`
|
|
94
|
+
`)}async function oB(f,$,J,W){let H=tB(f,[x.UPDATE,x.DELETE]),Q={};for(let Z of H){let j=z5($,Z,W),X;try{X=await bf.readFile(j,J)}catch{throw new Qf(`File not found: ${Z}`)}Q[Z]=X.replace(/\r\n/g,`
|
|
95
|
+
`)}return Q}function eB(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:sB($[W]??"",H.chunks,W),movePath:H.movePath};break}return J}async function fY(f,$,J,W){let H=[];for(let[Q,Z]of Object.entries(f)){let j=z5($,Q,W);switch(Z.type){case"delete":await bf.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 bf.mkdir(Cf.dirname(j),{recursive:!0}),await bf.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=z5($,Z.movePath,W);await bf.mkdir(Cf.dirname(X),{recursive:!0}),await bf.writeFile(X,Z.newContent,{encoding:J}),await bf.rm(j,{force:!0}),H.push(`${Q} -> ${Z.movePath}`)}else await bf.writeFile(j,Z.newContent,{encoding:J}),H.push(Q);break}}}return H}function C2(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0}=f;return async(W,H,Q)=>{let Z=aB(W.input),j=await oB(Z.lines,H,$,J),X=new O5(Z.lines,j),{patch:A,fuzz:P}=X.parse(),B=eB(A,j),Y=await fY(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(`
|
|
96
|
+
`)}}import{spawn as PQ}from"node:child_process";import{getDefaultShell as $Y,getShellArgs as JY}from"@cline/shared";function WY(f,$,J,W,H){return new Promise((Q,Z)=>{let j=process.platform==="win32",X=PQ(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){PQ("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?`
|
|
97
97
|
[stderr]
|
|
98
|
-
${
|
|
98
|
+
${B}`:""):P;if(Y>W)_+=`
|
|
99
99
|
|
|
100
|
-
[Output truncated: ${
|
|
100
|
+
[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 E2(f={}){let{shell:$=$Y(process.platform),timeoutMs:J=30000,maxOutputBytes:W=1e6,env:H={},combineOutput:Q=!0}=f;return(Z,j,X)=>{let A=typeof Z!=="string";return WY({executable:A?Z.command:$,args:A?Z.args??[]:JY($,Z),cwd:j,env:H},X,J,W,Q)}}import*as pf from"node:fs/promises";import*as lf from"node:path";function HY(f,$,J){let W=lf.isAbsolute($),H=W?lf.normalize($):lf.resolve(f,$);if(!J)return H;if(W)return H;let Q=lf.relative(f,H);if(Q.startsWith("..")||lf.isAbsolute(Q))throw Error(`Path must stay within cwd: ${$}`);return H}function QY(f,$){if($.length===0)return 0;return f.split($).length-1}function ZY(f,$,J){let W=f.split(`
|
|
101
101
|
`),H=$.split(`
|
|
102
|
-
`),Q=Math.max(W.length,H.length),Z=["```diff"],j=0;for(let
|
|
103
|
-
`)}async function
|
|
104
|
-
${
|
|
102
|
+
`),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(`
|
|
103
|
+
`)}async function jY(f,$,J){return await pf.mkdir(lf.dirname(f),{recursive:!0}),await pf.writeFile(f,$,{encoding:J}),`File created successfully at: ${f}`}async function XY(f){try{return await pf.access(f),!0}catch{return!1}}async function AY(f,$,J,W,H){let Q=await pf.readFile(f,W),Z=QY(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 pf.writeFile(f,j,{encoding:W});let X=ZY(Q,j,H);return`Edited ${f}
|
|
104
|
+
${X}`}async function PY(f,$,J,W){let Q=(await pf.readFile(f,W)).split(`
|
|
105
105
|
`),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(`
|
|
106
|
-
`)),await
|
|
107
|
-
`),{encoding:W}),`Inserted content at line ${$} in ${f}.`}function
|
|
108
|
-
`),U=Math.max((j??1)-1,0),
|
|
106
|
+
`)),await pf.writeFile(f,Q.join(`
|
|
107
|
+
`),{encoding:W}),`Inserted content at line ${$} in ${f}.`}function S2(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0,maxDiffLines:W=200}=f;return async(H,Q,Z)=>{let j=HY(Q,H.path,J);if(H.insert_line!=null)return PY(j,H.insert_line,H.new_text,$);if(!await XY(j))return jY(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 AY(j,H.old_text,H.new_text,$,W)}}import*as k2 from"node:fs/promises";import*as u0 from"node:path";var BY=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),YY={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function I2(f={}){let{maxFileSizeBytes:$,encoding:J,includeLineNumbers:W}={...YY,...f};return async(H,Q)=>{let{path:Z,start_line:j,end_line:X}=H,A=u0.isAbsolute(Z)?u0.normalize(Z):u0.resolve(process.cwd(),Z),P=u0.extname(A).toLowerCase(),B=BY.get(P),Y=await k2.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 k2.readFile(A);return[{type:"text",text:"Successfully read image"},{type:"image",data:y.toString("base64"),mediaType:B}]}let R=(await k2.readFile(A,J)).split(`
|
|
108
|
+
`),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(`
|
|
109
109
|
`)}return F.join(`
|
|
110
|
-
`)}}import{spawn as
|
|
111
|
-
`).filter((
|
|
112
|
-
`)}let
|
|
113
|
-
`);for(let
|
|
114
|
-
Searched ${U} files.`;let F=[`Found ${R.length} result${R.length===1?"":"s"} for pattern: ${
|
|
115
|
-
`)}}function
|
|
110
|
+
`)}}import{spawn as yQ}from"node:child_process";import*as UQ from"node:fs/promises";import*as m4 from"node:path";var KQ={};N(KQ,{prewarmFileIndex:()=>I4,getFileIndex:()=>F0,enrichPromptWithMentions:()=>Z1});import{spawn as VY}from"node:child_process";import{readdir as RY}from"node:fs/promises";import q5 from"node:path";import{isMainThread as VQ,parentPort as BQ,Worker as FY}from"node:worker_threads";var KY=15000,yY=600000,UY=1000,GY=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function YQ(f){let $=f&&typeof f==="object"&&"code"in f?String(f.code??""):"";return $==="EACCES"||$==="EPERM"||$==="ENOENT"}var Q1=new Map;function TY(f){if(Q1.size<=1)return;for(let[$,J]of Q1.entries()){if(J.pending)continue;if(f-J.lastAccessedAt>yY)Q1.delete($)}}function DY(f,$){return q5.relative(f,$).split(q5.sep).join("/")}async function _Y(f){let J=(await new Promise((W,H)=>{let Q=VY("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 RQ(f,$,J){let W;try{W=await RY($,{withFileTypes:!0})}catch(H){if(YQ(H))return;throw H}for(let H of W){let Q=q5.join($,H.name);if(H.isDirectory()){if(GY.has(H.name))continue;try{await RQ(f,Q,J)}catch(Z){if(YQ(Z))continue;throw Z}continue}if(H.isFile())J.add(DY(f,Q))}}async function MY(f){let $=new Set;return await RQ(f,f,$),$}async function k4(f){try{return await _Y(f)}catch{return MY(f)}}function LY(){if(VQ||!BQ)return;let f=BQ;f.on("message",($)=>{if($.type!=="index")return;k4($.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 FQ{worker=new FY(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)},UY);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($)}}LY();var N5;function hY(){if(!VQ)return null;if(N5===void 0)N5=new FQ;return N5}async function OY(f){let $=hY();if(!$)return k4(f);try{let J=await $.requestIndex(f);if(J===null)return k4(f);return new Set(J)}catch{return k4(f)}}async function F0(f,$={}){let J=$.ttlMs??KY,W=Date.now();TY(W);let H=Q1.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=OY(f).then((Z)=>{return Q1.set(f,{files:Z,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),Z});return Q1.set(f,{files:H?.files??new Set,lastBuiltAt:H?.lastBuiltAt??0,lastAccessedAt:W,pending:Q}),Q}async function I4(f,$={}){await F0(f,{...$,ttlMs:0})}import{stat as zY}from"node:fs/promises";import y$ from"node:path";var NY=/[),.:;!?`'"]+$/,qY=/^[(`'"]+/;function wY(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(qY,"").replace(NY,"");if(Q.length===0||Q.includes("@"))continue;J.push(Q)}return Array.from(new Set(J))}function bY(f,$){let J=f.replace(/\\/g,"/"),W=y$.isAbsolute(J)?y$.resolve(J):y$.resolve($,J),H=y$.relative($,W);if(H.startsWith("..")||y$.isAbsolute(H))return;return H.split(y$.sep).join("/")}async function Z1(f,$,J={}){let W=wY(f);if(W.length===0)return{prompt:f,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:H,maxFileBytes:Q,maxTotalBytes:Z}=J,j=await F0($,{ttlMs:J.ttlMs}),X=[],A=[],P=[],B=0;for(let Y of W){if(H&&P.length>=H){A.push(Y);continue}let V=bY(Y,$);if(!V||!j.has(V)){A.push(Y);continue}if(!Q||!Z){X.push(V);continue}let R=y$.join($,V);try{if(!(await zY(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 CY=["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"],EY=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],U$=null;function SY(){if(U$!==null)return Promise.resolve(U$);return new Promise((f)=>{let $=yQ("rg",["--version"],{stdio:["ignore","pipe","pipe"]});$.on("close",(J)=>{U$=J===0,f(U$)}),$.on("error",()=>{U$=!1,f(!1)}),setTimeout(()=>{if(!$.killed)$.kill("SIGTERM");if(U$===null)U$=!1,f(!1)},1000)})}function kY(f,$,J,W,H=5000,Q){return new Promise((Z)=>{let j=yQ("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(`
|
|
111
|
+
`).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 IY(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=m4.posix.extname(Q).slice(1).toLowerCase();return J.has(j)||!j&&!Q.startsWith(".")}function m2(f={}){let{includeExtensions:$=CY,excludeDirs:J=EY,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 SY(),Y=null;if(B)Y=await kY(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(`
|
|
112
|
+
`)}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 F0(A);for(let y of K){if(P.signal?.aborted)throw Error("Search operation aborted");if(!IY(y,Z,j,Q))continue;if(R.length>=W)break;U++;let D=m4.join(A,y);try{let T=(await UQ.readFile(D,"utf-8")).split(`
|
|
113
|
+
`);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}
|
|
114
|
+
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(`
|
|
115
|
+
`)}}function mY(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,`
|
|
116
116
|
`).replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&#(\d+);/g,($,J)=>String.fromCharCode(parseInt(J,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
|
|
117
117
|
`).replace(/\n{3,}/g,`
|
|
118
118
|
|
|
119
|
-
`).trim()}function
|
|
120
|
-
[Content truncated: showing first 50000 of ${
|
|
121
|
-
`)}catch(
|
|
119
|
+
`).trim()}function x2(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=mY(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(`
|
|
120
|
+
[Content truncated: showing first 50000 of ${T.length} characters]`);return _.push("","--- Analysis Request ---",`Prompt: ${j}`),_.join(`
|
|
121
|
+
`)}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 j1(f={}){return{readFile:I2(f.fileRead),search:m2(f.search),bash:E2(f.bash),webFetch:x2(f.webFetch),applyPatch:C2(f.applyPatch),editor:S2(f.editor)}}var xY={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"},X1=[{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 GQ(f,$){if(!$||$.length===0)return!0;let J=f.toLowerCase();return $.some((W)=>J.includes(W.toLowerCase()))}function gY(f,$,J,W){if(f.mode&&f.mode!=="any"&&f.mode!==W)return!1;return GQ($,f.providerIdIncludes)&&GQ(J,f.modelIdIncludes)}function A1(f,$,J,W){if(!W||W.length===0)return{};let H=new Map;for(let Z of W){if(!gY(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[xY[Z]]=j;return Q}var Ef={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 K0(f){if(f.mode==="plan")return"plan";if(f.mode==="yolo")return"yolo";return"act"}function x4(f){if(f!=="yolo")return{};let $={enabled:!0,autoApprove:!0},J={"*":$};for(let W of k0)J[W]=$;return J}function g4(f,$){let J=Ef[f],{enableSpawnAgent:W,enableAgentTeams:H,...Q}=J;return v0({...Q,...$})}import{createTool as bV,zodToJsonSchema as CV}from"@cline/shared";import{z as g5}from"zod";import{createAgentRuntime as _V}from"@cline/agents";import{createContributionRegistry as MV}from"@cline/shared";import{createGateway as vY,MODEL_COLLECTIONS_BY_PROVIDER_ID as uY}from"@cline/llms";function w5(f){let $=f.providerConfig;if($?.knownModels)return $.knownModels;if(f.knownModels)return f.knownModels;return uY[f.providerId]?.models??void 0}function TQ(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:w5(f),maxOutputTokens:f.maxTokensPerTurn,reasoningEffort:f.reasoningEffort,thinkingBudgetTokens:f.thinkingBudgetTokens,thinking:f.thinking,logger:$,extensionContext:f.extensionContext};return vY({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 DQ}from"@cline/shared";var cY=50000,dY=6000000,_Q=8000,rY=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),lY=new Set(["read","read_files"]),G$="[outdated - see the latest file content]",MQ="Tool execution was interrupted before a result was produced.",pY=(f)=>`
|
|
122
122
|
|
|
123
123
|
...[truncated ${f} chars]...
|
|
124
124
|
|
|
125
|
-
`,
|
|
125
|
+
`,iY=(f)=>`
|
|
126
126
|
|
|
127
127
|
...[truncated ${f} chars to fit provider request budget]...
|
|
128
128
|
|
|
129
|
-
`;class wW{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor(f=DB,$=_B,J=MB){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=X7(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=X7(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 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=[],W=new Map,H=!1,Q=()=>{if(W.size===0)return;Z(this.createMissingToolResultMessage(W)),W.clear(),H=!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)]},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 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},W);if(Z(V),W.size>0)W.clear();H=!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,$,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?`${Y7} Tool: ${f}.`:Y7}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)??F$;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:F$}}if(Q.type==="image"){if(H===0)return Q;return H-=1,{type:"text",text:F$}}if(Q.type!=="text")return Q;let Z=this.replaceOutdatedInString(Q.text,J);if(Z===null)return{...Q,text:F$};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=F$;else if(typeof W.content==="string")W.content=F$;else W.result=F$;return W}isReadTool(f){return!!f&&LB.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 bW(f,this.maxToolResultChars,zB)}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)=>qB(Q))}}),W=this.collectTruncationCandidates(J);for(let H of W){if($<=this.maxTotalTextBytes)break;let Q=H.byteLength;if(Q<=V7)continue;let Z=$-this.maxTotalTextBytes,j=Math.max(V7,Q-Z),P=NB(H.get(),j,OB);H.set(P),$-=Q-Kf(P)}return J}countMessageTextBytes(f){let $=0;for(let J of f){if(typeof J.content==="string"){$+=Kf(J.content);continue}for(let W of J.content)if(W.type==="text")$+=Kf(W.text);else if(W.type==="thinking")$+=Kf(W.thinking);else if(W.type==="file")$+=Kf(W.content);else if(W.type==="tool_result"){if(typeof W.content==="string")$+=Kf(W.content);else for(let H of W.content)if(H.type==="text")$+=Kf(H.text);else if(H.type==="file")$+=Kf(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:Kf(W.content),get:()=>W.content,set:(Q)=>{W.content=Q}});continue}for(let Q of W.content)if(Q.type==="text")$.push({byteLength:Kf(Q.text),get:()=>Q.text,set:(Z)=>{Q.text=Z}});else if(Q.type==="file")$.push({byteLength:Kf(Q.content),get:()=>Q.content,set:(Z)=>{Q.content=Z}})}}return $.sort((J,W)=>W.byteLength-J.byteLength)}}function Kf(f){return Buffer.byteLength(f,"utf8")}function bW(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)),P=f.slice(0,j),X=j>0?f.slice(-j):"";return`${P}${Z}${X}`}function NB(f,$,J){if(Kf(f)<=$)return f;let W=0,H=f.length,Q=bW(f,0,J);while(W<=H){let Z=W+H>>>1,j=bW(f,Z,J);if(Kf(j)<=$)Q=j,W=Z+1;else H=Z-1}return Q}function qB(f){if(f.type!=="tool_result"||typeof f.content==="string")return{...f};return{...f,content:f.content.map(($)=>({...$}))}}function CW(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class EW{messages=[];conversationId=CW();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=CW(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=CW(),this.sessionStarted=!1}restore(f){this.messages=[...f],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function bB(f){let $=CB(f.content),J=[],W=f.id??kB(),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(EB),createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:B7(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:B7(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:[F7(j)],createdAt:f.ts??Date.now(),metadata:f.metadata})}return Z(),J}function S4(f){return f.flatMap(bB)}function wB(f){let $=f.content.map(y7).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:SB(f.metrics)}}function P1(f){return f.map(wB)}function R7(f){let $=[];for(let J of f){let W=J.content.map(y7).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 CB(f){if(typeof f==="string")return f.length>0?[{type:"text",text:f}]:[];return[...f]}function EB(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 F7(f)}}function F7(f){return{type:"tool-result",toolCallId:f.tool_use_id,toolName:"",output:f.content,isError:f.is_error}}function y7(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 B7(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 SB(f){if(!f)return;return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,cost:f.cost}}var A7=0;function kB(){return A7+=1,`msg_${Date.now().toString(36)}_${A7.toString(36)}`}function K7(f){let{agentConfig:$}=f,J=mB($),W=IB($),H=f.hooks,Q=xB($.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??gB($.telemetry),initialMessages:f.initialMessages,completionPolicy:$.completionPolicy,maxIterations:$.maxIterations,toolExecution:Q,toolPolicies:$.toolPolicies,toolContextMetadata:f.toolContextMetadata,requestToolApproval:$.requestToolApproval}}function mB(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 IB(f){let $=f.providerConfig?.family;return{id:f.modelId,provider:f.providerId,family:$}}function xB(f){if(f===void 0)return;return f>=2?"parallel":"sequential"}function gB(f){if(!f)return;return{capture:($,J)=>{f.capture({event:$,properties:J})}}}function vB(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function uB(f){f.lastToolName="",f.lastToolSignature="",f.consecutiveIdenticalCount=0}function SW(f){if(f==null||typeof f!=="object")return f;if(Array.isArray(f))return f.map(SW);let $={};for(let J of Object.keys(f).sort())$[J]=SW(f[J]);return $}function cB(f){if(f==null)return"null";if(typeof f==="string")return f;if(typeof f!=="object")return String(f);try{return JSON.stringify(SW(f))}catch{return String(f)}}function dB(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 U7={softThreshold:3,hardThreshold:5};class kW{config;state=vB();constructor(f){this.config={softThreshold:f?.softThreshold??U7.softThreshold,hardThreshold:f?.hardThreshold??U7.hardThreshold}}inspect(f){let $=cB(f.input),J=dB(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(){uB(this.state)}}class mW{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 lB({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:rB({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 rB(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 lB(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 pB(f){let $=f.content.filter((J)=>J.type==="text");if($.length===0)return;return $.map((J)=>J.text).join("")}function iB(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 nB(f){return f.content.find(($)=>$.type==="tool-result")}function aB(f){switch(f){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function tB(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 IW{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=pB(f);if(J!==void 0)$.push({type:"content_end",contentType:"text",text:J});let W=iB(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=nB(f.message),H=W?.output,Q=tB(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:aB(f.status),text:f.outputText,iterations:f.iterations,usage:$}]}}function HA(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 QA(f){let J=(typeof f.content==="function"?await f.content():f.content).trim();return J.length>0?J:void 0}function ZA(f,$){let J=f.trim(),W=$.map((H)=>H.trim()).filter(Boolean).join(`
|
|
129
|
+
`;class C5{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor(f=cY,$=rY,J=dY){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=DQ(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=DQ(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?`${MQ} Tool: ${f}.`:MQ}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)??G$;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:G$}}if(Q.type==="image"){if(H===0)return Q;return H-=1,{type:"text",text:G$}}if(Q.type!=="text")return Q;let Z=this.replaceOutdatedInString(Q.text,J);if(Z===null)return{...Q,text:G$};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=G$;else if(typeof W.content==="string")W.content=G$;else W.result=G$;return W}isReadTool(f){return!!f&&lY.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 b5(f,this.maxToolResultChars,pY)}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)=>aY(Q))}}),W=this.collectTruncationCandidates(J);for(let H of W){if($<=this.maxTotalTextBytes)break;let Q=H.byteLength;if(Q<=_Q)continue;let Z=$-this.maxTotalTextBytes,j=Math.max(_Q,Q-Z),X=nY(H.get(),j,iY);H.set(X),$-=Q-_f(X)}return J}countMessageTextBytes(f){let $=0;for(let J of f){if(typeof J.content==="string"){$+=_f(J.content);continue}for(let W of J.content)if(W.type==="text")$+=_f(W.text);else if(W.type==="thinking")$+=_f(W.thinking);else if(W.type==="file")$+=_f(W.content);else if(W.type==="tool_result"){if(typeof W.content==="string")$+=_f(W.content);else for(let H of W.content)if(H.type==="text")$+=_f(H.text);else if(H.type==="file")$+=_f(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:_f(W.content),get:()=>W.content,set:(Q)=>{W.content=Q}});continue}for(let Q of W.content)if(Q.type==="text")$.push({byteLength:_f(Q.text),get:()=>Q.text,set:(Z)=>{Q.text=Z}});else if(Q.type==="file")$.push({byteLength:_f(Q.content),get:()=>Q.content,set:(Z)=>{Q.content=Z}})}}return $.sort((J,W)=>W.byteLength-J.byteLength)}}function _f(f){return Buffer.byteLength(f,"utf8")}function b5(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 nY(f,$,J){if(_f(f)<=$)return f;let W=0,H=f.length,Q=b5(f,0,J);while(W<=H){let Z=W+H>>>1,j=b5(f,Z,J);if(_f(j)<=$)Q=j,W=Z+1;else H=Z-1}return Q}function aY(f){if(f.type!=="tool_result"||typeof f.content==="string")return{...f};return{...f,content:f.content.map(($)=>({...$}))}}function E5(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class S5{messages=[];conversationId=E5();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=E5(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=E5(),this.sessionStarted=!1}restore(f){this.messages=[...f],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function tY(f){let $=oY(f.content),J=[],W=f.id??$V(),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(eY),createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:LQ(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:LQ(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:[zQ(j)],createdAt:f.ts??Date.now(),metadata:f.metadata})}return Z(),J}function v4(f){return f.flatMap(tY)}function sY(f){let $=f.content.map(NQ).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:fV(f.metrics)}}function P1(f){return f.map(sY)}function OQ(f){let $=[];for(let J of f){let W=J.content.map(NQ).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 oY(f){if(typeof f==="string")return f.length>0?[{type:"text",text:f}]:[];return[...f]}function eY(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 zQ(f)}}function zQ(f){return{type:"tool-result",toolCallId:f.tool_use_id,toolName:"",output:f.content,isError:f.is_error}}function NQ(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 LQ(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 fV(f){if(!f)return;return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,cost:f.cost}}var hQ=0;function $V(){return hQ+=1,`msg_${Date.now().toString(36)}_${hQ.toString(36)}`}function qQ(f){let{agentConfig:$}=f,J=JV($),W=WV($),H=f.hooks,Q=HV($.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??QV($.telemetry),initialMessages:f.initialMessages,completionPolicy:$.completionPolicy,maxIterations:$.maxIterations,toolExecution:Q,toolPolicies:$.toolPolicies,toolContextMetadata:f.toolContextMetadata,requestToolApproval:$.requestToolApproval}}function JV(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 WV(f){let $=f.providerConfig?.family;return{id:f.modelId,provider:f.providerId,family:$}}function HV(f){if(f===void 0)return;return f>=2?"parallel":"sequential"}function QV(f){if(!f)return;return{capture:($,J)=>{f.capture({event:$,properties:J})}}}function ZV(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function jV(f){f.lastToolName="",f.lastToolSignature="",f.consecutiveIdenticalCount=0}function k5(f){if(f==null||typeof f!=="object")return f;if(Array.isArray(f))return f.map(k5);let $={};for(let J of Object.keys(f).sort())$[J]=k5(f[J]);return $}function XV(f){if(f==null)return"null";if(typeof f==="string")return f;if(typeof f!=="object")return String(f);try{return JSON.stringify(k5(f))}catch{return String(f)}}function AV(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 wQ={softThreshold:3,hardThreshold:5};class I5{config;state=ZV();constructor(f){this.config={softThreshold:f?.softThreshold??wQ.softThreshold,hardThreshold:f?.hardThreshold??wQ.hardThreshold}}inspect(f){let $=XV(f.input),J=AV(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(){jV(this.state)}}class m5{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 BV({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:PV({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 PV(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 BV(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 YV(f){let $=f.content.filter((J)=>J.type==="text");if($.length===0)return;return $.map((J)=>J.text).join("")}function VV(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 RV(f){return f.content.find(($)=>$.type==="tool-result")}function FV(f){switch(f){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function KV(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 x5{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=YV(f);if(J!==void 0)$.push({type:"content_end",contentType:"text",text:J});let W=VV(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=RV(f.message),H=W?.output,Q=KV(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:FV(f.status),text:f.outputText,iterations:f.iterations,usage:$}]}}function LV(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 hV(f){let J=(typeof f.content==="function"?await f.content():f.content).trim();return J.length>0?J:void 0}function OV(f,$){let J=f.trim(),W=$.map((H)=>H.trim()).filter(Boolean).join(`
|
|
130
130
|
|
|
131
131
|
`);if(J&&W)return`${J}
|
|
132
132
|
|
|
133
|
-
${W}`;return J||W}function jA(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 m0{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 IW;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??JA,this.conversation=new EW(f.initialMessages),this.messageBuilder=new wW,this.contributionRegistry=WA({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 mW({maxConsecutiveMistakes:J,onLimitReached:f.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,Z,j)=>PA(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 kW(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 QA($);if(J)f.push(J)}return ZA(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 VA(J,f.userImages,f.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let W=await this.composeSystemPrompt(),H=P7(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=T7(this.config),X=Array.from(Z.values()),V=S4(this.conversation.getMessages()),Y=K7({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:j,parentAgentId:this.parentAgentId,model:H,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:W}),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=P1(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=jA([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=P1(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:S4(Z.messages)}:{},...Z.systemPrompt!==void 0?{systemPrompt:Z.systemPrompt}:{}}}}async prepareMessagesForModelRequest(f){let $=await this.prepareProviderMessagesForApi(R7(f));return S4($)}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((P)=>P.type==="tool-result"),Q=H?.type==="tool-result"&&H.isError===!0,Z=Q?HA(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(P1(f));return}if($.length===0)return;let J=new Set(this.conversation.getMessages().map((H)=>H.id).filter((H)=>typeof H==="string")),W=P1($).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":XA($),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=$?P1($.messages):this.conversation.getMessages(),V=T7(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:W,endedAt:H,durationMs:Q}}}function PA(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 XA(f){if(!f)return"error";switch(f.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function VA(f,$,J,W){let{buildInitialUserContent:H}=await Promise.resolve().then(() => G7);return H(f,$,J,W)}function T7(f){if(f.knownModels?.[f.modelId])return f.knownModels[f.modelId];let $=qW(f);if($?.[f.modelId])return $[f.modelId];return}import{buildClineSystemPrompt as h7}from"@cline/shared";function D7(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return h7({ide:$.clineIdeName?.trim()||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,rules:`# Team Teammate Role
|
|
134
|
-
${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function M7(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return h7({ide:$.clineIdeName||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,overridePrompt:J,metadata:$.workspaceMetadata,platform:$.clinePlatform})}function X1(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 y$(f){let $=f.configProvider.getRuntimeConfig(),J=f.kind==="teammate"?D7(f.prompt,$):M7(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 V1(f){let $=y$(f),J=new m0($);if($.onEvent)J.subscribeEvents($.onEvent);return J}var AA=xW.object({systemPrompt:xW.string().describe("System prompt defining the sub-agent's behavior"),task:xW.string().describe("Task for the sub-agent to complete")});function I0(f){return YA({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:BA(AA),execute:async($,J)=>{let W=f.createSubAgentTools?await f.createSubAgentTools($,J):f.subAgentTools??[],H=V1({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 P=await H.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 Wf,TEAM_AWAIT_TIMEOUT_MS as RA,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as FA,TEAM_RUN_TEXT_PREVIEW_LIMIT as yA,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as KA,TeamAttachOutcomeFragmentInputSchema as _7,TeamAwaitRunsInputSchema as L7,TeamBroadcastInputSchema as z7,TeamBroadcastToolResultSchema as UA,TeamCancelRunInputSchema as O7,TeamCancelRunToolResultSchema as GA,TeamCleanupInputSchema as N7,TeamCleanupToolResultSchema as TA,TeamCreateOutcomeInputSchema as q7,TeamCreateOutcomeToolResultSchema as hA,TeamFinalizeOutcomeInputSchema as b7,TeamFinalizeOutcomeToolResultSchema as DA,TeamListOutcomesInputSchema as w7,TeamListRunsInputSchema as C7,TeamMailboxMessageToolResultSchema as MA,TeamMissionLogInputSchema as E7,TeamMissionLogToolResultSchema as _A,TeamOutcomeFragmentToolResultSchema as S7,TeamOutcomeToolResultSchema as LA,TeamReadMailboxInputSchema as k7,TeamReviewOutcomeFragmentInputSchema as m7,TeamRunTaskInputSchema as I7,TeamRunTaskToolResultSchema as gW,TeamRunToolSummarySchema as vW,TeamSendMessageInputSchema as x7,TeamSendMessageToolResultSchema as zA,TeamShutdownTeammateInputSchema as g7,TeamSimpleAgentStatusToolResultSchema as v7,TeamSpawnTeammateInputSchema as u7,TeamStatusInputSchema as c7,TeamStatusToolResultSchema as OA,TeamTaskInputSchema as d7,TeamTaskToolResultSchema as x2,validateWithZod as b,zodToJsonSchema as Hf}from"@cline/shared";function r7(f,$){let J=f.replace(/\s+/g," ").trim();if(J.length<=$)return J;return`${J.slice(0,Math.max(0,$-3)).trimEnd()}...`}function K$(f,$){if(f===void 0)throw Error(`Missing required field: ${$}`);return f}function NA(f){let $=f.result;if(!$)return;return{textPreview:r7($.text,yA),iterations:$.iterations,finishReason:$.finishReason,durationMs:$.durationMs,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost}}}function k4(f){return f?.toISOString()}function uW(f){return{id:f.id,agentId:f.agentId,taskId:f.taskId,status:f.status,messagePreview:r7(f.message,FA),priority:f.priority,retryCount:f.retryCount,maxRetries:f.maxRetries,nextAttemptAt:k4(f.nextAttemptAt),continueConversation:f.continueConversation,startedAt:f.startedAt.toISOString(),endedAt:k4(f.endedAt),leaseOwner:f.leaseOwner,heartbeatAt:k4(f.heartbeatAt),lastProgressAt:k4(f.lastProgressAt),lastProgressMessage:f.lastProgressMessage,currentActivity:f.currentActivity,error:f.error,resultSummary:NA(f)}}function qA(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 Y1=["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 l7(f){let $=[];if(f.createBaseTools)$.push(...f.createBaseTools());$.push(...U$({runtime:f.runtime,requesterId:f.spec.agentId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!1})),f.runtime.spawnTeammate({agentId:f.spec.agentId,config:y$({kind:"teammate",prompt:f.spec.rolePrompt,role:f.spec.rolePrompt,configProvider:f.teammateConfigProvider,tools:$,maxIterations:f.spec.maxIterations,cwd:f.teammateConfigProvider.getRuntimeConfig().cwd})})}function B1(f){let $=f.leadAgentId??"lead",J=f.restoredFromPersistence===!0,W=U$({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;l7({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:Q}),H.push(Q.agentId)}return{tools:W,restoredFromPersistence:J,restoredTeammates:H}}function U$(f){let $=f.allowSpawn??!0,J=f.includeSpawnTool??!0,W=f.includeManagementTools??!0,H=[];if(J)H.push(Wf({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:Hf(u7),execute:async(Z)=>{let j=b(u7,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(l7({runtime:f.runtime,requesterId:f.requesterId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:P}),!W)f.onLeadToolsUnlocked?.(U$({...f,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return b(v7,{agentId:j.agentId,status:"spawned"})}}));if(!W)return H;H.push(Wf({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:Hf(g7),execute:async(Z)=>{let j=b(g7,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(v7,{agentId:j.agentId,status:"stopped"})}})),H.push(Wf({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:Hf(c7),execute:async(Z)=>{return b(c7,Z),b(OA,f.runtime.getSnapshot())}})),H.push(Wf({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:Hf(d7),execute:async(Z)=>{let j=b(d7,Z);switch(j.action){case"create":{let P=new Set(KA.create??[]),X=Object.entries(Z).filter(([Y,B])=>P.has(Y)&&B!=null).map(([Y])=>Y),V=f.runtime.createTask({title:K$(j.title,"title"),description:K$(j.description,"description"),dependsOn:j.dependsOn,assignee:j.assignee,createdBy:f.requesterId});return b(x2,{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(x2,{action:"list",tasks:f.runtime.listTaskItems({status:j.status,assignee:j.assignee})});case"claim":{let P=f.runtime.claimTask(K$(j.taskId,"taskId"),f.requesterId);return b(x2,{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(K$(j.taskId,"taskId"),f.requesterId,K$(j.summary,"summary"));return b(x2,{action:"complete",taskId:P.id,status:P.status})}case"block":{let P=f.runtime.blockTask(K$(j.taskId,"taskId"),f.requesterId,K$(j.reason,"reason"));return b(x2,{action:"block",taskId:P.id,status:P.status})}}}}));let Q=new Map;return H.push(Wf({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:Hf(I7),execute:async(Z)=>{let j=b(I7,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(gW,{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(gW,{...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(gW,{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}})),H.push(Wf({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:Hf(O7),execute:async(Z)=>{let j=b(O7,Z),P=f.runtime.cancelRun(j.runId,j.reason);return b(GA,{runId:P.id,status:P.status})}})),H.push(Wf({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:Hf(C7),execute:async(Z)=>b(vW.array(),f.runtime.listRuns(b(C7,Z)).map(uW))})),H.push(Wf({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:Hf(L7),timeoutMs:RA,execute:async(Z)=>{let j=b(L7,Z);if(j.runId){let V=await f.runtime.awaitRun(j.runId);return qA(V),b(vW,uW(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(vW.array(),P.map(uW))}})),H.push(Wf({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:Hf(x7),execute:async(Z)=>{let j=b(x7,Z),P=f.runtime.sendMessage(f.requesterId,j.toAgentId,j.subject,j.body,j.taskId??void 0);return b(zA,{id:P.id,toAgentId:P.toAgentId})}})),H.push(Wf({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:Hf(z7),execute:async(Z)=>{let j=b(z7,Z),P=f.runtime.broadcast(f.requesterId,j.subject,j.body,{taskId:j.taskId??void 0});return b(UA,{delivered:P.length})}})),H.push(Wf({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:Hf(k7),execute:async(Z)=>{let j=b(k7,Z);return b(MA.array(),f.runtime.listMailbox(f.requesterId,{unreadOnly:j.unreadOnly,markRead:!0}))}})),H.push(Wf({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:Hf(E7),execute:async(Z)=>{let j=b(E7,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(_A,{id:P.id})}})),H.push(Wf({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:Hf(N7),execute:async(Z)=>{if(b(N7,Z),f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return f.runtime.cleanup(),b(TA,{status:"cleaned"})}})),H.push(Wf({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:Hf(q7),execute:async(Z)=>{let j=b(q7,Z),P=f.runtime.createOutcome({title:j.title,requiredSections:j.requiredSections,createdBy:f.requesterId});return b(hA,{outcomeId:P.id,status:P.status,requiredSections:P.requiredSections})}})),H.push(Wf({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:Hf(_7),execute:async(Z)=>{let j=b(_7,Z),P=f.runtime.attachOutcomeFragment({outcomeId:j.outcomeId,section:j.section,sourceAgentId:f.requesterId,sourceRunId:j.sourceRunId||void 0,content:j.content});return b(S7,{fragmentId:P.id,status:P.status})}})),H.push(Wf({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:Hf(m7),execute:async(Z)=>{let j=b(m7,Z),P=f.runtime.reviewOutcomeFragment({fragmentId:j.fragmentId,reviewedBy:f.requesterId,approved:j.approved});return b(S7,{fragmentId:P.id,status:P.status})}})),H.push(Wf({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:Hf(b7),execute:async(Z)=>{let j=b(b7,Z),P=f.runtime.finalizeOutcome(j.outcomeId);return b(DA,{outcomeId:P.id,status:P.status})}})),H.push(Wf({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:Hf(w7),execute:async(Z)=>{return b(w7,Z),b(LA.array(),f.runtime.listOutcomes())}})),H}function m4(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 I4(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var bA=[{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:I0({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...Y1]}],wA={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function CA(f){return f==="plan"||f==="yolo"?f:"act"}function i7(f){let $=CA(f.mode),J=Nf[B0({mode:$})],W=j1(f.providerId??"",f.modelId??"",$,Z1);return{mode:$,flags:{...J,...W,...typeof f.enableSpawnAgent==="boolean"?{enableSpawnAgent:f.enableSpawnAgent}:{},...typeof f.enableAgentTeams==="boolean"?{enableAgentTeams:f.enableAgentTeams}:{}}}}function p7(f,$){if($.disabledToolIds?.has(f))return!1;let{flags:J}=i7($);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=wA[f];return W?J[W]===!0:!1}function EA(f,$){if(f.id==="editor"){let{flags:J}=i7($),W=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...f,defaultEnabled:p7(f.id,$),headlessToolNames:[W?"apply_patch":"editor"]}}return{...f,defaultEnabled:p7(f.id,$)}}function G$(f={}){return bA.map(($)=>EA($,f))}function x4(f={}){return G$(f).filter(($)=>$.defaultEnabled).map(($)=>$.id)}function g4(f){if(!f.enabled)return new Set;let $=G$(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 g2(f,$={}){return G$($).filter((J)=>f.has(J.id)).flatMap((J)=>J.headlessToolNames)}function v4(f,$={}){return g2(f,$)}function T$(f={}){let{executorOptions:$={},executors:J,...W}=f,H={...Q1($),...J??{}};return S0({...W,executors:H})}import{mkdirSync as gA,writeFileSync as vA}from"node:fs";import{dirname as uA}from"node:path";import{normalizeUserInput as cA}from"@cline/shared";import{nanoid as dA}from"nanoid";var a7={};N(a7,{sanitizeSessionToken:()=>h$,parseTeamTaskSubSessionId:()=>R1,parseSubSessionId:()=>u2,makeTeamTaskSubSessionId:()=>v2,makeSubSessionId:()=>A1,deriveSubsessionStatus:()=>c2});import{nanoid as mA}from"nanoid";function h$(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function A1(f,$){let J=h$(f),W=h$($),H=`${J}__${W}`;return H.length>180?H.slice(0,180):H}function v2(f,$){let J=h$(f),W=h$($);return`${J}__teamtask__${W}__${mA(6)}`}function R1(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 u2(f){if(R1(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 c2(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 i}from"zod";var t7={};N(t7,{SessionSource:()=>Pf,SESSION_STATUSES:()=>d2});import{SESSION_STATUS_VALUES as IA}from"@cline/shared";var d2=IA,Pf={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 xA=i.enum(d2),Uf=i.object({version:i.literal(1),session_id:i.string().min(1),source:i.string().min(1),pid:i.number().int(),started_at:i.string().min(1),ended_at:i.string().min(1).optional(),exit_code:i.number().int().nullable().optional(),status:xA,interactive:i.boolean(),provider:i.string().min(1),model:i.string().min(1),cwd:i.string().min(1),workspace_root:i.string().min(1),team_name:i.string().min(1).optional(),enable_tools:i.boolean(),enable_spawn:i.boolean(),enable_teams:i.boolean(),prompt:i.string().optional(),metadata:i.record(i.string(),i.unknown()).optional(),messages_path:i.string().min(1).optional()});function s7(f){if(!f)return!1;return Object.values(f).some(($)=>typeof $==="function")}function dW(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 o7(f){return JSON.stringify(f,($,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function A0(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function cW(f,$){let J={...f};J.id=A0(J.id)??dA();let W=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,H={id:A0(W?.id)??A0(J.modelId)??A0($?.id),provider:A0(W?.provider)??A0(J.providerId)??A0($?.provider),family:A0(W?.family)??A0($?.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 u4(f){return f.map(($)=>cW($))}function c4(f,$,J=[]){let W=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 cW(Y)}),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((P)=>P.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 P=W[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}}W[j]={...cW(P,{id:$.model.id,provider:$.model.provider,family:$.model.info?.family}),...X?{metrics:X}:{},ts:P.ts??$.endedAt.getTime()}}return W}function r2(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 rA=120;function D$(f){let $=f?.trim();return $?$.slice(0,rA):void 0}function rW(f){let $=cA(f??"").trim();if(!$)return;return D$($.split(`
|
|
135
|
-
`)[0]?.trim())}function
|
|
136
|
-
`,"utf8")}function fQ(f,$){return Uf.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 $Q(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}}Gf();var ZQ={};N(ZQ,{summarizeUsageFromMessages:()=>a2,getCurrentContextSize:()=>iW,createInitialAccumulatedUsage:()=>u0,accumulateUsageTotals:()=>c0});function u0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function c0(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 y1(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function a2(f){let $=u0();for(let J of f){let W=J.metrics;if(!W)continue;$=c0($,{inputTokens:y1(W.inputTokens),outputTokens:y1(W.outputTokens),cacheReadTokens:y1(W.cacheReadTokens),cacheWriteTokens:y1(W.cacheWriteTokens),totalCost:y1(W.cost)})}return $}function iW(f){for(let $=f.length-1;$>=0;$-=1){let J=f[$];if(J?.role!=="assistant")continue;let W=y1(J.metrics?.inputTokens);return W>0?W:void 0}return}function iA(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 U0(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 aW(f,$,J){let{sessionId:W,config:H,liveSession:Q,emit:Z}=f,j=H.telemetry,P=Q?.runtime.teamRuntime,X=J?.isPrimaryAgentEvent??!0,V=nW($),Y=U0({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=iA($.input);if(B)s4(j,{ulid:W,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:H.providerId,modelId:H.modelId,...Y})}if($.type==="content_end"&&$.contentType==="tool"){let B=$.toolName??"unknown",A=!$.error;if(t4(j,{ulid:W,tool:B,autoApproved:void 0,success:A,modelId:H.modelId,provider:H.providerId,...Y}),!A&&(B==="editor"||B==="apply_patch"))o4(j,{ulid:W,modelId:H.modelId,provider:H.providerId,errorType:$.error,...Y})}if($.type==="notice"&&$.reason==="api_error")i2(j,{ulid:W,model:H.modelId,provider:H.providerId,errorMessage:$.message,...Y});if($.type==="error")i2(j,{ulid:W,model:H.modelId,provider:H.providerId,errorMessage:$.error?.message??"unknown error",...Y});if($.type==="usage"&&X&&Q?.turnUsageBaseline)f.usageBySession.set(W,c0(Q.turnUsageBaseline,{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost})),F1(j,{ulid:W,provider:H.providerId,model:H.modelId,source:"assistant",mode:H.mode,...Y}),n4(j,{ulid:W,tokensIn:$.inputTokens,tokensOut:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost,model:H.modelId,...Y});if($.type==="iteration_end"&&X)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??(X?"lead":void 0):void 0}}),Z({type:"chunk",payload:{sessionId:W,stream:"agent",chunk:o7($),ts:Date.now()}})}function d0(f){return f.workspaceRoot??f.cwd}import{hasRuntimeConfigExtension as Hy}from"@cline/shared";function jQ(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 nA(f){let J=new TextEncoder().encode(f),W=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(W)}function aA(f=32){let $=new Uint8Array(f);return crypto.getRandomValues($),jQ($)}async function H6(){let f=aA(),$=jQ(await nA(f));return{verifier:f,challenge:$}}function Q6(f){return f.endsWith("/")?f.slice(0,-1):f}function M$(f,$){return new URL($,`${Q6(f)}/`).toString()}function K1(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 tA(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 Rf(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=tA(H);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function U1(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 _$(f,$){return Date.now()>=f.expires-$}async function G1(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 K1($,f.parseOptions);if(await W,J)throw J;if($)return K1($,f.parseOptions);return{}}G0();import{existsSync as CR}from"node:fs";import{discoverPluginModulePaths as ER,resolveConfiguredPluginModulePaths as SR,resolvePluginConfigSearchPaths as kR}from"@cline/shared/storage";import{resolve as BR}from"node:path";import{normalizePluginManifest as AR}from"@cline/shared";import{existsSync as r0,readFileSync as eW}from"node:fs";import{builtinModules as $R,createRequire as yQ}from"node:module";import{dirname as Y6,extname as KQ,isAbsolute as JR,resolve as Ff}from"node:path";import{fileURLToPath as UQ}from"node:url";import{PLUGIN_FILE_EXTENSIONS as WR}from"@cline/shared";var HR=Y6(UQ(import.meta.url)),GQ=yQ(import.meta.url),QR=Ff(HR,"..","..","..","..",".."),sW=ZR(QR),f5=new Set($R.flatMap((f)=>[f,f.replace(/^node:/,"")])),V6=new Set(WR);function ZR(f){let $={},J={"@cline/agents":Ff(f,"packages/agents/src/index.ts"),"@cline/core":Ff(f,"packages/core/src/index.ts"),"@cline/llms":Ff(f,"packages/llms/src/index.ts"),"@cline/shared":Ff(f,"packages/shared/src/index.ts"),"@cline/shared/storage":Ff(f,"packages/shared/src/storage/index.ts"),"@cline/shared/db":Ff(f,"packages/shared/src/db/index.ts")};for(let[W,H]of Object.entries(J))if(r0(H))$[W]=H;return $}function TQ(f){return!(f.startsWith(".")||f.startsWith("/")||f.startsWith("file:")||f.startsWith("data:")||f.startsWith("http:")||f.startsWith("https:"))}function oW(f){if(f.startsWith("@")){let[$,J]=f.split("/",3);return J?`${$}/${J}`:f}return f.split("/",1)[0]??f}function hQ(f,$){let J=oW($),W=Y6(f);while(!0){let H=Ff(W,"node_modules",J);if(r0(H)||r0(Ff(H,"package.json")))return!0;let Q=Ff(W,"..");if(Q===W)return!1;W=Q}}function jR(f){try{return GQ.resolve(f),!0}catch{return!1}}function PR(f){try{return GQ.resolve(f)}catch{return null}}function XR(f){let J=Y6(f);for(let W=0;W<4;W++){let H=Ff(J,"package.json");if(r0(H))try{let Z=JSON.parse(eW(H,"utf8"));return Z!=null&&typeof Z==="object"&&"cline"in Z}catch{return!1}let Q=Ff(J,"..");if(Q===J)return!1;J=Q}return!1}function VR(f,$){let J=$.startsWith("file:")?UQ($):JR($)?$:Ff(Y6(f),$);if(r0(J)&&V6.has(KQ(J)))return J;for(let W of V6){let H=`${J}${W}`;if(r0(H))return H}for(let W of V6){let H=Ff(J,`index${W}`);if(r0(H))return H}return null}function DQ(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 MQ(f,$,J=new Set){if(J.has(f)||!r0(f))return;if(J.add(f),!V6.has(KQ(f)))return;let W=eW(f,"utf8");for(let H of DQ(W)){if(H.startsWith("node:")||f5.has(H))continue;if(TQ(H)){if(Object.hasOwn(sW,H)||Object.hasOwn(sW,oW(H))||hQ(f,H)||$&&jR(H))continue;throw Error(`Cannot find module '${oW(H)}'`)}let Q=VR(f,H);if(Q)MQ(Q,$,J)}}function YR(f,$){let J=yQ(f),W={};for(let[H,Q]of Object.entries(sW)){try{J.resolve(H);continue}catch{}W[H]=Q}if($){let H=eW(f,"utf8");for(let Q of DQ(H)){if(!TQ(Q)||Q.startsWith("node:")||f5.has(Q)||Object.hasOwn(W,Q)||hQ(f,Q))continue;let Z=PR(Q);if(Z)W[Q]=Z}}return W}async function _Q(f,$={}){let J=!XR(f);MQ(f,J);let W=YR(f,J),H=await import("jiti"),Q=typeof H==="function"?H:typeof H.default==="function"?H.default:void 0;if(!Q)throw Error("Unable to load jiti");return await Q(f,{alias:W,cache:$.useCache,requireCache:$.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...f5],transformModules:Object.keys(W)}).import(f,{})}function LQ(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 zQ(f){return typeof f==="object"&&f!==null}function $5(f){return Array.isArray(f)&&f.every(($)=>typeof $==="string")}function RR(f,$){if(!zQ(f.manifest))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);if(!$5(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")&&!$5(f.manifest.providerIds))throw Error(`Invalid plugin module at ${$}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn(f.manifest,"modelIds")&&!$5(f.manifest.modelIds))throw Error(`Invalid plugin module at ${$}: manifest.modelIds must be a string array when provided`)}function FR(f,$){if(!zQ(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"`);RR(f,$)}async function e2(f,$={}){let J=BR($.cwd??process.cwd(),f),W=await _Q(J,{useCache:$.useCache}),H=$.exportName??"plugin",Q=W.default??W[H];FR(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:AR(Z.manifest),setup:P}}async function B6(f,$={}){return(await T0(f,$)).plugins}async function T0(f,$={}){let J=[],W=[],H=new Map,Q=0;for(let Z of f)try{let j=await e2(Z,$);if(!LQ(j.manifest,$))continue;let P=H.get(j.name);if(P)W.push({type:"duplicate_plugin_override",pluginName:j.name,pluginPath:Z,overriddenPluginPath:P.pluginPath,message:`Plugin "${j.name}" from ${Z} overrides ${P.pluginPath}`});H.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:[...H.values()].sort((Z,j)=>Z.order-j.order).map((Z)=>Z.plugin),failures:J,warnings:W}}import{existsSync as TR}from"node:fs";import{createRequire as hR}from"node:module";import{dirname as DR,join as A6}from"node:path";import{fileURLToPath as MR}from"node:url";var wQ={};N(wQ,{resolveSubprocessRuntimeExecutable:()=>J5,buildSubprocessSandboxCommand:()=>bQ,SubprocessSandbox:()=>T1,CLINE_JS_RUNTIME_PATH_ENV:()=>qQ});import{spawn as yR}from"node:child_process";import{basename as KR}from"node:path";import{augmentNodeCommandForDebug as UR,withResolvedClineBuildEnv as GR}from"@cline/shared";function OQ(f){if(f instanceof Error)return f;return Error(String(f))}var qQ="CLINE_JS_RUNTIME_PATH";function NQ(f){let $=f?.trim();if(!$)return!1;let J=KR($).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function J5(f={}){let $=f.env??process.env,J=f.runtimeExecutable?.trim()||$[qQ]?.trim();if(J)return J;let W=f.execPath?.trim()||process.execPath;if(NQ(W))return W;for(let H of[$.BUN_EXEC_PATH,$.npm_node_execpath,$.NODE]){let Q=H?.trim();if(Q&&NQ(Q))return Q}return"node"}function bQ(f,$={}){let J=J5({env:$.env,execPath:$.execPath,runtimeExecutable:$.runtimeExecutable});return UR([J,...f],{env:$.env,execArgv:$.execArgv,debugRole:$.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class T1{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??""],$=bQ(f,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=yR($[0]??J5(this.options),$.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:GR(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: ${OQ(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 P={resolve:(X)=>Z(X),reject:j};if((J.timeoutMs??0)>0)P.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,P),W.send(Q,(X)=>{if(!X)return;let V=this.clearPendingRequest(H);if(!V)return;V.reject(Error(`${this.processLabel} failed to send call "${f}": ${OQ(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 _R(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 R6(f){return(f instanceof Error?f.message:String(f)).includes("Unknown sandbox plugin id:")}function LR(){let f=DR(MR(import.meta.url)),$=hR(import.meta.url),J=[A6(f,"plugin-sandbox-bootstrap.js"),A6(f,"extensions","plugin-sandbox-bootstrap.js"),A6(f,"agents","plugin-sandbox-bootstrap.js")];for(let Q of J)if(TR(Q))return{file:Q};let W=A6(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(`
|
|
137
|
-
`)}}var
|
|
138
|
-
`).filter(Boolean);await Promise.allSettled(H.map((Q)=>
|
|
139
|
-
`),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
|
|
140
|
-
`).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
|
|
141
|
-
`,Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??
|
|
133
|
+
${W}`;return J||W}function zV(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 c0{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 x5;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??_V,this.conversation=new S5(f.initialMessages),this.messageBuilder=new C5,this.contributionRegistry=MV({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 m5({maxConsecutiveMistakes:J,onLimitReached:f.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,Z,j)=>NV(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 I5(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 hV($);if(J)f.push(J)}return OV(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 wV(J,f.userImages,f.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let W=await this.composeSystemPrompt(),H=TQ(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=CQ(this.config),A=Array.from(Z.values()),P=v4(this.conversation.getMessages()),B=qQ({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=P1(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=zV([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=P1(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:v4(Z.messages)}:{},...Z.systemPrompt!==void 0?{systemPrompt:Z.systemPrompt}:{}}}}async prepareMessagesForModelRequest(f){let $=await this.prepareProviderMessagesForApi(OQ(f));return v4($)}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?LV(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(P1(f));return}if($.length===0)return;let J=new Set(this.conversation.getMessages().map((H)=>H.id).filter((H)=>typeof H==="string")),W=P1($).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":qV($),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=$?P1($.messages):this.conversation.getMessages(),P=CQ(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 NV(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 qV(f){if(!f)return"error";switch(f.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function wV(f,$,J,W){let{buildInitialUserContent:H}=await Promise.resolve().then(() => bQ);return H(f,$,J,W)}function CQ(f){if(f.knownModels?.[f.modelId])return f.knownModels[f.modelId];let $=w5(f);if($?.[f.modelId])return $[f.modelId];return}import{buildClineSystemPrompt as EQ}from"@cline/shared";function SQ(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return EQ({ide:$.clineIdeName?.trim()||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,rules:`# Team Teammate Role
|
|
134
|
+
${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function kQ(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return EQ({ide:$.clineIdeName||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,overridePrompt:J,metadata:$.workspaceMetadata,platform:$.clinePlatform})}function B1(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 T$(f){let $=f.configProvider.getRuntimeConfig(),J=f.kind==="teammate"?SQ(f.prompt,$):kQ(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 Y1(f){let $=T$(f),J=new c0($);if($.onEvent)J.subscribeEvents($.onEvent);return J}var EV=g5.object({systemPrompt:g5.string().describe("System prompt defining the sub-agent's behavior"),task:g5.string().describe("Task for the sub-agent to complete")});function d0(f){return bV({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:CV(EV),execute:async($,J)=>{let W=f.createSubAgentTools?await f.createSubAgentTools($,J):f.subAgentTools??[],H=Y1({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 SV,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as kV,TEAM_RUN_TEXT_PREVIEW_LIMIT as IV,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as mV,TeamAttachOutcomeFragmentInputSchema as IQ,TeamAwaitRunsInputSchema as mQ,TeamBroadcastInputSchema as xQ,TeamBroadcastToolResultSchema as xV,TeamCancelRunInputSchema as gQ,TeamCancelRunToolResultSchema as gV,TeamCleanupInputSchema as vQ,TeamCleanupToolResultSchema as vV,TeamCreateOutcomeInputSchema as uQ,TeamCreateOutcomeToolResultSchema as uV,TeamFinalizeOutcomeInputSchema as cQ,TeamFinalizeOutcomeToolResultSchema as cV,TeamListOutcomesInputSchema as dQ,TeamListRunsInputSchema as rQ,TeamMailboxMessageToolResultSchema as dV,TeamMissionLogInputSchema as lQ,TeamMissionLogToolResultSchema as rV,TeamOutcomeFragmentToolResultSchema as pQ,TeamOutcomeToolResultSchema as lV,TeamReadMailboxInputSchema as iQ,TeamReviewOutcomeFragmentInputSchema as nQ,TeamRunTaskInputSchema as aQ,TeamRunTaskToolResultSchema as v5,TeamRunToolSummarySchema as u5,TeamSendMessageInputSchema as tQ,TeamSendMessageToolResultSchema as pV,TeamShutdownTeammateInputSchema as sQ,TeamSimpleAgentStatusToolResultSchema as oQ,TeamSpawnTeammateInputSchema as eQ,TeamStatusInputSchema as f7,TeamStatusToolResultSchema as iV,TeamTaskInputSchema as $7,TeamTaskToolResultSchema as v2,validateWithZod as b,zodToJsonSchema as jf}from"@cline/shared";function J7(f,$){let J=f.replace(/\s+/g," ").trim();if(J.length<=$)return J;return`${J.slice(0,Math.max(0,$-3)).trimEnd()}...`}function D$(f,$){if(f===void 0)throw Error(`Missing required field: ${$}`);return f}function nV(f){let $=f.result;if(!$)return;return{textPreview:J7($.text,IV),iterations:$.iterations,finishReason:$.finishReason,durationMs:$.durationMs,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost}}}function u4(f){return f?.toISOString()}function c5(f){return{id:f.id,agentId:f.agentId,taskId:f.taskId,status:f.status,messagePreview:J7(f.message,kV),priority:f.priority,retryCount:f.retryCount,maxRetries:f.maxRetries,nextAttemptAt:u4(f.nextAttemptAt),continueConversation:f.continueConversation,startedAt:f.startedAt.toISOString(),endedAt:u4(f.endedAt),leaseOwner:f.leaseOwner,heartbeatAt:u4(f.heartbeatAt),lastProgressAt:u4(f.lastProgressAt),lastProgressMessage:f.lastProgressMessage,currentActivity:f.currentActivity,error:f.error,resultSummary:nV(f)}}function aV(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 V1=["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 W7(f){let $=[];if(f.createBaseTools)$.push(...f.createBaseTools());$.push(..._$({runtime:f.runtime,requesterId:f.spec.agentId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!1})),f.runtime.spawnTeammate({agentId:f.spec.agentId,config:T$({kind:"teammate",prompt:f.spec.rolePrompt,role:f.spec.rolePrompt,configProvider:f.teammateConfigProvider,tools:$,maxIterations:f.spec.maxIterations,cwd:f.teammateConfigProvider.getRuntimeConfig().cwd})})}function R1(f){let $=f.leadAgentId??"lead",J=f.restoredFromPersistence===!0,W=_$({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;W7({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:Q}),H.push(Q.agentId)}return{tools:W,restoredFromPersistence:J,restoredTeammates:H}}function _$(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(eQ),execute:async(Z)=>{let j=b(eQ,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(W7({runtime:f.runtime,requesterId:f.requesterId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:X}),!W)f.onLeadToolsUnlocked?.(_$({...f,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return b(oQ,{agentId:j.agentId,status:"spawned"})}}));if(!W)return H;H.push(Zf({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:jf(sQ),execute:async(Z)=>{let j=b(sQ,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(oQ,{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(f7),execute:async(Z)=>{return b(f7,Z),b(iV,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($7),execute:async(Z)=>{let j=b($7,Z);switch(j.action){case"create":{let X=new Set(mV.create??[]),A=Object.entries(Z).filter(([B,Y])=>X.has(B)&&Y!=null).map(([B])=>B),P=f.runtime.createTask({title:D$(j.title,"title"),description:D$(j.description,"description"),dependsOn:j.dependsOn,assignee:j.assignee,createdBy:f.requesterId});return b(v2,{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(v2,{action:"list",tasks:f.runtime.listTaskItems({status:j.status,assignee:j.assignee})});case"claim":{let X=f.runtime.claimTask(D$(j.taskId,"taskId"),f.requesterId);return b(v2,{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(D$(j.taskId,"taskId"),f.requesterId,D$(j.summary,"summary"));return b(v2,{action:"complete",taskId:X.id,status:X.status})}case"block":{let X=f.runtime.blockTask(D$(j.taskId,"taskId"),f.requesterId,D$(j.reason,"reason"));return b(v2,{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(aQ),execute:async(Z)=>{let j=b(aQ,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(v5,{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(v5,{...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(v5,{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(gQ),execute:async(Z)=>{let j=b(gQ,Z),X=f.runtime.cancelRun(j.runId,j.reason);return b(gV,{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(rQ),execute:async(Z)=>b(u5.array(),f.runtime.listRuns(b(rQ,Z)).map(c5))})),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(mQ),timeoutMs:SV,execute:async(Z)=>{let j=b(mQ,Z);if(j.runId){let P=await f.runtime.awaitRun(j.runId);return aV(P),b(u5,c5(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(u5.array(),X.map(c5))}})),H.push(Zf({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:jf(tQ),execute:async(Z)=>{let j=b(tQ,Z),X=f.runtime.sendMessage(f.requesterId,j.toAgentId,j.subject,j.body,j.taskId??void 0);return b(pV,{id:X.id,toAgentId:X.toAgentId})}})),H.push(Zf({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:jf(xQ),execute:async(Z)=>{let j=b(xQ,Z),X=f.runtime.broadcast(f.requesterId,j.subject,j.body,{taskId:j.taskId??void 0});return b(xV,{delivered:X.length})}})),H.push(Zf({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:jf(iQ),execute:async(Z)=>{let j=b(iQ,Z);return b(dV.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(lQ),execute:async(Z)=>{let j=b(lQ,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(rV,{id:X.id})}})),H.push(Zf({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:jf(vQ),execute:async(Z)=>{if(b(vQ,Z),f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return f.runtime.cleanup(),b(vV,{status:"cleaned"})}})),H.push(Zf({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:jf(uQ),execute:async(Z)=>{let j=b(uQ,Z),X=f.runtime.createOutcome({title:j.title,requiredSections:j.requiredSections,createdBy:f.requesterId});return b(uV,{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(IQ),execute:async(Z)=>{let j=b(IQ,Z),X=f.runtime.attachOutcomeFragment({outcomeId:j.outcomeId,section:j.section,sourceAgentId:f.requesterId,sourceRunId:j.sourceRunId||void 0,content:j.content});return b(pQ,{fragmentId:X.id,status:X.status})}})),H.push(Zf({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:jf(nQ),execute:async(Z)=>{let j=b(nQ,Z),X=f.runtime.reviewOutcomeFragment({fragmentId:j.fragmentId,reviewedBy:f.requesterId,approved:j.approved});return b(pQ,{fragmentId:X.id,status:X.status})}})),H.push(Zf({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:jf(cQ),execute:async(Z)=>{let j=b(cQ,Z),X=f.runtime.finalizeOutcome(j.outcomeId);return b(cV,{outcomeId:X.id,status:X.status})}})),H.push(Zf({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:jf(dQ),execute:async(Z)=>{return b(dQ,Z),b(lV.array(),f.runtime.listOutcomes())}})),H}function c4(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 H7(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var tV=[{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:d0({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...V1]}],sV={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function oV(f){return f==="plan"||f==="yolo"?f:"act"}function Z7(f){let $=oV(f.mode),J=Ef[K0({mode:$})],W=A1(f.providerId??"",f.modelId??"",$,X1);return{mode:$,flags:{...J,...W,...typeof f.enableSpawnAgent==="boolean"?{enableSpawnAgent:f.enableSpawnAgent}:{},...typeof f.enableAgentTeams==="boolean"?{enableAgentTeams:f.enableAgentTeams}:{}}}}function Q7(f,$){if($.disabledToolIds?.has(f))return!1;let{flags:J}=Z7($);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=sV[f];return W?J[W]===!0:!1}function eV(f,$){if(f.id==="editor"){let{flags:J}=Z7($),W=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...f,defaultEnabled:Q7(f.id,$),headlessToolNames:[W?"apply_patch":"editor"]}}return{...f,defaultEnabled:Q7(f.id,$)}}function M$(f={}){return tV.map(($)=>eV($,f))}function d4(f={}){return M$(f).filter(($)=>$.defaultEnabled).map(($)=>$.id)}function r4(f){if(!f.enabled)return new Set;let $=M$(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 u2(f,$={}){return M$($).filter((J)=>f.has(J.id)).flatMap((J)=>J.headlessToolNames)}function l4(f,$={}){return u2(f,$)}function L$(f={}){let{executorOptions:$={},executors:J,...W}=f,H={...j1($),...J??{}};return v0({...W,executors:H})}import{mkdirSync as QR,writeFileSync as ZR}from"node:fs";import{dirname as jR}from"node:path";import{normalizeUserInput as XR}from"@cline/shared";import{nanoid as AR}from"nanoid";var X7={};N(X7,{sanitizeSessionToken:()=>h$,parseTeamTaskSubSessionId:()=>K1,parseSubSessionId:()=>d2,makeTeamTaskSubSessionId:()=>c2,makeSubSessionId:()=>F1,deriveSubsessionStatus:()=>r2});import{nanoid as JR}from"nanoid";function h$(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function F1(f,$){let J=h$(f),W=h$($),H=`${J}__${W}`;return H.length>180?H.slice(0,180):H}function c2(f,$){let J=h$(f),W=h$($);return`${J}__teamtask__${W}__${JR(6)}`}function K1(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 d2(f){if(K1(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 r2(f){switch(f.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let $=String(f.reason??"").toLowerCase();if($.includes("cancel")||$.includes("abort")||$.includes("interrupt"))return"cancelled";if($.includes("fail")||$.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as a}from"zod";var A7={};N(A7,{SessionSource:()=>Vf,SESSION_STATUSES:()=>l2});import{SESSION_STATUS_VALUES as WR}from"@cline/shared";var l2=WR,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 HR=a.enum(l2),Mf=a.object({version:a.literal(1),session_id:a.string().min(1),source:a.string().min(1),pid:a.number().int(),started_at:a.string().min(1),ended_at:a.string().min(1).optional(),exit_code:a.number().int().nullable().optional(),status:HR,interactive:a.boolean(),provider:a.string().min(1),model:a.string().min(1),cwd:a.string().min(1),workspace_root:a.string().min(1),team_name:a.string().min(1).optional(),enable_tools:a.boolean(),enable_spawn:a.boolean(),enable_teams:a.boolean(),prompt:a.string().optional(),metadata:a.record(a.string(),a.unknown()).optional(),messages_path:a.string().min(1).optional()});function P7(f){if(!f)return!1;return Object.values(f).some(($)=>typeof $==="function")}function r5(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 B7(f){return JSON.stringify(f,($,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function y0(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function d5(f,$){let J={...f};J.id=y0(J.id)??AR();let W=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,H={id:y0(W?.id)??y0(J.modelId)??y0($?.id),provider:y0(W?.provider)??y0(J.providerId)??y0($?.provider),family:y0(W?.family)??y0($?.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 p4(f){return f.map(($)=>d5($))}function i4(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 d5(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]={...d5(X,{id:$.model.id,provider:$.model.provider,family:$.model.info?.family}),...A?{metrics:A}:{},ts:X.ts??$.endedAt.getTime()}}return W}function p2(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 PR=120;function O$(f){let $=f?.trim();return $?$.slice(0,PR):void 0}function l5(f){let $=XR(f??"").trim();if(!$)return;return O$($.split(`
|
|
135
|
+
`)[0]?.trim())}function r0(f){if(!f)return;let $={...f},J=O$(typeof $.title==="string"?$.title:void 0);if(J)$.title=J;else delete $.title;return Object.keys($).length>0?$:void 0}function i2(f){let $=r0(f.metadata)??{},J=f.title!==void 0?O$(f.title):l5(f.prompt);if(J)$.title=J;return Object.keys($).length>0?$:void 0}function p5(f){let $=K1(f);if($)return{agent:"teammate",sessionId:$.rootSessionId,taskType:"team"};let J=d2(f);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:f}}function i5(f){return{version:1,updated_at:f.updatedAt,agent:f.context.agent,sessionId:f.context.sessionId,...f.context.taskType?{taskType:f.context.taskType}:{},messages:p4(f.messages),...f.systemPrompt?{system_prompt:f.systemPrompt}:{}}}function Y7(f,$,J){QR(jR(f),{recursive:!0}),ZR(f,`${JSON.stringify(i5({updatedAt:$,context:J,messages:[]}),null,2)}
|
|
136
|
+
`,"utf8")}function V7(f,$){return Mf.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 R7(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}}Lf();var G7={};N(G7,{summarizeUsageFromMessages:()=>G1,sumUsageTotals:()=>s2,getCurrentContextSize:()=>n5,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 s2(f){let $=Pf();for(let J of f)$=Xf($,J);return $}function U1(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function G1(f){let $=Pf();for(let J of f){let W=J.metrics;if(!W)continue;$=Xf($,{inputTokens:U1(W.inputTokens),outputTokens:U1(W.outputTokens),cacheReadTokens:U1(W.cacheReadTokens),cacheWriteTokens:U1(W.cacheWriteTokens),totalCost:U1(W.cost)})}return $}function n5(f){for(let $=f.length-1;$>=0;$-=1){let J=f[$];if(J?.role!=="assistant")continue;let W=U1(J.metrics?.inputTokens);return W>0?W:void 0}return}function VR(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 a5(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 _0(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 RR(f){return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost}}function FR(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 t5(f,$,J){let{sessionId:W,config:H,liveSession:Q,emit:Z}=f,j=H.telemetry,X=Q?.runtime.teamRuntime,A=J?.isPrimaryAgentEvent??!0,P=a5($),B=_0({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=VR($.input);if(Y)J6(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($6(j,{ulid:W,tool:Y,autoApproved:void 0,success:V,modelId:H.modelId,provider:H.providerId,...B}),!V&&(Y==="editor"||Y==="apply_patch"))W6(j,{ulid:W,modelId:H.modelId,provider:H.providerId,errorType:$.error,...B})}if($.type==="notice"&&$.reason==="api_error")a2(j,{ulid:W,model:H.modelId,provider:H.providerId,errorMessage:$.message,...B});if($.type==="error")a2(j,{ulid:W,model:H.modelId,provider:H.providerId,errorMessage:$.error?.message??"unknown error",...B});if($.type==="usage"&&Q?.turnUsageBaseline){let Y=RR($);if(A){Q.turnPrimaryUsage=Xf(Q.turnPrimaryUsage??Pf(),Y);let R=Xf(Q.turnUsageBaseline,Q.turnPrimaryUsage);f.usageBySession.set(W,R),y1(j,{ulid:W,provider:H.providerId,model:H.modelId,source:"assistant",mode:H.mode,...B}),e4(j,{ulid:W,tokensIn:$.inputTokens,tokensOut:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost,model:H.modelId,...B})}else{let R=FR({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(),s2(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:B7($),ts:Date.now()}})}function i0(f){return f.workspaceRoot??f.cwd}import{hasRuntimeConfigExtension as EK}from"@cline/shared";function T7(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 KR(f){let J=new TextEncoder().encode(f),W=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(W)}function yR(f=32){let $=new Uint8Array(f);return crypto.getRandomValues($),T7($)}async function A6(){let f=yR(),$=T7(await KR(f));return{verifier:f,challenge:$}}function P6(f){return f.endsWith("/")?f.slice(0,-1):f}function z$(f,$){return new URL($,`${P6(f)}/`).toString()}function T1(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 UR(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 Rf(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=UR(H);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function D1(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 N$(f,$){return Date.now()>=f.expires-$}async function _1(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 T1($,f.parseOptions);if(await W,J)throw J;if($)return T1($,f.parseOptions);return{}}M0();import{existsSync as HF}from"node:fs";import{discoverPluginModulePaths as QF,resolveConfiguredPluginModulePaths as ZF,resolvePluginConfigSearchPaths as jF}from"@cline/shared/storage";import{resolve as xR}from"node:path";import{normalizePluginManifest as gR}from"@cline/shared";import{existsSync as Tf,readFileSync as L1}from"node:fs";import{builtinModules as MR,createRequire as w7}from"node:module";import{dirname as J8,extname as $W,isAbsolute as LR,resolve as d}from"node:path";import{fileURLToPath as b7}from"node:url";import{PLUGIN_FILE_EXTENSIONS as hR}from"@cline/shared";var C7=J8(b7(import.meta.url)),OR=w7(import.meta.url),zR=d(C7,"..","..","..","..",".."),o5=wR(zR),NR=["@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"],JW=new Set(MR.flatMap((f)=>[f,f.replace(/^node:/,"")])),$8=new Set(hR),qR=["development","node","import","require","default"];function wR(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(L1(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=bR(H,X);if(!A)continue;let P=j==="."?Z.name:`${Z.name}/${j.replace(/^\.\//,"")}`;$[P]=A}}catch{}}return $}function bR(f,$){let J=WW($);if(!J)return null;let W=E7(f,J);for(let H of W)if(Tf(H))return H;return null}function WW(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 qR){let H=WW(J[W],$);if(H)return H}return null}function E7(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 CR(f){return Object.fromEntries(Object.entries(f).sort(([$],[J])=>J.length-$.length))}function F6(f){return!(f.startsWith(".")||f.startsWith("/")||f.startsWith("file:")||f.startsWith("data:")||f.startsWith("http:")||f.startsWith("https:"))}function M1(f){if(f.startsWith("@")){let[$,J]=f.split("/",3);return J?`${$}/${J}`:f}return f.split("/",1)[0]??f}function ER(f){let $=M1(f);if(f===$)return".";return`.${f.slice($.length)}`}function S7(f){return M1(f).startsWith("@cline/")}function e5(f,$){let J=M1($),W=J8(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 q7(f){return fW(f)!==null}function fW(f){try{return OR.resolve(f)}catch{}return SR(f)}function SR(f){let $=M1(f),J=kR($);if(!J)return null;let W=d(J,"package.json");try{let H=JSON.parse(L1(W,"utf8")),Q=ER(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=WW(Z)??(Q==="."&&typeof H.main==="string"?H.main:null);if(!j)return null;let X=d(J,j),A=[X,...E7(J,j).filter((P)=>P!==X)];for(let P of A)if(Tf(P))return P;return null}catch{return null}}function kR(f){let $=C7;while(!0){let J=d($,"package.json");if(Tf(J))try{if(JSON.parse(L1(J,"utf8")).name===f)return $}catch{}let W=d($,"node_modules",f,"package.json");if(Tf(W))return J8(W);let H=d($,"..");if(H===$)return null;$=H}}function IR(f){let J=J8(f);for(let W=0;W<4;W++){let H=d(J,"package.json");if(Tf(H))try{let Z=JSON.parse(L1(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 k7(f,$){let J=$.startsWith("file:")?b7($):LR($)?$:d(J8(f),$);if(Tf(J)&&$8.has($W(J)))return J;for(let W of $8){let H=`${J}${W}`;if(Tf(H))return H}for(let W of $8){let H=d(J,`index${W}`);if(Tf(H))return H}return null}function I7(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 m7(f,$,J=new Set){if(J.has(f)||!Tf(f))return;if(J.add(f),!$8.has($W(f)))return;let W=L1(f,"utf8");for(let H of I7(W)){if(H.startsWith("node:")||JW.has(H))continue;if(F6(H)){if(Object.hasOwn(o5,H)||Object.hasOwn(o5,M1(H))||e5(f,H)||S7(H)&&q7(H)||$&&q7(H))continue;throw Error(`Cannot find module '${M1(H)}'`)}let Q=k7(f,H);if(Q)m7(Q,$,J)}}function x7(f,$=new Set,J=new Set){if($.has(f)||!Tf(f))return J;if($.add(f),!$8.has($W(f)))return J;let W=L1(f,"utf8");for(let H of I7(W)){if(J.add(H),F6(H))continue;let Q=k7(f,H);if(Q)x7(Q,$,J)}return J}function mR(f,$){let J=w7(f),W={},H=x7(f),Q=new Set(NR);for(let[Z,j]of Object.entries(o5)){try{J.resolve(Z);continue}catch{}W[Z]=j}for(let Z of H)if(F6(Z)&&(S7(Z)||$))Q.add(Z);for(let Z of Q){if(Object.hasOwn(W,Z)||e5(f,Z))continue;let j=fW(Z);if(j)W[Z]=j}if(!$)return W;for(let Z of H){if(!F6(Z)||Object.hasOwn(W,Z)||e5(f,Z)||Z.startsWith("node:")||JW.has(Z))continue;let j=fW(Z);if(j)W[Z]=j}return W}async function g7(f,$={}){let J=!IR(f);m7(f,J);let W=mR(f,J),H=CR(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:[...JW],transformModules:Object.keys(H)}).import(f,{})}function v7(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 u7(f){return typeof f==="object"&&f!==null}function HW(f){return Array.isArray(f)&&f.every(($)=>typeof $==="string")}function vR(f,$){if(!u7(f.manifest))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);if(!HW(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")&&!HW(f.manifest.providerIds))throw Error(`Invalid plugin module at ${$}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn(f.manifest,"modelIds")&&!HW(f.manifest.modelIds))throw Error(`Invalid plugin module at ${$}: manifest.modelIds must be a string array when provided`)}function uR(f,$){if(!u7(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"`);vR(f,$)}async function W8(f,$={}){let J=xR($.cwd??process.cwd(),f),W=await g7(J,{useCache:$.useCache}),H=$.exportName??"plugin",Q=W.default??W[H];uR(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:gR(Z.manifest),setup:X}}async function K6(f,$={}){return(await L0(f,$)).plugins}async function L0(f,$={}){let J=[],W=[],H=new Map,Q=0;for(let Z of f)try{let j=await W8(Z,$);if(!v7(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 pR}from"node:fs";import{createRequire as iR}from"node:module";import{dirname as nR,join as y6}from"node:path";import{fileURLToPath as aR}from"node:url";var p7={};N(p7,{resolveSubprocessRuntimeExecutable:()=>QW,buildSubprocessSandboxCommand:()=>l7,SubprocessSandbox:()=>h1,CLINE_JS_RUNTIME_PATH_ENV:()=>r7});import{spawn as cR}from"node:child_process";import{basename as dR}from"node:path";import{augmentNodeCommandForDebug as rR,withResolvedClineBuildEnv as lR}from"@cline/shared";function c7(f){if(f instanceof Error)return f;return Error(String(f))}var r7="CLINE_JS_RUNTIME_PATH";function d7(f){let $=f?.trim();if(!$)return!1;let J=dR($).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function QW(f={}){let $=f.env??process.env,J=f.runtimeExecutable?.trim()||$[r7]?.trim();if(J)return J;let W=f.execPath?.trim()||process.execPath;if(d7(W))return W;for(let H of[$.BUN_EXEC_PATH,$.npm_node_execpath,$.NODE]){let Q=H?.trim();if(Q&&d7(Q))return Q}return"node"}function l7(f,$={}){let J=QW({env:$.env,execPath:$.execPath,runtimeExecutable:$.runtimeExecutable});return rR([J,...f],{env:$.env,execArgv:$.execArgv,debugRole:$.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class h1{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??""],$=l7(f,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=cR($[0]??QW(this.options),$.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:lR(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: ${c7(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}": ${c7(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 tR(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 U6(f){return(f instanceof Error?f.message:String(f)).includes("Unknown sandbox plugin id:")}function sR(){let f=nR(aR(import.meta.url)),$=iR(import.meta.url),J=[y6(f,"plugin-sandbox-bootstrap.js"),y6(f,"extensions","plugin-sandbox-bootstrap.js"),y6(f,"agents","plugin-sandbox-bootstrap.js")];for(let Q of J)if(pR(Q))return{file:Q};let W=y6(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(`
|
|
137
|
+
`)}}var ZW=sR();function jW(f,$){return typeof f==="number"&&f>0?f:$}async function n7(f){let $=new h1({name:"plugin-sandbox",..."file"in ZW?{bootstrapFile:ZW.file}:{bootstrapScript:ZW.script},onEvent:f.onEvent}),J=jW(f.importTimeoutMs,4000),W=jW(f.hookTimeoutMs,3000),H=jW(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(tR).map((B)=>{let Y={name:B.name,manifest:B.manifest,setup:(V)=>{oR(V,$,B,H,j),eR(V,$,B,H,j),$F(V,$,B,H,j),fF(V,B)}};return Y.hooks=WF($,B,W,j),Y}),failures:X.failures,shutdown:async()=>{await $.shutdown()},warnings:X.warnings}}function oR(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(!U6(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 eR(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(!U6(j))throw j;return await H(),await $.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:Z},{timeoutMs:W})}}})}function fF(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 $F(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 i7(j)?j:Z}catch(j){if(!U6(j))throw j;await H();let X=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:Z},{timeoutMs:W});return i7(X)?X:Z}}})}function i7(f){return Array.isArray(f)&&f.every(($)=>typeof $==="object"&&$!==null&&("role"in $)&&("content"in $))}function JF(f,$,J,W,H){return async(Q)=>{try{return await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:W})}catch(Z){if(!U6(Z))throw Z;return await H(),await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:W})}}}function WF(f,$,J,W){let H={};for(let Q of $.hooks??[])H[Q]=JF(f,$.pluginId,Q,J,W);return Object.keys(H).length>0?H:void 0}function H8(f){return jF(f)}function Q8(f){return QF(f)}function b$(f={}){let $=f.cwd??process.cwd(),J=H8(f.workspacePath).flatMap((Z)=>Q8(Z)).filter((Z)=>HF(Z)),W=ZF(f.pluginPaths??[],$),H=[],Q=new Set;for(let Z of[...W,...J]){if(Q.has(Z))continue;Q.add(Z),H.push(Z)}return V6(H)}async function O1(f={}){let $=b$(f);if($.length===0)return{extensions:[],failures:[],warnings:[]};if(f.mode==="in_process"){let W=await L0($,{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 n7({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 XF}from"node:child_process";import{promisify as AF}from"node:util";var PF=AF(XF);function XW(f,$){f?.log($,{severity:"warn"})}function BF(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 C$(f,$){let J=await PF("git",["-C",f,...$],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function AW(f,$){if(!f)return;let J=`refs/cline/checkpoints/${$}/`;try{let{stdout:W}=await C$(f,["for-each-ref","--format=%(refname)",J]),H=W.trim().split(`
|
|
138
|
+
`).filter(Boolean);await Promise.allSettled(H.map((Q)=>C$(f,["update-ref","-d",Q])))}catch{}}async function a7(f,$,J){if(!f||J.length===0)return;await Promise.allSettled(J.map((W)=>C$(f,["update-ref",`refs/cline/checkpoints/${$}/${W.runCount}`,W.ref])))}function YF(f,$){let J=f.findIndex((W)=>W.runCount===$.runCount);if(J<0)return[...f,$];return f.map((W,H)=>H===J?$:W)}function t7(f){let $=f.initialRunCount??0,J,W=async()=>{if(J!==void 0)return J;try{J=(await C$(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 C$(f.cwd,["rev-parse","HEAD"])).stdout.trim();if(!B)return;return{ref:B,createdAt:Date.now(),runCount:$,kind:"commit"}}catch(P){XW(f.logger,`${A}: ${P instanceof Error?P.message:String(P)}`);return}},Z=`cline checkpoint session=${f.sessionId} run=${$}`,j="";try{j=(await C$(f.cwd,["stash","create",Z])).stdout.trim()}catch(A){return XW(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 C$(f.cwd,["update-ref",X,j])}catch(A){XW(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=BF(j);if(X?.latest.ref===Z.ref)return;let A=YF(X?.history??[],Z);await f.writeSessionMetadata({...j??{},checkpoint:{latest:Z,history:A}});return}}}import{spawn as DF}from"node:child_process";import{appendFileSync as _F,readFileSync as MF}from"node:fs";import{join as LF}from"node:path";import{augmentNodeCommandForDebug as e7,withResolvedClineBuildEnv as YW}from"@cline/shared";import{ensureHookLogDir as s7}from"@cline/shared/storage";function z1(f,$){if(!$)return;return{name:f,manifest:{capabilities:["hooks"]},hooks:$}}import{existsSync as VF,readdirSync as RF}from"node:fs";import{basename as FF,extname as KF,join as yF}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as G6,resolveHooksConfigSearchPaths as UF}from"@cline/shared/storage";function Z8(f){return UF(f)}var N1;((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"})(N1||={});var j8={["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"},GF=new Map(Object.values(N1).map((f)=>[f.toLowerCase(),f])),TF=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function X8(f){let $=KF(f).toLowerCase();if(!TF.has($))return;let J=FF(f,$).trim().toLowerCase();return GF.get(J)}function n0(f){let $=[],J=new Set,W=Z8(f).filter((H)=>VF(H));for(let H of W)try{for(let Q of RF(H,{withFileTypes:!0})){if(!Q.isFile())continue;let Z=X8(Q.name);if(!Z)continue;let j=yF(H,Q.name);if(J.has(j))continue;J.add(j),$.push({fileName:Z,hookEventName:j8[Z],path:j})}}catch{}return $.sort((H,Q)=>H.path.localeCompare(Q.path))}function D6(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 T6(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 hF(f,$){if(!$)return f;if(!f)return{...$};let J=[f.context,$.context].filter((H)=>typeof H==="string"&&H.length>0).join(`
|
|
139
|
+
`),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 OF(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 PW(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function Ff(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 zF(f){let $=f.trim();if(!$)return{};let W=$.split(`
|
|
140
|
+
`).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 NF(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 fZ(f,$){if($.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await o7(f,$)}catch(J){let W=bF($.command,process.platform,J);if(!W)throw J;return await o7(f,{...$,command:W})}}async function o7(f,$){let J=e7($.command,{env:$.env,debugRole:"hook"}),W=DF(J[0],J.slice(1),{cwd:$.cwd,env:YW($.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 NF(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}=zF(j);Y({exitCode:V,stdout:j,stderr:X,parsedJson:R,parseError:U,timedOut:A})})});return await Promise.race([B,Q])}function qF(f){try{let J=MF(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 wF(f){return!!(f&&typeof f==="object"&&("code"in f)&&f.code==="ENOENT")}function bF(f,$=process.platform,J){if($!=="win32"||!wF(J))return;if(f[0]!=="py"||f[1]!=="-3")return;return["python",...f.slice(2)]}function $Z(f){if(f.length===0)return;let[$,...J]=f,W=$.replace(/\\/g,"/").toLowerCase(),H=W.split("/").at(-1)??W;if(H==="env")return $Z(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 CF(f){let $=qF(f);if($&&$.length>0)return[...$Z($)??$,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 e7(["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 EF(f){let $={};for(let J of n0(f)){if(!J.hookEventName)continue;let W=J.hookEventName,H=$[W]??[];H.push(CF(J.path)),$[W]=H}return $}async function SF(f){let $;for(let J of f.commands){let W=J.join(" ");try{let H=await fZ(f.payload,{command:J,cwd:f.cwd,env:YW(process.env),detached:!1,timeoutMs:f.timeoutMs});if(H?.timedOut){T6(f.logger,`hook command timed out: ${W}`);continue}if(H?.parseError){T6(f.logger,`hook command returned invalid JSON control output: ${W} (${H.parseError})`);continue}$=hF($,OF(H?.parsedJson))}catch(H){T6(f.logger,`hook command failed: ${W}`,H)}}return $}function E$(f){for(let $ of f.commands){let J=$.join(" ");fZ(f.payload,{command:$,cwd:f.cwd,env:YW(process.env),detached:!0}).catch((W)=>{T6(f.logger,`hook command failed: ${J}`,W)})}}function a0(f){return{agentId:f.agentId,conversationId:f.conversationId??f.runId??f.agentId,parentAgentId:f.parentAgentId??null}}function BW(f,$){return{...a0(f.snapshot),userMessage:$}}function JZ(f){return{...a0(f.snapshot),iteration:f.snapshot.iteration,call:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input}}}function WZ(f){return{...a0(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 HZ(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function kF(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 q1(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})}
|
|
141
|
+
`,Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??LF(s7(),"hooks.jsonl");s7(Z),_F(Z,H,"utf8")};return{beforeRun:async(W)=>{let H=BW(W,"");J({...Ff(H,$),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(W)=>{let H=JZ(W);J({...Ff(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:D6(H.call.input)}});return},afterTool:async(W)=>{let H=WZ(W);J({...Ff(H,$),hookName:"tool_result",iteration:H.iteration,tool_result:H.record,postToolUse:{toolName:H.record.name,parameters:D6(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=a0(W);if(H.status==="completed"){J({...Ff(Q,$),hookName:"agent_end",iteration:H.iterations,turn:{outputText:H.outputText,status:H.status},taskComplete:{taskMetadata:{}}});return}if(H.status==="aborted"||PW(H.error?.message)){J({...Ff(Q,$),hookName:"agent_abort",reason:H.error?.message,taskCancel:{taskMetadata:{}}});return}if(H.error)J({...Ff(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=BW({snapshot:W.snapshot},HZ(W.message.content));J({...Ff(H,$),hookName:"prompt_submit",userPromptSubmit:{prompt:H.userMessage,attachments:[]}})}}}function A8(f){let $=EF(f.workspacePath);if(!Object.values($).some((B)=>B.length>0))return;let W=async(B,Y)=>{let V=$[Y]??[];if(V.length===0)return;E$({commands:V,cwd:f.cwd,logger:f.logger,payload:Y==="agent_resume"?{...Ff(B,f),hookName:Y,taskResume:{taskMetadata:{},previousState:{}}}:{...Ff(B,f),hookName:Y,taskStart:{taskMetadata:{}}}})},H=async(B)=>{let Y=$.prompt_submit??[];if(Y.length>0)E$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...Ff(B,f),hookName:"prompt_submit",userPromptSubmit:{prompt:B.userMessage,attachments:[]}}})},Q=async(B)=>{let Y=$.tool_call??[];if(Y.length===0)return;return SF({commands:Y,cwd:f.cwd,logger:f.logger,timeoutMs:f.toolCallTimeoutMs??120000,payload:{...Ff(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:D6(B.call.input)}}})},Z=async(B)=>{let Y=$.tool_result??[];if(Y.length===0)return;E$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...Ff(B,f),hookName:"tool_result",iteration:B.iteration,tool_result:B.record,postToolUse:{toolName:B.record.name,parameters:D6(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;E$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...Ff(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;E$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...Ff(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(PW(B.reason)){let V=$.agent_abort??[];if(V.length>0)E$({commands:V,cwd:f.cwd,logger:f.logger,payload:{...Ff(B,f),hookName:"agent_abort",reason:B.reason,taskCancel:{taskMetadata:{}}}})}let Y=$.session_shutdown??[];if(Y.length===0)return;E$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...Ff(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(a0(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(BW({snapshot:B.snapshot},HZ(B.message.content)))}}if(($.tool_call?.length??0)>0)P.beforeTool=async(B)=>{let Y=await Q(JZ(B));return kF(Y)};if(($.tool_result?.length??0)>0)P.afterTool=async(B)=>{await Z(WZ(B));return};if(($.agent_end?.length??0)>0)P.afterRun=async({snapshot:B,result:Y})=>{if(Y.status!=="completed")return;await j({...a0(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"||PW(R.error?.message)){await A({...a0(V),reason:R.error?.message});return}if(R.error)await X({...a0(V),iteration:R.iterations,error:R.error})}}return P}function w1(f){return z1("core.hook_config_files",A8(f))}function S$(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 k$(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return;return{beforeRun:S$($,"beforeRun"),afterRun:S$($,"afterRun"),beforeModel:S$($,"beforeModel"),afterModel:S$($,"afterModel"),beforeTool:S$($,"beforeTool"),afterTool:S$($,"afterTool"),onEvent:S$($,"onEvent")}}var QZ={};N(QZ,{normalizeRuntimeCapabilities:()=>Kf});function Kf(...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 qZ={};N(qZ,{toProviderConfig:()=>kf,emptyStoredProviderSettings:()=>e0,StoredProviderSettingsSchema:()=>S1,StoredProviderSettingsEntrySchema:()=>l6,ProviderSettingsSchemaTyped:()=>G8});import{z as o0}from"zod";var NZ={};N(NZ,{toProviderConfig:()=>kf,safeParseSettings:()=>r6,safeCreateProviderConfig:()=>qW,parseSettings:()=>d6,normalizeProviderId:()=>E1,isBuiltInProviderId:()=>zW,createProviderConfig:()=>NW,SapSettingsSchema:()=>v6,ReasoningSettingsSchema:()=>I6,ProviderSettingsSchema:()=>s0,ProviderProtocolSchema:()=>E6,ProviderIdSchema:()=>U8,ProviderClientSchema:()=>S6,OcaSettingsSchema:()=>u6,ModelCatalogSettingsSchema:()=>c6,GcpSettingsSchema:()=>x6,BUILT_IN_PROVIDER_IDS:()=>OW,BUILT_IN_PROVIDER:()=>y8,AzureSettingsSchema:()=>g6,AwsSettingsSchema:()=>m6,AuthSettingsSchema:()=>k6});import*as Sf from"@cline/llms";import{z as h}from"zod";Lf();var DZ={};N(DZ,{refreshOcaToken:()=>B8,loginOcaOAuth:()=>b1,getValidOcaCredentials:()=>Y8,generateOcaOpcRequestId:()=>h6,createOcaRequestHeaders:()=>KW,createOcaOAuthProvider:()=>FW,OCI_HEADER_OPC_REQUEST_ID:()=>RZ,DEFAULT_INTERNAL_OCA_BASE_URL:()=>_6,DEFAULT_INTERNAL_IDCS_URL:()=>AZ,DEFAULT_INTERNAL_IDCS_SCOPES:()=>PZ,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>XZ,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>M6,DEFAULT_EXTERNAL_IDCS_URL:()=>YZ,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>VZ,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>BZ});import{nanoid as jZ}from"nanoid";class VW{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 ZZ={};N(ZZ,{startLocalOAuthServer:()=>h0});function IF(){let f;return{promise:new Promise((J)=>{f=J}),resolve:f}}async function h0(f){let $=await import("node:http"),J=f.host??"127.0.0.1",W=f.timeoutMs??300000,H=f.successHtml??mF,Q=IF(),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 mF=`<!DOCTYPE html>
|
|
142
142
|
<html lang="en">
|
|
143
143
|
<head>
|
|
144
144
|
<meta charset="utf-8">
|
|
@@ -179,30 +179,30 @@ ${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function M7(f,$){l
|
|
|
179
179
|
</div>
|
|
180
180
|
<script>setTimeout(() => window.close(), 3000);</script>
|
|
181
181
|
</body>
|
|
182
|
-
</html>`;var U6="a8331954c0cf48ba99b5dd223a14c6ea",G6="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",T6="openid offline_access",z1="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",h6="c1aba3deed5740659981a752714eba33",D6="https://login-ext.identity.oraclecloud.com",M6="openid offline_access",O1="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",_6="opc-request-id",BF="/auth/oca",AF=Array.from({length:11},(f,$)=>48801+$),RF=300000,FF=30000,iQ=30000,yF=600000;class L6 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 i0={internal:{clientId:U6,idcsUrl:G6,scopes:T6,baseUrl:z1},external:{clientId:h6,idcsUrl:D6,scopes:M6,baseUrl:O1}},Z8=new Map,KF=86400000,UF=300000,GF=32,Y5=new V5(KF,GF);function nQ(f){if(typeof f==="function")return f();return f??"internal"}function aQ(f){return{internal:{clientId:f?.internal?.clientId??i0.internal.clientId,idcsUrl:f?.internal?.idcsUrl??i0.internal.idcsUrl,scopes:f?.internal?.scopes??i0.internal.scopes,baseUrl:f?.internal?.baseUrl??i0.internal.baseUrl},external:{clientId:f?.external?.clientId??i0.external.clientId,idcsUrl:f?.external?.idcsUrl??i0.external.idcsUrl,scopes:f?.external?.scopes??i0.external.scopes,baseUrl:f?.external?.baseUrl??i0.external.baseUrl}}}function TF(f=Date.now()){let $=f-yF;for(let[J,W]of Z8.entries())if(W.createdAt<$)Z8.delete(J)}function hF(f,$,J){if(typeof f.expires_in==="number"&&f.expires_in>0)return Date.now()+f.expires_in*1000;let H=Rf($)?.exp;if(typeof H==="number"&&H>0)return H*1000;let Z=Rf(J)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return Date.now()+3600000}function tQ(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=Rf(f.id_token),Z=Rf(W),j=Q?.sub??Z?.sub,P=Q?.email??Z?.email;return{access:W,refresh:H,expires:hF(f,W,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 sQ(f,$){let J=Q6(f),W=Y5.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 P=`${J}/oauth2/v1/token`;return Y5.set(J,P,Date.now(),UF),P}let j=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return Y5.set(J,j),j}function oQ(f){return{code:f.error,message:f.error_description}}async function DF(f){let $=Z8.get(f.state);if(!$)throw Error("No PKCE verifier found for this state");Z8.delete(f.state);let J=f.mode==="external"?f.config.external:f.config.internal,W=await sQ(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 P=oQ(Z);throw new L6(`Token exchange failed: ${Q.status}${P.message?` - ${P.message}`:""}`,{status:Q.status,errorCode:P.code})}let j=Rf(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 tQ(Z,f.mode)}function MF(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 N1(f){R0(f.telemetry,"oca");let $=aQ(f.config),J=nQ(f.mode),W=f.callbackPorts?.length?f.callbackPorts:AF,H=f.callbackPath??BF,Q=f.requestTimeoutMs??iQ,Z=await h0({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 P=pQ(16),X=pQ(16),{verifier:V,challenge:Y}=await H6();TF(),Z8.set(P,{verifier:V,nonce:X,mode:J,redirectUri:j,createdAt:Date.now()});let B=MF({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 G1({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 DF({code:R,state:U,mode:J,config:$,requestTimeoutMs:Q});return F0(f.telemetry,"oca"),K0(f.telemetry,{id:y.accountId,email:y.email,provider:"oca"}),y}catch(A){throw y0(f.telemetry,"oca",A instanceof Error?A.message:String(A)),A}finally{Z.close()}}async function j8(f,$={}){let J=aQ($.config),W=$.requestTimeoutMs??iQ,H=f.metadata?.mode,Q=H==="internal"||H==="external"?H:nQ($.mode),Z=Q==="external"?J.external:J.internal,j=await sQ(Z.idcsUrl,W),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(W)}),V=await X.json();if(!X.ok){let Y=oQ(V);throw new L6(`Token refresh failed: ${X.status}${Y.message?` - ${Y.message}`:""}`,{status:X.status,errorCode:Y.code})}return tQ(V,Q,f)}async function P8(f,$,J){if(!f)return null;let W=$?.refreshBufferMs??J?.refreshBufferMs??RF,H=$?.retryableTokenGraceMs??J?.retryableTokenGraceMs??FF;if($?.forceRefresh!==!0&&!_$(f,W))return f;try{return await j8(f,J)}catch(Z){if(Z instanceof L6&&Z.isLikelyInvalidGrant())return g0(J?.telemetry,"oca","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function B5(f={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login($){return N1({...f,callbacks:$})},async refreshToken($){return j8($,f)},getApiKey($){return $.access}}}async function z6(f,$){let J=new TextEncoder,W=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("")},[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 P=(j[0]??0).toString(16).padStart(8,"0");return H+Q+Z+P}async function A5(f){let $=await z6(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",[_6]:$}}var QZ={};N(QZ,{resolveProviderConfig:()=>Y8,getProviderConfig:()=>S6,getLiveModelsCatalog:()=>q1,clearPublicModelsCatalogCache:()=>dF,clearPrivateModelsCatalogCache:()=>D5,clearLiveModelsCatalogCache:()=>h5,OPENAI_COMPATIBLE_PROVIDERS:()=>V8,DEFAULT_MODELS_CATALOG_URL:()=>C6});import*as Af from"@cline/llms";function R5(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 _F(f,$){let J=R5(f);if(J.length>0)return J;if(!f||typeof f!=="object")return[];let W=f,H=R5(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=R5(Q.models??Q);if(j.length>0)return j}return[]}async function O6(f,$){let J=await fetch(f,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${f}: HTTP ${J.status}`);return _F(await J.json(),$)}function fZ(f){return f.replace(/\/+$/,"")}function N6(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 P=fZ(Z.pathname),X=fZ(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 W}}function LF(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{...J}]))}function zF(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 OF=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:LF(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})),$Z=Object.fromEntries(OF.map((f)=>[f.id,f]));function NF(f){return $Z[f]}function qF(){return Object.fromEntries(Object.entries($Z).filter(([,f])=>zF(f)))}function JZ(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 C6="https://models.dev/api.json",bF=600000,WZ=300000,wF=5000,w6=new Map,X8=new Map,y5=new Map,q6=new Map;async function CF(){return Af.getGeneratedProviderModels()}async function EF(f,$={},J={},W={},H={},Q={}){let Z=await CF(),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(H).length>0;if(X&&V)return Af.sortModelsByReleaseDate({...H,...Q});return Af.sortModelsByReleaseDate({...P,...$,...J,...W,...H,...Q})}function SF(f,$){let J=Af.resolveProviderModelCatalogKeys(f);return Object.assign({},...J.map((W)=>$[W]??{}))}function U5(f){let $=f?.trim();return $&&$.length>0?$:""}function G5(f){let $=f.apiKey?.trim()||f.accessToken?.trim();return $&&$.length>0?$:void 0}function kF(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 mF(f,$){return`${f}:${U5($.baseUrl)}:${kF(G5($)??"")}`}async function T5(f,$,J=wF){let W=new AbortController,H=setTimeout(()=>W.abort(),J);try{return await fetch(f,{...$,signal:W.signal})}finally{clearTimeout(H)}}function F5(f,$,J){if(J&&!f.includes($))f.push($)}function E6(f,$){let J=["streaming","tools"];return F5(J,"images",Boolean($.supportsImages)),F5(J,"prompt-cache",Boolean($.supportsPromptCache)),F5(J,"reasoning",Boolean($.supportsReasoning)),{id:f,name:$.name??f,contextWindow:$.contextWindow,maxTokens:$.maxTokens,capabilities:J,releaseDate:$.releaseDate,status:"active"}}async function IF(f,$){let J=await T5("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 P=Z.supported_features??[];Q[j]=E6(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 xF(f,$){let J=await T5("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]=E6(j,{name:j,contextWindow:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}function gF(f){let $=U5(f);if(!$)return"http://localhost:4000";return $.endsWith("/v1")?$.slice(0,-3):$}async function vF(f,$){let W=`${gF(f.baseUrl)}/v1/model/info`,H=async(X)=>T5(W,{method:"GET",headers:{accept:"application/json",...X}}),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??[],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=E6(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 HZ={baseten:IF,hicap:xF,litellm:vF},K5=new Map,b6=new Map;function uF(f,$){return`${f}:${U5($.baseUrl)}`}async function cF(f,$,J){let W=Af.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],H=N6(J.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!H)return{};let Q=$?.cacheTtlMs??WZ,Z=uF(f,J),j=Date.now(),P=K5.get(Z);if(P&&P.expiresAt>j)return P.data;let X=b6.get(Z);if(X)return X;let V=O6(H,f).then((Y)=>{let B=Object.fromEntries(Y.map((A)=>[A,E6(A,{name:A})]));return K5.set(Z,{data:B,expiresAt:j+Q}),B}).finally(()=>{b6.delete(Z)});return b6.set(Z,V),V}function dF(){K5.clear(),b6.clear()}async function rF(f,$){let J=G5($);if(!J)return{};let W=HZ[f];if(!W)return{};return W($,J)}function lF(f,$,J){if(!J)return!1;if(!HZ[f])return!1;if($?.loadPrivateOnAuth===!1)return!1;return Boolean(G5(J))}async function pF(f,$,J){let W=$?.cacheTtlMs??WZ,H=mF(f,J),Q=Date.now(),Z=y5.get(H);if(Z&&Z.expiresAt>Q)return Z.data;let j=q6.get(H);if(j)return j;let P=rF(f,J).then((X)=>{return y5.set(H,{data:X,expiresAt:Q+W}),X}).finally(()=>{q6.delete(H)});return q6.set(H,P),P}async function iF(f){return Af.fetchModelsDevProviderModels(f)}async function q1(f={}){let $=f.url??C6,J=f.cacheTtlMs??bF,W=Date.now(),H=w6.get($);if(H&&H.expiresAt>W)return H.data;let Q=X8.get($);if(Q)return Q;let Z=iF($).then((j)=>{return w6.set($,{data:j,expiresAt:W+J}),j}).finally(()=>{X8.delete($)});return X8.set($,Z),Z}function h5(f){if(f){w6.delete(f),X8.delete(f);return}w6.clear(),X8.clear()}function D5(){y5.clear(),q6.clear()}function nF(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:JZ(J.capabilities)}]))}var V8=nF(qF());function S6(f){let $=NF(f);if(!$||!$.baseUrl)return;return{baseUrl:$.baseUrl,modelId:$.modelId,knownModels:$.knownModels,capabilities:JZ($.capabilities)}}async function Y8(f,$,J){let W=S6(f);if(!W)return;try{let H=$?.loadLatestOnInit?await q1($):void 0,Q=H?SF(f,H):{},Z=J&&lF(f,$,J)?await pF(f,$,J):{},P=Boolean(Af.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl)?J??{providerId:f,modelId:W.modelId,baseUrl:W.baseUrl}:J,X=P?await cF(f,$,P).catch(()=>({})):{},V=await EF(f,W.knownModels,Q,Z,X,J?.knownModels);return{...W,knownModels:V}}catch(H){if($?.failOnError)throw H;return W}}var B8=qf.BUILT_IN_PROVIDER,M5=qf.BUILT_IN_PROVIDER_IDS,_5=qf.isBuiltInProviderId,b1=qf.normalizeProviderId,A8=_.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),k6=_.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),m6=_.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),I6=_.object({apiKey:_.string().optional(),accessToken:_.string().optional(),refreshToken:_.string().optional(),expiresAt:_.number().int().positive().optional(),accountId:_.string().optional()}),aF=_.enum(["none","low","medium","high","xhigh"]),x6=_.object({enabled:_.boolean().optional(),effort:aF.optional(),budgetTokens:_.number().int().positive().optional()}),g6=_.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()}),v6=_.object({projectId:_.string().optional(),region:_.string().optional()}),u6=_.object({apiVersion:_.string().optional(),useIdentity:_.boolean().optional()}),c6=_.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()}),d6=_.object({mode:_.enum(["internal","external"]).optional(),usePromptCache:_.boolean().optional()}),r6=_.object({loadLatestOnInit:_.boolean().optional(),loadPrivateOnAuth:_.boolean().optional(),url:_.string().url().optional(),cacheTtlMs:_.number().int().positive().optional(),failOnError:_.boolean().optional()}),n0=_.object({provider:A8,apiKey:_.string().optional(),auth:I6.optional(),model:_.string().optional(),protocol:k6.optional(),client:m6.optional(),routingProviderId:A8.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:x6.optional(),aws:g6.optional(),gcp:v6.optional(),azure:u6.optional(),sap:c6.optional(),oca:d6.optional(),region:_.string().optional(),apiLine:_.enum(["china","international"]).optional(),capabilities:_.array(_.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth"])).optional(),modelCatalog:r6.optional()});function l6(f){return n0.parse(f)}function p6(f){return n0.safeParse(f)}function tF(f){return f.protocol==="openai-responses"||f.client==="openai"}function bf(f,$={}){let J=f.provider,W=b1(J),H=$.includeKnownModels!==!1,Q=f.reasoning?.effort||"none",Z=Q==="none"?void 0:Q,j=V8[W],P=Object.assign({},...qf.resolveProviderModelCatalogKeys(W).map((U)=>qf.getGeneratedModelsForProvider(U))),X=Object.keys(P)[0],V=f.auth?.accessToken??f.apiKey??f.auth?.apiKey,Y=f.baseUrl??(W==="oca"?f.oca?.mode==="internal"?z1:O1:j?.baseUrl),B=f.routingProviderId??(tF(f)&&W!==B8.OPENAI_NATIVE?B8.OPENAI_NATIVE:void 0),A=H?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",...H?{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 L5(f){let $=l6(f);return bf($)}function z5(f){let $=p6(f);if($.success)return{success:!0,config:bf($.data)};return{success:!1,error:$.error}}var R8=n0;var i6=a0.object({settings:n0,updatedAt:a0.string().datetime(),tokenSource:a0.enum(["manual","oauth","migration"]).default("manual")}),w1=a0.object({version:a0.literal(1),lastUsedProvider:a0.string().min(1).optional(),providers:a0.record(a0.string(),i6)});function t0(){return{version:1,providers:{}}}G0();var YZ={};N(YZ,{InMemoryWorkspaceManager:()=>E1});import{upsertWorkspaceInfo as fy,WorkspaceManifestSchema as N5}from"@cline/shared";var VZ={};N(VZ,{normalizeWorkspacePath:()=>D0,generateWorkspaceInfoWithDiagnostics:()=>F8,generateWorkspaceInfo:()=>C1,buildWorkspaceMetadataWithInfo:()=>O5,buildWorkspaceMetadata:()=>y8});import{basename as sF,resolve as oF}from"node:path";import{performance as PZ}from"node:perf_hooks";import{processWorkspaceInfo as XZ}from"@cline/shared";import eF from"simple-git";function D0(f){return oF(f)}async function C1(f){return(await F8(f)).info}function n6(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 F8(f){let $=D0(f),J={rootPath:$,hint:sF($)},W;try{let H=eF({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((P)=>{let X=P.refs.fetch||P.refs.push;return`${P.name}: ${X}`});J.associatedRemoteUrls=j}}catch(Z){W??=n6(Z)}try{let Z=(await H.revparse(["HEAD"])).trim();if(Z.length>0)J.latestGitCommitHash=Z}catch(Z){W??=n6(Z)}try{let Z=(await H.branch()).current.trim();if(Z.length>0)J.latestGitBranchName=Z}catch(Z){W??=n6(Z)}return{info:J,vcsType:"git",error:W}}catch(H){return{info:J,vcsType:"none",error:n6(H)}}}async function y8(f){let $=await C1(f);return XZ($)}async function O5(f){let $=PZ.now(),J=await F8(f),W=PZ.now()-$,H=J.info;return{workspaceInfo:H,workspaceMetadata:XZ(H),durationMs:W,vcsType:J.vcsType,initError:J.error}}class E1{manifest;listeners=new Set;constructor(f){this.manifest=N5.parse(f??{workspaces:{}})}async addWorkspacePath(f){let $=await C1(f);return this.manifest=fy(this.manifest,$),this.emit({type:"workspace_added",workspace:$}),$}async switchWorkspace(f){let $=D0(f),J=this.manifest.workspaces[$];if(J)return this.manifest=N5.parse({...this.manifest,currentWorkspacePath:$}),this.emit({type:"workspace_switched",workspace:J}),J;let W=await this.addWorkspacePath($);return this.manifest=N5.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 $=D0(f);return this.manifest.workspaces[$]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(f){for(let $ of this.listeners)$(f)}}Gf();import{createHash as $y}from"node:crypto";var BZ=new Set,AZ=new Set;function Jy(f){return $y("sha256").update(f).digest("hex")}function Wy(f){if(f.vcsTypes&&f.vcsTypes.length>0)return f.vcsTypes;return[f.vcsType==="git"?"git":"none"]}function RZ(f){if(!f.telemetry)return;let $=Jy(f.rootPath),J=f.rootCount??1;if(!BZ.has($))BZ.add($),r4(f.telemetry,{root_count:J,vcs_types:Wy(f),init_duration_ms:f.durationMs,feature_flag_enabled:f.featureFlagEnabled??!0,is_remote_workspace:f.isRemoteWorkspace});if(f.initError&&!AZ.has($)){AZ.add($);let W=Error(f.initError.message);W.name=f.initError.errorType||"Error",l4(f.telemetry,W,{fallback_to_single_root:!0,workspace_count:J})}}function Qy(f){return`${f.pluginName??f.pluginPath}: ${f.message}`}function Zy(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(Qy).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 jy(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 Py(f,$){return Hy(f,$)}function Xy(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 Vy(f){let $={...f.storedHeaders??{},...f.configHeaders??{}},J=f.accountId?.trim()||Yy(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 Yy(f){let $=f?.trim();if(!$)return;let J=Rf($),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 By(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"?Vy({sessionId:$,configHeaders:f.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:f.apiKey??Q?.auth?.accessToken??Q?.apiKey}):f.headers??Q?.headers,reasoning:jy(f,Q?.reasoning),modelCatalog:Z},P=bf(j);if(f.knownModels)P.knownModels=f.knownModels;if(f.extensionContext)P.extensionContext=f.extensionContext;let V=f.fetch??P.fetch??H;if(V)P.fetch=V;return P}async function FZ(f){let{input:$,sessionId:J,providerSettingsManager:W,defaultTelemetry:H,defaultCapabilities:Q,defaultToolPolicies:Z,defaultFetch:j,onPluginEvent:P,onTeamEvent:X,createSpawnTool:V,localRuntime:Y,readSessionMetadata:B,writeSessionMetadata:A}=f,R=d0($.config),{modelCatalogDefaults:U,userInstructionService:y,configExtensions:F,onTeamRestored:K,...M}=Y??{},h=Object.keys(M).length>0?M:void 0,{workspaceInfo:G,workspaceMetadata:T,durationMs:z,vcsType:u,initError:vf}=await O5(R),a=h?.extensionContext,c={...a??{},workspace:{...G,...a?.workspace??{}},session:{...a?.session??{},sessionId:J},logger:a?.logger??h?.logger,telemetry:a?.telemetry??h?.telemetry??H};RZ({telemetry:c.telemetry,rootPath:G.rootPath,workspaceInfo:G,rootCount:1,vcsType:u,durationMs:z,initError:vf,featureFlagEnabled:!0});let d=L1({cwd:$.config.cwd,workspacePath:R,rootSessionId:J,logger:h?.logger,workspaceInfo:G}),t=s7(h?.hooks)?void 0:_1({rootSessionId:J,workspacePath:R,workspaceInfo:G}),nf=w$([h?.hooks,t]),C;if(Py(F,"plugins"))try{C=await h1({pluginPaths:h?.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}),Zy(C.failures,C.warnings,h?.logger)}catch(y2){let r=y2 instanceof Error?y2.message:String(y2);h?.logger?.log?.(`plugin loading failed; continuing without plugins (${r})`)}let uf=dW(d?[d]:void 0,dW(h?.extensions,X6(C?.extensions))),$f={...$.config,...h??{},sessionId:J,hooks:nf,extensions:uf,extensionContext:c,telemetry:c.telemetry},R2=By($f,J,W,U,j),P$=w$([$f.hooks,$f.checkpoint?.enabled===!0?kQ({cwd:$f.cwd,sessionId:J,logger:$f.logger,createCheckpoint:$f.checkpoint?.createCheckpoint,initialRunCount:Xy($.initialMessages),readSessionMetadata:B,writeSessionMetadata:A}):void 0]),X$={...$f,providerConfig:R2,workspaceMetadata:T,hooks:P$},e$=$.toolPolicies??$f.toolPolicies??Z,F2=Vf(Q,$.capabilities),z4=F2?.requestToolApproval,QW=F2?.toolExecutors,f1=new E1({currentWorkspacePath:G.rootPath,workspaces:{[G.rootPath]:G}});return{effectiveInput:$,config:X$,providerConfig:R2,workspaceMetadata:T,workspaceInfo:G,extensions:uf,hooks:P$,toolPolicies:e$,requestToolApproval:z4,pluginSandboxShutdown:C?.shutdown,runtimeBuilderInput:{config:X$,hooks:P$,extensions:uf,onTeamEvent:X,createSpawnTool:V,onTeamRestored:K,userInstructionService:y,configExtensions:F,toolExecutors:QW,workspaceManager:f1,logger:X$.logger,telemetry:X$.telemetry}}}import{existsSync as t6,mkdirSync as Ay,readdirSync as Ry,rmdirSync as Fy,rmSync as yy,unlinkSync as Ky}from"node:fs";import{dirname as yZ,join as a6}from"node:path";function s(){return new Date().toISOString()}function K8(f){if(!f||!t6(f))return;try{Ky(f)}catch{}}function Uy(f){let $=R1(f);if($)return{rootSessionId:$.rootSessionId,fileStem:`${$.agentId}__${$.teamTaskId}`};let J=u2(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 a6(this.ensureSessionsDir(),f)}ensureSessionArtifactsDir(f){let $=this.sessionArtifactsDir(f);if(!t6($))Ay($,{recursive:!0});return $}sessionMessagesPath(f){return a6(this.sessionArtifactsDir(f),`${f}.messages.json`)}sessionManifestPath(f,$=!1){let J=$?this.ensureSessionArtifactsDir(f):this.sessionArtifactsDir(f);return a6(J,`${f}.json`)}removeSessionDirIfEmpty(f){let $=this.sessionArtifactsDir(f),J=this.ensureSessionsDir();while($.startsWith(J)&&$!==J){if(!t6($)){$=yZ($);continue}try{if(Ry($).length>0)break;Fy($)}catch{break}$=yZ($)}}removeSessionDir(f){this.removeDir(this.sessionArtifactsDir(f))}removeDir(f){if(!t6(f))return;try{yy(f,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths(f,$,J){let{rootSessionId:W,fileStem:H}=Uy(f),Q=this.sessionArtifactsDir(W);return{messagesPath:a6(Q,`${H}.messages.json`)}}}import{resolveDocumentsExtensionPath as Gy}from"@cline/shared/storage";Gf();function KZ(f,$,J,W,H){if(J)i4(f.telemetry,{ulid:$,apiProvider:f.providerId,...H});else p4(f.telemetry,{ulid:$,apiProvider:f.providerId,...H});Ty(f.telemetry,{workspacePath:W})}function Ty(f,$){let J=Gy("Hooks"),W=l0($.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())W6(f,Q,Z.global,Z.workspace)}function UZ(f,$){for(let J of $.mentions)$6(f,J,$.matchedFiles.includes(J)?1:0,"file",!$.matchedFiles.includes(J));for(let J of $.matchedFiles)e4(f,"file",J.length);for(let J of $.ignoredMentions)f6(f,"file","not_found",J)}var nV={};N(nV,{ProviderSettingsManager:()=>P0});import{chmodSync as tV,existsSync as f3,mkdirSync as qL,readFileSync as bL,writeFileSync as wL}from"node:fs";import{basename as sV,dirname as $3}from"node:path";import{resolveProviderSettingsPath as CL}from"@cline/shared/storage";var L={};N(L,{writeHubDiscovery:()=>KJ,writeGlobalSettings:()=>L$,withHubStartupLock:()=>UJ,verifyHubConnection:()=>f0,updateLocalProvider:()=>nJ,truncateNotificationBody:()=>y4,toggleDisabledTool:()=>j6,toTeamProgressLifecycleEvent:()=>p1,toProviderConfig:()=>bf,toHubHealthUrl:()=>hH,toHookConfigFileName:()=>H8,summarizeUsageFromMessages:()=>a2,stopLocalHubServerGracefully:()=>CH,startLocalOAuthServer:()=>h0,startHubWebSocketServer:()=>t$,startHubServer:()=>oX,startClineDeviceAuth:()=>k5,splitCoreSessionConfig:()=>v8,spawnDetachedHubServer:()=>u1,setTelemetryOptOutGlobally:()=>YQ,setDisabledTools:()=>tW,setDisabledPlugin:()=>FQ,sendHubCommand:()=>HX,saveLocalProviderSettings:()=>m9,saveLocalProviderOAuthCredentials:()=>v9,sanitizeTeamName:()=>I4,sanitizeSessionToken:()=>h$,safeParseSettings:()=>p6,safeCreateProviderConfig:()=>z5,runSubprocessEvent:()=>f2,runHook:()=>J2,reviveTeamStateDates:()=>m4,restartLocalHubIfIdleAfterStartupTimeout:()=>hJ,resolveWorkspaceHubOwnerContext:()=>aj,resolveWorkflowsConfigSearchPaths:()=>E8,resolveSkillsConfigSearchPaths:()=>w8,resolveSharedHubOwnerContext:()=>Qf,resolveSessionBackend:()=>sH,resolveRulesConfigSearchPaths:()=>C8,resolveProviderConfig:()=>Y8,resolvePluginConfigSearchPaths:()=>f8,resolveMcpServerRegistrations:()=>Y4,resolveLocalClineAuthToken:()=>u9,resolveHubUrl:()=>H9,resolveHubOwnerContext:()=>M0,resolveHubEndpointOptions:()=>Sf,resolveHubBuildId:()=>J$,resolveHooksConfigSearchPaths:()=>J8,resolveDisabledToolNames:()=>rf,resolveDisabledPluginPaths:()=>o2,resolveDefaultMcpSettingsPath:()=>Q$,resolveDefaultHubPort:()=>v1,resolveDefaultHubPathname:()=>zH,resolveDefaultHubHost:()=>LH,resolveCoreSelectedToolIds:()=>g4,resolveCompatibleLocalHubUrl:()=>f4,resolveClineDir:()=>lj,resolveClineDataDir:()=>t8,resolveAndLoadAgentPlugins:()=>h1,resolveAgentPluginPaths:()=>O$,requestHubShutdown:()=>e8,requestDesktopToolApproval:()=>N9,rememberRecoverableLocalHubUrl:()=>W$,registerMcpServersFromSettingsFile:()=>o1,registerDisposable:()=>zL,refreshProviderModelsFromSource:()=>I9,refreshOpenAICodexToken:()=>M8,refreshOcaToken:()=>j8,refreshClineToken:()=>h8,readSessionCheckpointHistory:()=>K4,readHubDiscovery:()=>Zf,readGlobalSettings:()=>of,probeHubServer:()=>Bf,probeHubConnection:()=>WX,prewarmFileIndex:()=>b4,prewarmDetachedHubServer:()=>GJ,parseWorkflowConfigFromMarkdown:()=>b8,parseUserCommandEnvelope:()=>LL,parseSkillConfigFromMarkdown:()=>N8,parseSettings:()=>l6,parseRuleConfigFromMarkdown:()=>q8,parseHookEventPayload:()=>$2,openaiCodexOAuthProvider:()=>v5,normalizeWorkspacePath:()=>D0,normalizeUserInput:()=>_L,normalizeRuntimeCapabilities:()=>Vf,normalizeProviderId:()=>b1,normalizeOpenAICodexCredentials:()=>g5,normalizeOAuthProvider:()=>x9,normalizeHubWebSocketUrl:()=>H$,noopBasicLogger:()=>ML,migrateLegacyProviderSettings:()=>_4,mergeRulesForSystemPrompt:()=>g1,mergeAgentHooks:()=>w$,makeTeamTaskSubSessionId:()=>v2,makeSubSessionId:()=>A1,loginOpenAICodex:()=>m1,loginOcaOAuth:()=>N1,loginLocalProvider:()=>g9,loginClineOAuth:()=>k1,loadOpenTelemetryAdapter:()=>AL,loadMcpSettingsFile:()=>V4,loadLlmsConfigFromFile:()=>s9,loadAgentPluginsFromPathsWithDiagnostics:()=>T0,loadAgentPluginsFromPaths:()=>B6,loadAgentPluginFromPath:()=>e2,listSessionHistoryFromBackend:()=>KH,listPluginTools:()=>g8,listLocalProviders:()=>S9,listHookConfigFiles:()=>l0,isToolDisabledGlobally:()=>BQ,isTelemetryOptedOutGlobally:()=>Z6,isRuleEnabled:()=>jJ,isPluginDisabledGlobally:()=>RQ,isOpenAICodexTokenExpired:()=>x5,isHubReconnectableTransportError:()=>bH,isHubCommandTimeoutError:()=>TJ,isDiscoveryFilePresent:()=>ij,isClineAccountActionRequest:()=>s6,isBuiltInProviderId:()=>_5,identifyAccount:()=>K0,hasMcpSettingsFile:()=>s1,getValidOpenAICodexCredentials:()=>_8,getValidOcaCredentials:()=>P8,getValidClineCredentials:()=>D8,getProviderConfigFields:()=>c9,getProviderConfig:()=>S6,getLocalProviderModels:()=>k9,getLiveModelsCatalog:()=>q1,getFileIndex:()=>Y0,getCurrentContextSize:()=>iW,getCoreHeadlessToolNames:()=>g2,getCoreDefaultEnabledToolIds:()=>x4,getCoreBuiltinToolCatalog:()=>G$,getCoreAcpToolNames:()=>v4,getClineDefaultSystemPrompt:()=>FL,generateWorkspaceInfoWithDiagnostics:()=>F8,generateWorkspaceInfo:()=>C1,generateOcaOpcRequestId:()=>z6,formatRulesForSystemPrompt:()=>x1,formatDisplayUserInput:()=>DL,filterExtensionToolRegistrations:()=>X6,filterDisabledTools:()=>z$,filterDisabledPluginPaths:()=>P6,fetchClineRecommendedModels:()=>a9,executeClineAccountAction:()=>o6,ensureHubWebSocketServer:()=>vJ,ensureHubServer:()=>eX,ensureDetachedHubServer:()=>sj,ensureCustomProvidersLoaded:()=>iJ,ensureCompatibleLocalHubUrl:()=>g$,enrichPromptWithMentions:()=>H1,emptyWorkspaceManifest:()=>hL,emptyStoredProviderSettings:()=>t0,discoverPluginModulePaths:()=>$8,deriveSubsessionStatus:()=>c2,deleteLocalProvider:()=>aJ,defineLlmsConfig:()=>t9,createWorkflowsConfigDefinition:()=>m8,createUserInstructionConfigService:()=>o0,createToolPoliciesWithPreset:()=>C4,createTool:()=>TL,createTeamName:()=>cJ,createSubprocessHooks:()=>wJ,createSpawnAgentTool:()=>I0,createSkillsConfigDefinition:()=>S8,createSessionHost:()=>a1,createRuntimeHost:()=>a1,createRulesConfigDefinition:()=>k8,createProviderConfig:()=>L5,createOpenTelemetryTelemetryService:()=>F4,createOcaRequestHeaders:()=>A5,createOcaOAuthProvider:()=>B5,createOAuthClientCallbacks:()=>T8,createMcpTools:()=>e1,createLocalHubScheduleRuntimeHandlers:()=>uJ,createLlmsSdk:()=>e9,createInitialAccumulatedUsage:()=>u0,createInMemoryHubOwnerContext:()=>pj,createHubServerUrl:()=>lf,createHubAuthToken:()=>yJ,createHookConfigFileHooks:()=>Q8,createHookConfigFileExtension:()=>L1,createHookAuditHooks:()=>_1,createDisabledMcpToolPolicy:()=>B4,createDisabledMcpToolPolicies:()=>NJ,createDelegatedAgentConfigProvider:()=>X1,createDelegatedAgent:()=>V1,createDefaultToolsWithPreset:()=>E4,createDefaultTools:()=>S0,createDefaultMcpServerClientFactory:()=>t1,createDefaultExecutors:()=>Q1,createCoreSettingsService:()=>S$,createCoreSessionSnapshot:()=>$0,createContributionRegistry:()=>GL,createContextCompactionPrepareTurn:()=>h2,createConfiguredTelemetryService:()=>i$,createConfiguredTelemetryHandle:()=>j2,createClineTelemetryServiceMetadata:()=>UL,createClineTelemetryServiceConfig:()=>KL,createClineOAuthProvider:()=>I5,createBuiltinTools:()=>T$,createAgentTeamsTools:()=>U$,createAgentRuntime:()=>NL,createAgentHooksExtension:()=>D1,connectToHub:()=>kJ,completeClineDeviceAuth:()=>m5,clearPrivateModelsCatalogCache:()=>D5,clearLiveModelsCatalogCache:()=>h5,clearHubDiscovery:()=>Ef,captureWorkspacePathResolved:()=>HQ,captureWorkspaceInitialized:()=>r4,captureWorkspaceInitError:()=>l4,captureToolUsage:()=>t4,captureTokenUsage:()=>n4,captureTaskRestarted:()=>i4,captureTaskCreated:()=>p4,captureTaskCompleted:()=>p2,captureSubagentExecution:()=>n2,captureSkillUsed:()=>s4,captureProviderApiError:()=>i2,captureModeSwitch:()=>a4,captureMentionUsed:()=>e4,captureMentionSearchResults:()=>$6,captureMentionFailed:()=>f6,captureHookDiscovery:()=>W6,captureExtensionActivated:()=>WQ,captureDiffEditFailure:()=>o4,captureConversationTurnEvent:()=>F1,captureAuthSucceeded:()=>F0,captureAuthStarted:()=>R0,captureAuthLoggedOut:()=>g0,captureAuthFailed:()=>y0,captureAgentTeamCreated:()=>J6,captureAgentCreated:()=>v0,buildWorkspaceMetadata:()=>y8,buildTeamProgressSummary:()=>l1,buildDelegatedAgentConfig:()=>y$,bootstrapAgentTeams:()=>B1,addLocalProvider:()=>E9,accumulateUsageTotals:()=>c0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>O8,UnifiedConfigFileWatcher:()=>C$,ToolPresets:()=>Nf,TelemetryService:()=>Q2,TelemetryLoggerSink:()=>R4,TEAM_TOOL_NAMES:()=>Y1,SubprocessSandbox:()=>T1,StoredProviderSettingsSchema:()=>w1,StoredProviderSettingsEntrySchema:()=>i6,SqliteTeamStore:()=>s$,SqliteSessionStore:()=>W0,SessionVersioningService:()=>j$,SessionVersioningError:()=>Df,SessionSource:()=>Pf,SapSettingsSchema:()=>c6,SKILLS_CONFIG_DIRECTORY_NAME:()=>z8,SESSION_STATUSES:()=>d2,RpcClineAccountService:()=>G8,RemoteRuntimeHost:()=>r1,ReasoningSettingsSchema:()=>x6,RULES_CONFIG_DIRECTORY_NAME:()=>ZJ,ProviderSettingsSchema:()=>n0,ProviderSettingsManager:()=>P0,ProviderProtocolSchema:()=>k6,ProviderIdSchema:()=>A8,ProviderClientSchema:()=>m6,OpenTelemetryProvider:()=>Z2,OcaSettingsSchema:()=>d6,OPENAI_COMPATIBLE_PROVIDERS:()=>V8,OCI_HEADER_OPC_REQUEST_ID:()=>_6,NodeHubClient:()=>pf,NativeHubTransportAdapter:()=>h4,ModelCatalogSettingsSchema:()=>r6,LocalRuntimeHost:()=>Z0,Llms:()=>RL,InMemoryWorkspaceManager:()=>E1,InMemoryMcpManager:()=>r$,HubUIClient:()=>Z9,HubTransportError:()=>yf,HubSessionClient:()=>Q9,HubServerTransport:()=>X2,HubScheduleService:()=>H2,HubScheduleCommandService:()=>W2,HubRuntimeHost:()=>_0,HubCommandError:()=>c1,HookEventPayloadSchema:()=>bJ,HookEventNameSchema:()=>qJ,HookConfigFileName:()=>M1,HOOK_CONFIG_FILE_EVENT_MAP:()=>W8,HOOKS_CONFIG_DIRECTORY_NAME:()=>F6,GlobalSettingsSchema:()=>s2,GcpSettingsSchema:()=>v6,FileTeamPersistenceStore:()=>tJ,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>JW,DefaultToolNames:()=>ff,DefaultRuntimeBuilder:()=>B2,DefaultLlmsSdk:()=>L4,DEFAULT_MODELS_CATALOG_URL:()=>C6,DEFAULT_INTERNAL_OCA_BASE_URL:()=>z1,DEFAULT_INTERNAL_IDCS_URL:()=>G6,DEFAULT_INTERNAL_IDCS_SCOPES:()=>T6,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>U6,DEFAULT_HUB_PORT:()=>MH,DEFAULT_HUB_PATHNAME:()=>_H,DEFAULT_HUB_HOST:()=>DH,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>O1,DEFAULT_EXTERNAL_IDCS_URL:()=>D6,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>M6,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>h6,CoreSettingsService:()=>e0,CoreSessionService:()=>Q0,ContributionRegistry:()=>yL,ClineCore:()=>P4,ClineAccountService:()=>U8,ChatViewStateSchema:()=>i9,ChatSummarySchema:()=>$W,ChatSessionStatusSchema:()=>oJ,ChatSessionConfigSchema:()=>sJ,ChatMessageSchema:()=>fW,ChatMessageRoleSchema:()=>eJ,CORE_TELEMETRY_EVENTS:()=>g,CORE_BUILD_VERSION:()=>n9,BrowserWebSocketHubAdapter:()=>T4,BUILT_IN_PROVIDER_IDS:()=>M5,BUILT_IN_PROVIDER:()=>B8,AzureSettingsSchema:()=>u6,AwsSettingsSchema:()=>g6,AuthSettingsSchema:()=>I6,AgentTeamsRuntime:()=>d$,AgentTeam:()=>n1,Agent:()=>OL,ALL_DEFAULT_TOOL_NAMES:()=>q0});O(L,Fg);import*as RL from"@cline/llms";import{buildClineSystemPrompt as FL,ContributionRegistry as yL,createClineTelemetryServiceConfig as KL,createClineTelemetryServiceMetadata as UL,createContributionRegistry as GL,createTool as TL,emptyWorkspaceManifest as hL,formatDisplayUserInput as DL,noopBasicLogger as ML,normalizeUserInput as _L,parseUserCommandEnvelope as LL,registerDisposable as zL}from"@cline/shared";import"@cline/shared/storage";var TZ={};N(TZ,{isClineAccountActionRequest:()=>s6,executeClineAccountAction:()=>o6,RpcClineAccountService:()=>G8,ClineAccountService:()=>U8});function hy(f){if(typeof f!=="object"||f===null||!("error"in f))return;let $=f.error;return typeof $==="string"&&$.trim()?$:void 0}function GZ(f,$,J){let W=hy(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 U8{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(),P;if(j.trim())try{P=JSON.parse(j)}catch{if(!Z.ok)throw Error(GZ(Z.status,j,void 0));throw Error("Cline account response was not valid JSON")}if(!Z.ok)throw Error(GZ(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 s6(f){return f.action==="clineAccount"}async function o6(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 G8{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 hZ={};N(hZ,{createOAuthClientCallbacks:()=>T8});function T8(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}}Gf();var qZ={};N(qZ,{startClineDeviceAuth:()=>k5,refreshClineToken:()=>h8,loginClineOAuth:()=>k1,getValidClineCredentials:()=>D8,createClineOAuthProvider:()=>I5,completeClineDeviceAuth:()=>m5});var e6={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},LZ={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},b5="https://api.workos.com",w5="client_01K3A541FN8TA3EPPHTD2325AR",Dy="/auth",DZ=Array.from({length:11},(f,$)=>48801+$),My=300000,_y=30000,S1=30000,Ly=300,zy=5;class s0 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 Oy(f){let $=Date.parse(f);if(Number.isNaN($))throw Error(`Invalid expiresAt value: ${f}`);return $}function C5(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:Oy(f.expiresAt),accountId:W??void 0,email:f.userInfo.email||J.email,metadata:{provider:$,tokenType:f.tokenType,userInfo:f.userInfo}}}async function E5(f){if(!f)return{};return typeof f==="function"?await f():f}function MZ(f,$){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return $;return Math.floor(f)}async function _Z(f){await new Promise(($)=>setTimeout($,f))}function S5(f,$){if(!f.success||!f.data?.accessToken)throw Error($);return f.data}async function zZ(f,$){let J=await fetch(M$(b5,LZ.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:f}),signal:AbortSignal.timeout($?.requestTimeoutMs??S1)}),W=await J.json().catch(()=>({}));if(!J.ok)throw new s0(`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:MZ(W.expires_in,Ly),pollIntervalSeconds:MZ(W.interval,zy)}}async function OZ(f){let $=Date.now()+f.expiresInSeconds*1000,J=Math.max(1,f.initialPollIntervalSeconds);while(Date.now()<=$){let W=await fetch(M$(f.workosApiBaseUrl,LZ.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 _Z(J*1000);break}case"slow_down":{J+=1,await _Z(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new s0(H.error_description||"WorkOS authorization failed",{status:W.status,errorCode:H.error});default:throw new s0(`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 NZ(f,$,J){let W={accessToken:f.accessToken,refreshToken:f.refreshToken},H=await fetch(M$($.apiBaseUrl,e6.register),{method:"POST",headers:{"Content-Type":"application/json",...await E5($.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout($.requestTimeoutMs??S1)});if(!H.ok){let Z=await H.text().catch(()=>""),j=U1(Z);throw new s0(`Token registration failed: ${H.status}${j.message?` - ${j.message}`:""}`,{status:H.status,errorCode:j.code})}let Q=await H.json();return C5(S5(Q,"Invalid token exchange response"),J??$.provider)}async function Ny(f,$,J,W){let H={grant_type:"authorization_code",code:f,client_type:"extension",redirect_uri:$,provider:W??J.provider},Q=await fetch(M$(J.apiBaseUrl,e6.token),{method:"POST",headers:{"Content-Type":"application/json",...await E5(J.headers)},body:JSON.stringify(H),signal:AbortSignal.timeout(J.requestTimeoutMs??S1)});if(!Q.ok){let j=await Q.text().catch(()=>""),P=U1(j);throw new s0(`Token exchange failed: ${Q.status}${P.message?` - ${P.message}`:""}`,{status:Q.status,errorCode:P.code})}let Z=await Q.json();return C5(S5(Z,"Invalid token exchange response"),W??J.provider)}async function k1(f){R0(f.telemetry,f.provider??"cline");let $=f.useWorkOSDeviceAuth??!0,J=f.callbackPorts?.length?f.callbackPorts:DZ,W=f.callbackPath??Dy,H=$?null:await h0({ports:J,callbackPath:W,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),Q=H?.callbackUrl||`http://127.0.0.1:${J[0]??DZ[0]}${W}`;try{let Z;if($){let j=w5,P=await zZ(j,f);f.callbacks.onAuth({url:P.verificationUriComplete??P.verificationUri,instructions:`Enter this code in your browser: ${P.userCode}`});let X=await OZ({clientId:j,deviceCode:P.deviceCode,expiresInSeconds:P.expiresInSeconds,initialPollIntervalSeconds:P.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??S1,workosApiBaseUrl:b5,onProgress:f.callbacks.onProgress});Z=await NZ(X,f,f.provider)}else{let j=new URL(M$(f.apiBaseUrl,e6.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 G1({waitForCallback:H?.waitForCallback??(async()=>null),cancelWait:H?.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=K1(Y,{includeProvider:!0});P=B.code,X=B.provider??X}if(!P)throw Error("Missing authorization code");Z=await Ny(P,Q,f,X)}return F0(f.telemetry,f.provider??"cline"),K0(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 k5(f){return await zZ(w5,f)}async function m5(f){let $=f.provider??"cline";R0(f.telemetry,$);try{let J=await OZ({clientId:w5,deviceCode:f.deviceCode,expiresInSeconds:f.expiresInSeconds,initialPollIntervalSeconds:f.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??S1,workosApiBaseUrl:b5}),W=await NZ(J,{apiBaseUrl:f.apiBaseUrl,headers:f.headers,requestTimeoutMs:f.requestTimeoutMs,provider:f.provider},f.provider);return F0(f.telemetry,$),K0(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 h8(f,$){let J=await fetch(M$($.apiBaseUrl,e6.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await E5($.headers)},body:JSON.stringify({refreshToken:f.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout($.requestTimeoutMs??S1)});if(!J.ok){let Q=await J.text().catch(()=>""),Z=U1(Q);throw new s0(`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 C5(S5(W,"Invalid token refresh response"),H,f)}async function D8(f,$,J){if(!f)return null;let W=J?.refreshBufferMs??My,H=J?.retryableTokenGraceMs??_y;if(J?.forceRefresh!==!0&&!_$(f,W))return f;try{return await h8(f,$)}catch(Z){if(Z instanceof s0&&Z.isLikelyInvalidGrant())return g0($.telemetry,$.provider??"cline","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function I5(f){return{id:"cline",name:"Cline Account",usesCallbackServer:!(f.useWorkOSDeviceAuth??!0),async login($){return k1({...f,callbacks:$})},async refreshToken($){return h8($,f)},getApiKey($){return`workos:${$.access}`}}}Gf();var CZ={};N(CZ,{refreshOpenAICodexToken:()=>M8,openaiCodexOAuthProvider:()=>v5,normalizeOpenAICodexCredentials:()=>g5,loginOpenAICodex:()=>m1,isOpenAICodexTokenExpired:()=>x5,getValidOpenAICodexCredentials:()=>_8,OPENAI_CODEX_OAUTH_CONFIG:()=>o});import{nanoid as qy}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 fJ 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 by(f,$,J=o.redirectUri){let W=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(!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 wy(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 W=await $.text().catch(()=>""),H=U1(W);throw new fJ(`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 fJ)throw $;return{type:"failed"}}}async function Cy(f="pi"){let{verifier:$,challenge:J}=await H6(),W=qy(32),H=new URL(o.authorizationEndpoint);return H.searchParams.set("response_type","code"),H.searchParams.set("client_id",o.clientId),H.searchParams.set("redirect_uri",o.redirectUri),H.searchParams.set("scope",o.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 Ey(){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 bZ(f,$){let J=$?Rf($):Rf(f),W=J?J:Rf(f),Q=W?.[o.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 P=Z[0];if(typeof P?.id==="string"&&P.id.length>0)return P.id}let j=W?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return null}function wZ(f,$){let J=bZ(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 m1(f){R0(f.telemetry,"openai-codex");let $=Ey(),{verifier:J,state:W,url:H}=await Cy(f.originator),Q=await h0({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 G1({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 V=await f.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),Y=K1(V,{allowHashCodeState:!0});if(Y.state&&Y.state!==W)throw Error("State mismatch");Z=Y.code}if(!Z)throw Error("Missing authorization code");let P=await by(Z,J,$.redirectUri);if(P.type!=="success")throw Error("Token exchange failed");let X=wZ(P);return F0(f.telemetry,"openai-codex"),K0(f.telemetry,{id:X.accountId,email:X.email,provider:"openai-codex"}),X}catch(j){throw y0(f.telemetry,"openai-codex",j instanceof Error?j.message:String(j)),j}finally{Q.close()}}async function M8(f,$){let J=await wy(f);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=wZ(J,$);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function _8(f,$){if(!f)return null;let J=$?.refreshBufferMs??o.refreshBufferMs,W=$?.retryableTokenGraceMs??o.retryableTokenGraceMs;if($?.forceRefresh!==!0&&!_$(f,J))return f;try{return await M8(f.refresh,f)}catch(Q){if(Q instanceof fJ&&Q.isLikelyInvalidGrant())return g0($?.telemetry,"openai-codex","invalid_grant"),null;if(f.expires-Date.now()>W)return f;return null}}function x5(f,$=o.refreshBufferMs){return _$(f,$)}function g5(f){let $=f.accountId??bZ(f.access);if(!$)throw Error("Failed to extract accountId from token");return{...f,accountId:$,metadata:{...f.metadata??{},provider:"openai-codex"}}}var v5={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login(f){return m1({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 xP={};N(xP,{ClineCore:()=>P4});function EZ(f){if(f===!0)return{};if(!f)return;return f}function SZ(f){if(f==="user")return"global";return f}class u5{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 kZ(f){let{host:$}=f;return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),H=await $.startSession({source:J.source?.trim()||Pf.CLI,interactive:!1,config:{providerId:b1(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:my(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:ky(H)}},async abortSession(J){return await $.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function $J(f){let $=Sy(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 Sy(f,$){if(!f)return;return{ingestEvent:(J)=>{$.ingestEvent(J)}}}function ky(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 my(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}var Wj={};N(Wj,{createCoreSettingsService:()=>S$,CoreSettingsService:()=>e0});import{existsSync as n5}from"node:fs";import{basename as fj,isAbsolute as VK,relative as YK}from"node:path";var aZ={};N(aZ,{resolveWorkflowsConfigSearchPaths:()=>E8,resolveSkillsConfigSearchPaths:()=>w8,resolveRulesConfigSearchPaths:()=>C8,parseWorkflowConfigFromMarkdown:()=>b8,parseSkillConfigFromMarkdown:()=>N8,parseRuleConfigFromMarkdown:()=>q8,createWorkflowsConfigDefinition:()=>m8,createUserInstructionConfigService:()=>o0,createSkillsConfigDefinition:()=>S8,createRulesConfigDefinition:()=>k8,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>O8,UnifiedConfigFileWatcher:()=>C$,SKILLS_CONFIG_DIRECTORY_NAME:()=>z8,RULES_CONFIG_DIRECTORY_NAME:()=>ZJ});import{createHash as Iy}from"node:crypto";import{watch as xy}from"node:fs";import{readdir as gy,readFile as vy}from"node:fs/promises";import{join as uy}from"node:path";function cy(f){return Iy("sha1").update(f).digest("hex")}function xZ(f){return Boolean(f&&typeof f==="object"&&"code"in f)}function mZ(f){return xZ(f)&&f.code==="ENOENT"}function IZ(f){return xZ(f)&&(f.code==="EACCES"||f.code==="EPERM")}class C${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=xy($,()=>{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(!mZ(J)&&!IZ(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 P=await vy(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:cy(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 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 gy(f,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:f,fileName:J.name,filePath:uy(f,J.name)})).sort((J,W)=>J.fileName.localeCompare(W.fileName))}catch($){if(mZ($)||IZ($))return[];throw $}}}import{readdir as c5,readFile as dy,stat as gZ}from"node:fs/promises";import{basename as E$,dirname as ry,extname as d5,join as Tf}from"node:path";import{RULES_CONFIG_DIRECTORY_NAME as ZJ,resolveRulesConfigSearchPaths as ly,resolveSkillsConfigSearchPaths as py,resolveWorkflowsConfigSearchPaths as iy,SKILLS_CONFIG_DIRECTORY_NAME as z8,WORKFLOWS_CONFIG_DIRECTORY_NAME as O8}from"@cline/shared/storage";import ny from"yaml";var JJ="SKILL.md",ay="managed.json",ty=new Set([".md",".markdown",".txt"]);function r5(f){return f.trim().toLowerCase()}function L8(f){let $=f;return $?.code==="ENOENT"||$?.code==="EACCES"||$?.code==="EPERM"}function WJ(f){return ty.has(d5(f).toLowerCase())}async function l5(f){try{let $=await c5(f,{withFileTypes:!0}),J=[];for(let W of $){if(!W.isDirectory())continue;let H=Tf(f,W.name),Q=Tf(H,ay);try{let Z=await dy(Q,"utf8"),j=JSON.parse(Z);if(j&&typeof j==="object")J.push(H)}catch(Z){if(L8(Z))continue;if(Z?.name==="SyntaxError")continue;throw Z}}return J.sort((W,H)=>W.localeCompare(H))}catch($){if(L8($))return[];throw $}}function p5(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=ny.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 HJ(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 I1(f,$){if(f===void 0||f===null)return;if(typeof f!=="boolean")throw Error(`Frontmatter field '${$}' must be a boolean.`);return f}function N8(f,$){let{data:J,body:W,parseError:H}=p5(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=HJ(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing skill name.");return{name:j,description:HJ(J.description,"description",!1),disabled:I1(J.disabled,"disabled")??(I1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function q8(f,$){let{data:J,body:W,parseError:H}=p5(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=HJ(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing rule name.");return{name:Z,disabled:I1(J.disabled,"disabled")??(I1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function b8(f,$){let{data:J,body:W,parseError:H}=p5(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=HJ(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing workflow name.");return{name:Z,disabled:I1(J.disabled,"disabled")??(I1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function w8(f){return py(f)}function C8(f){return ly(f)}function E8(f){return iy(f)}async function vZ(f){if(E$(f)===".cline"){let $=await l5(f);return(await Promise.all($.map((W)=>vZ(Tf(W,z8))))).flat()}try{let $=await c5(f,{withFileTypes:!0}),J=[];for(let W of $){if(W.isFile()&&W.name===JJ){J.push({directoryPath:f,fileName:W.name,filePath:Tf(f,W.name)});continue}if(W.isDirectory())J.push({directoryPath:Tf(f,W.name),fileName:JJ,filePath:Tf(f,W.name,JJ)})}return J}catch($){if(L8($))return[];throw $}}async function QJ(f){if(E$(f)===".cline"){let $=await l5(f);return(await Promise.all($.map((W)=>QJ(Tf(W,"rules.md"))))).flat()}try{if((await gZ(f)).isFile())return[{directoryPath:ry(f),fileName:E$(f),filePath:f}]}catch($){if(!L8($))throw $}try{let J=(await c5(f,{withFileTypes:!0})).filter((H)=>H.isFile()&&WJ(H.name)).map((H)=>({directoryPath:f,fileName:H.name,filePath:Tf(f,H.name)})),W=Tf(f,"AGENTS.md");try{if((await gZ(W)).isFile()){if(!J.some((Z)=>Z.fileName==="AGENTS.md"))J.push({directoryPath:f,fileName:"AGENTS.md",filePath:W})}}catch{}return J}catch($){if(L8($))return[];throw $}}async function sy(f){if(E$(f)===".cline"){let $=await l5(f);return(await Promise.all($.map((W)=>QJ(Tf(W,O8))))).flat()}return QJ(f)}function S8(f){let $=f?.directories??w8(f?.workspacePath),J=f?.workspacePath?Tf(f.workspacePath,".cline"):void 0;return{type:"skill",directories:J?[...$,J]:$,discoverFiles:vZ,includeFile:(W)=>W===JJ,parseFile:(W)=>N8(W.content,E$(W.directoryPath)),resolveId:(W)=>r5(W.name)}}function k8(f){let $=f?.directories??C8(f?.workspacePath),J=f?.workspacePath?Tf(f.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...$,J]:$,discoverFiles:QJ,includeFile:(W,H)=>W===".clinerules"||WJ(W)||WJ(H),parseFile:(W)=>q8(W.content,E$(W.filePath,d5(W.filePath))),resolveId:(W)=>r5(W.name)}}function m8(f){let $=f?.directories??E8(f?.workspacePath),J=f?.workspacePath?Tf(f.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...$,J]:$,discoverFiles:sy,includeFile:(W)=>WJ(W),parseFile:(W)=>b8(W.content,E$(W.filePath,d5(W.filePath))),resolveId:(W)=>r5(W.name)}}function uZ(f){let $=[S8(f?.skills),k8(f?.rules),m8(f?.workflows)];return new C$($,{debounceMs:f?.debounceMs,emitParseErrors:f?.emitParseErrors})}import{truncateSplit as cZ}from"@cline/shared";function oy(f,$){if(f.description?.trim())return cZ(f.description,".");if($==="workflow")return;return cZ(f.instructions,".")}function ey(f){return f.disabled!==!0}function dZ(f,$){return[...f.getSnapshot($).entries()].map(([J,W])=>({id:J,record:W})).filter(({record:J})=>ey(J.item)).map(({id:J,record:W})=>({id:J,name:W.item.name,instructions:W.item.instructions,description:oy(W.item,$),kind:$})).sort((J,W)=>J.name.localeCompare(W.name))}function I8(f){let $=new Map;for(let J of[...dZ(f,"workflow"),...dZ(f,"skill")])if(!$.has(J.name))$.set(J.name,J);return[...$.values()].sort((J,W)=>J.name.localeCompare(W.name))}function rZ(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=I8($).find((j)=>j.name===W);return Z?`${Z.instructions}${Q}`:f}var pZ={};N(pZ,{mergeRulesForSystemPrompt:()=>g1,loadRulesForSystemPromptFromWatcher:()=>i5,listEnabledRulesFromWatcher:()=>lZ,isRuleEnabled:()=>jJ,formatRulesForSystemPrompt:()=>x1});function jJ(f){return f.disabled!==!0}function x1(f){if(f.length===0)return"";return`
|
|
182
|
+
</html>`;var XZ="a8331954c0cf48ba99b5dd223a14c6ea",AZ="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",PZ="openid offline_access",_6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",BZ="c1aba3deed5740659981a752714eba33",YZ="https://login-ext.identity.oraclecloud.com",VZ="openid offline_access",M6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",RZ="opc-request-id",xF="/auth/oca",gF=Array.from({length:11},(f,$)=>48801+$),vF=300000,uF=30000,FZ=30000,cF=600000;class L6 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 t0={internal:{clientId:XZ,idcsUrl:AZ,scopes:PZ,baseUrl:_6},external:{clientId:BZ,idcsUrl:YZ,scopes:VZ,baseUrl:M6}},P8=new Map,dF=86400000,rF=300000,lF=32,RW=new VW(dF,lF);function KZ(f){if(typeof f==="function")return f();return f??"internal"}function yZ(f){return{internal:{clientId:f?.internal?.clientId??t0.internal.clientId,idcsUrl:f?.internal?.idcsUrl??t0.internal.idcsUrl,scopes:f?.internal?.scopes??t0.internal.scopes,baseUrl:f?.internal?.baseUrl??t0.internal.baseUrl},external:{clientId:f?.external?.clientId??t0.external.clientId,idcsUrl:f?.external?.idcsUrl??t0.external.idcsUrl,scopes:f?.external?.scopes??t0.external.scopes,baseUrl:f?.external?.baseUrl??t0.external.baseUrl}}}function pF(f=Date.now()){let $=f-cF;for(let[J,W]of P8.entries())if(W.createdAt<$)P8.delete(J)}function iF(f,$,J){if(typeof f.expires_in==="number"&&f.expires_in>0)return Date.now()+f.expires_in*1000;let H=Rf($)?.exp;if(typeof H==="number"&&H>0)return H*1000;let Z=Rf(J)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return Date.now()+3600000}function UZ(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=Rf(f.id_token),Z=Rf(W),j=Q?.sub??Z?.sub,X=Q?.email??Z?.email;return{access:W,refresh:H,expires:iF(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 GZ(f,$){let J=P6(f),W=RW.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 RW.set(J,X,Date.now(),rF),X}let j=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return RW.set(J,j),j}function TZ(f){return{code:f.error,message:f.error_description}}async function nF(f){let $=P8.get(f.state);if(!$)throw Error("No PKCE verifier found for this state");P8.delete(f.state);let J=f.mode==="external"?f.config.external:f.config.internal,W=await GZ(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=TZ(Z);throw new L6(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let j=Rf(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 UZ(Z,f.mode)}function aF(f){let $=f.mode==="external"?f.config.external:f.config.internal,J=new URL(`${P6($.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 b1(f){U0(f.telemetry,"oca");let $=yZ(f.config),J=KZ(f.mode),W=f.callbackPorts?.length?f.callbackPorts:gF,H=f.callbackPath??xF,Q=f.requestTimeoutMs??FZ,Z=await h0({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=jZ(16),A=jZ(16),{verifier:P,challenge:B}=await A6();pF(),P8.set(X,{verifier:P,nonce:A,mode:J,redirectUri:j,createdAt:Date.now()});let Y=aF({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 _1({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 nF({code:R,state:U,mode:J,config:$,requestTimeoutMs:Q});return G0(f.telemetry,"oca"),D0(f.telemetry,{id:K.accountId,email:K.email,provider:"oca"}),K}catch(V){throw T0(f.telemetry,"oca",V instanceof Error?V.message:String(V)),V}finally{Z.close()}}async function B8(f,$={}){let J=yZ($.config),W=$.requestTimeoutMs??FZ,H=f.metadata?.mode,Q=H==="internal"||H==="external"?H:KZ($.mode),Z=Q==="external"?J.external:J.internal,j=await GZ(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=TZ(P);throw new L6(`Token refresh failed: ${A.status}${B.message?` - ${B.message}`:""}`,{status:A.status,errorCode:B.code})}return UZ(P,Q,f)}async function Y8(f,$,J){if(!f)return null;let W=$?.refreshBufferMs??J?.refreshBufferMs??vF,H=$?.retryableTokenGraceMs??J?.retryableTokenGraceMs??uF;if($?.forceRefresh!==!0&&!N$(f,W))return f;try{return await B8(f,J)}catch(Z){if(Z instanceof L6&&Z.isLikelyInvalidGrant())return l0(J?.telemetry,"oca","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function FW(f={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login($){return b1({...f,callbacks:$})},async refreshToken($){return B8($,f)},getApiKey($){return $.access}}}async function h6(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 KW(f){let $=await h6(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",[RZ]:$}}var zZ={};N(zZ,{resolveProviderConfig:()=>K8,getProviderConfig:()=>C6,getLiveModelsCatalog:()=>C1,clearPublicModelsCatalogCache:()=>UK,clearPrivateModelsCatalogCache:()=>hW,clearLiveModelsCatalogCache:()=>LW,OPENAI_COMPATIBLE_PROVIDERS:()=>F8,DEFAULT_MODELS_CATALOG_URL:()=>b6});import*as ff from"@cline/llms";function yW(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 tF(f,$){let J=yW(f);if(J.length>0)return J;if(!f||typeof f!=="object")return[];let W=f,H=yW(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=yW(Q.models??Q);if(j.length>0)return j}return[]}async function O6(f,$){let J=await fetch(f,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${f}: HTTP ${J.status}`);return tF(await J.json(),$)}function _Z(f){return f.replace(/\/+$/,"")}function z6(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=_Z(Z.pathname),A=_Z(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 sF(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{...J}]))}function oF(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 eF=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:sF(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})),MZ=Object.fromEntries(eF.map((f)=>[f.id,f]));function fK(f){return MZ[f]}function $K(){return Object.fromEntries(Object.entries(MZ).filter(([,f])=>oF(f)))}function LZ(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 b6="https://models.dev/api.json",JK=600000,hZ=300000,WK=5000,w6=new Map,V8=new Map,GW=new Map,N6=new Map;async function HK(){return ff.getGeneratedProviderModels()}async function QK(f,$={},J={},W={},H={},Q={}){let Z=await HK(),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 ZK(f,$){let J=ff.resolveProviderModelCatalogKeys(f);return Object.assign({},...J.map((W)=>$[W]??{}))}function DW(f){let $=f?.trim();return $&&$.length>0?$:""}function _W(f){let $=f.apiKey?.trim()||f.accessToken?.trim();return $&&$.length>0?$:void 0}function jK(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 XK(f,$){return`${f}:${DW($.baseUrl)}:${jK(_W($)??"")}`}function AK(f){let $=f?.trim();if(!$)return;let J=Rf($),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 MW(f,$,J=WK){let W=new AbortController,H=setTimeout(()=>W.abort(),J);try{return await fetch(f,{...$,signal:W.signal})}finally{clearTimeout(H)}}function UW(f,$,J){if(J&&!f.includes($))f.push($)}function R8(f,$){let J=["streaming","tools"];return UW(J,"images",Boolean($.supportsImages)),UW(J,"prompt-cache",Boolean($.supportsPromptCache)),UW(J,"reasoning",Boolean($.supportsReasoning)),{id:f,name:$.name??f,contextWindow:$.contextWindow,maxTokens:$.maxTokens,capabilities:J,releaseDate:$.releaseDate,status:"active"}}function PK(f){let $=ff.getGeneratedModelsForProvider("openai")[f.id];if($)return{...$,id:f.id,name:f.name??$.name??f.id};return R8(f.id,{name:f.name??f.id})}async function BK(f,$){let J=await MW("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]=R8(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 YK(f,$){let J=await MW("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]=R8(j,{name:j,contextWindow:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}function VK(f){let $=DW(f);if(!$)return"http://localhost:4000";return $.endsWith("/v1")?$.slice(0,-3):$}async function RK(f,$){let W=`${VK(f.baseUrl)}/v1/model/info`,H=async(A)=>MW(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=R8(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 FK(f,$){let J=await ff.listOpenAICodexModels({accessToken:$,accountId:f.accountId??AK($),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,PK(W)]))}var OZ={baseten:BK,hicap:YK,litellm:RK,"openai-codex":FK},TW=new Map,q6=new Map;function KK(f,$){return`${f}:${DW($.baseUrl)}`}async function yK(f,$,J){let W=ff.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],H=z6(J.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!H)return{};let Q=$?.cacheTtlMs??hZ,Z=KK(f,J),j=Date.now(),X=TW.get(Z);if(X&&X.expiresAt>j)return X.data;let A=q6.get(Z);if(A)return A;let P=O6(H,f).then((B)=>{let Y=Object.fromEntries(B.map((V)=>[V,R8(V,{name:V})]));return TW.set(Z,{data:Y,expiresAt:j+Q}),Y}).finally(()=>{q6.delete(Z)});return q6.set(Z,P),P}function UK(){TW.clear(),q6.clear()}async function GK(f,$){let J=_W($);if(!J)return{};let W=OZ[f];if(!W)return{};return W($,J)}function TK(f,$,J){if(!J)return!1;if(!OZ[f])return!1;if($?.loadPrivateOnAuth===!1)return!1;return Boolean(_W(J))}async function DK(f,$,J){let W=$?.cacheTtlMs??hZ,H=XK(f,J),Q=Date.now(),Z=GW.get(H);if(Z&&Z.expiresAt>Q)return Z.data;let j=N6.get(H);if(j)return j;let X=GK(f,J).then((A)=>{return GW.set(H,{data:A,expiresAt:Q+W}),A}).finally(()=>{N6.delete(H)});return N6.set(H,X),X}async function _K(f){return ff.fetchModelsDevProviderModels(f)}async function C1(f={}){let $=f.url??b6,J=f.cacheTtlMs??JK,W=Date.now(),H=w6.get($);if(H&&H.expiresAt>W)return H.data;let Q=V8.get($);if(Q)return Q;let Z=_K($).then((j)=>{return w6.set($,{data:j,expiresAt:W+J}),j}).finally(()=>{V8.delete($)});return V8.set($,Z),Z}function LW(f){if(f){w6.delete(f),V8.delete(f);return}w6.clear(),V8.clear()}function hW(){GW.clear(),N6.clear()}function MK(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:LZ(J.capabilities)}]))}var F8=MK($K());function C6(f){let $=fK(f);if(!$||!$.baseUrl)return;return{baseUrl:$.baseUrl,modelId:$.modelId,knownModels:$.knownModels,capabilities:LZ($.capabilities)}}async function K8(f,$,J){let W=C6(f);if(!W)return;try{let H=$?.loadLatestOnInit?await C1($):void 0,Q=H?ZK(f,H):{},Z=J&&TK(f,$,J)?await DK(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 yK(f,$,X).catch(()=>({})):{},P=await QK(f,W.knownModels,Q,Z,A,J?.knownModels);return{...W,knownModels:P}}catch(H){if($?.failOnError)throw H;return W}}var y8=Sf.BUILT_IN_PROVIDER,OW=Sf.BUILT_IN_PROVIDER_IDS,zW=Sf.isBuiltInProviderId,E1=Sf.normalizeProviderId,U8=h.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),E6=h.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),S6=h.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),k6=h.object({apiKey:h.string().optional(),accessToken:h.string().optional(),refreshToken:h.string().optional(),expiresAt:h.number().int().positive().optional(),accountId:h.string().optional()}),LK=h.enum(["none","low","medium","high","xhigh"]),I6=h.object({enabled:h.boolean().optional(),effort:LK.optional(),budgetTokens:h.number().int().positive().optional()}),m6=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()}),x6=h.object({projectId:h.string().optional(),region:h.string().optional()}),g6=h.object({apiVersion:h.string().optional(),useIdentity:h.boolean().optional()}),v6=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()}),u6=h.object({mode:h.enum(["internal","external"]).optional(),usePromptCache:h.boolean().optional()}),c6=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()}),s0=h.object({provider:U8,apiKey:h.string().optional(),auth:k6.optional(),model:h.string().optional(),protocol:E6.optional(),client:S6.optional(),routingProviderId:U8.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:I6.optional(),aws:m6.optional(),gcp:x6.optional(),azure:g6.optional(),sap:v6.optional(),oca:u6.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:c6.optional()});function d6(f){return s0.parse(f)}function r6(f){return s0.safeParse(f)}function hK(f){return f.protocol==="openai-responses"||f.client==="openai"}function kf(f,$={}){let J=f.provider,W=E1(J),H=$.includeKnownModels!==!1,Q=f.reasoning?.effort||"none",Z=Q==="none"?void 0:Q,j=F8[W],X=Object.assign({},...Sf.resolveProviderModelCatalogKeys(W).map((U)=>Sf.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"?_6:M6:j?.baseUrl),Y=f.routingProviderId??(hK(f)&&W!==y8.OPENAI_NATIVE?y8.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 NW(f){let $=d6(f);return kf($)}function qW(f){let $=r6(f);if($.success)return{success:!0,config:kf($.data)};return{success:!1,error:$.error}}var G8=s0;var l6=o0.object({settings:s0,updatedAt:o0.string().datetime(),tokenSource:o0.enum(["manual","oauth","migration"]).default("manual")}),S1=o0.object({version:o0.literal(1),lastUsedProvider:o0.string().min(1).optional(),providers:o0.record(o0.string(),l6)});function e0(){return{version:1,providers:{}}}M0();var EZ={};N(EZ,{InMemoryWorkspaceManager:()=>I1});import{upsertWorkspaceInfo as qK,WorkspaceManifestSchema as bW}from"@cline/shared";var CZ={};N(CZ,{normalizeWorkspacePath:()=>O0,generateWorkspaceInfoWithDiagnostics:()=>T8,generateWorkspaceInfo:()=>k1,buildWorkspaceMetadataWithInfo:()=>wW,buildWorkspaceMetadata:()=>D8});import{basename as OK,resolve as zK}from"node:path";import{performance as wZ}from"node:perf_hooks";import{processWorkspaceInfo as bZ}from"@cline/shared";import NK from"simple-git";function O0(f){return zK(f)}async function k1(f){return(await T8(f)).info}function p6(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 T8(f){let $=O0(f),J={rootPath:$,hint:OK($)},W;try{let H=NK({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??=p6(Z)}try{let Z=(await H.revparse(["HEAD"])).trim();if(Z.length>0)J.latestGitCommitHash=Z}catch(Z){W??=p6(Z)}try{let Z=(await H.branch()).current.trim();if(Z.length>0)J.latestGitBranchName=Z}catch(Z){W??=p6(Z)}return{info:J,vcsType:"git",error:W}}catch(H){return{info:J,vcsType:"none",error:p6(H)}}}async function D8(f){let $=await k1(f);return bZ($)}async function wW(f){let $=wZ.now(),J=await T8(f),W=wZ.now()-$,H=J.info;return{workspaceInfo:H,workspaceMetadata:bZ(H),durationMs:W,vcsType:J.vcsType,initError:J.error}}class I1{manifest;listeners=new Set;constructor(f){this.manifest=bW.parse(f??{workspaces:{}})}async addWorkspacePath(f){let $=await k1(f);return this.manifest=qK(this.manifest,$),this.emit({type:"workspace_added",workspace:$}),$}async switchWorkspace(f){let $=O0(f),J=this.manifest.workspaces[$];if(J)return this.manifest=bW.parse({...this.manifest,currentWorkspacePath:$}),this.emit({type:"workspace_switched",workspace:J}),J;let W=await this.addWorkspacePath($);return this.manifest=bW.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 $=O0(f);return this.manifest.workspaces[$]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(f){for(let $ of this.listeners)$(f)}}Lf();import{createHash as wK}from"node:crypto";var SZ=new Set,kZ=new Set;function bK(f){return wK("sha256").update(f).digest("hex")}function CK(f){if(f.vcsTypes&&f.vcsTypes.length>0)return f.vcsTypes;return[f.vcsType==="git"?"git":"none"]}function IZ(f){if(!f.telemetry)return;let $=bK(f.rootPath),J=f.rootCount??1;if(!SZ.has($))SZ.add($),a4(f.telemetry,{root_count:J,vcs_types:CK(f),init_duration_ms:f.durationMs,feature_flag_enabled:f.featureFlagEnabled??!0,is_remote_workspace:f.isRemoteWorkspace});if(f.initError&&!kZ.has($)){kZ.add($);let W=Error(f.initError.message);W.name=f.initError.errorType||"Error",t4(f.telemetry,W,{fallback_to_single_root:!0,workspace_count:J})}}function SK(f){return`${f.pluginName??f.pluginPath}: ${f.message}`}function kK(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(SK).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 IK(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 mK(f,$){return EK(f,$)}function xK(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 gK(f){let $={...f.storedHeaders??{},...f.configHeaders??{}},J=f.accountId?.trim()||vK(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 vK(f){let $=f?.trim();if(!$)return;let J=Rf($),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 uK(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"?gK({sessionId:$,configHeaders:f.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:f.apiKey??Q?.auth?.accessToken??Q?.apiKey}):f.headers??Q?.headers,reasoning:IK(f,Q?.reasoning),modelCatalog:Z},X=kf(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 mZ(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=i0($.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 wW(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};IZ({telemetry:o.telemetry,rootPath:T.rootPath,workspaceInfo:T,rootCount:1,vcsType:q,durationMs:L,initError:Wf,featureFlagEnabled:!0});let c=w1({cwd:$.config.cwd,workspacePath:R,rootSessionId:J,logger:M?.logger,workspaceInfo:T}),Gf=P7(M?.hooks)?void 0:q1({rootSessionId:J,workspacePath:R,workspaceInfo:T}),E0=k$([M?.hooks,Gf]),i;if(mK(F,"plugins"))try{i=await O1({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}),kK(i.failures,i.warnings,M?.logger)}catch(U2){let r=U2 instanceof Error?U2.message:String(U2);M?.logger?.log?.(`plugin loading failed; continuing without plugins (${r})`)}let S=r5(c?[c]:void 0,r5(M?.extensions,R6(i?.extensions))),n={...$.config,...M??{},sessionId:J,hooks:E0,extensions:S,extensionContext:o,telemetry:o.telemetry},B0=uK(n,J,W,U,j),Y0=k$([n.hooks,n.checkpoint?.enabled===!0?t7({cwd:n.cwd,sessionId:J,logger:n.logger,createCheckpoint:n.checkpoint?.createCheckpoint,initialRunCount:xK($.initialMessages),readSessionMetadata:Y,writeSessionMetadata:V}):void 0]),V$={...n,providerConfig:B0,workspaceMetadata:_,hooks:Y0},$1=$.toolPolicies??n.toolPolicies??Z,y2=Kf(Q,$.capabilities),C4=y2?.requestToolApproval,Z5=y2?.toolExecutors,J1=new I1({currentWorkspacePath:T.rootPath,workspaces:{[T.rootPath]:T}});return{effectiveInput:$,config:V$,providerConfig:B0,workspaceMetadata:_,workspaceInfo:T,extensions:S,hooks:Y0,toolPolicies:$1,requestToolApproval:C4,pluginSandboxShutdown:i?.shutdown,runtimeBuilderInput:{config:V$,hooks:Y0,extensions:S,onTeamEvent:A,createSpawnTool:P,onTeamRestored:y,userInstructionService:K,configExtensions:F,toolExecutors:Z5,workspaceManager:J1,logger:V$.logger,telemetry:V$.telemetry}}}import{existsSync as n6,mkdirSync as cK,readdirSync as dK,rmdirSync as rK,rmSync as lK,unlinkSync as pK}from"node:fs";import{dirname as xZ,join as i6}from"node:path";function s(){return new Date().toISOString()}function _8(f){if(!f||!n6(f))return;try{pK(f)}catch{}}function iK(f){let $=K1(f);if($)return{rootSessionId:$.rootSessionId,fileStem:`${$.agentId}__${$.teamTaskId}`};let J=d2(f);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:f,fileStem:f}}class CW{ensureSessionsDir;constructor(f){this.ensureSessionsDir=f}sessionArtifactsDir(f){return i6(this.ensureSessionsDir(),f)}ensureSessionArtifactsDir(f){let $=this.sessionArtifactsDir(f);if(!n6($))cK($,{recursive:!0});return $}sessionMessagesPath(f){return i6(this.sessionArtifactsDir(f),`${f}.messages.json`)}sessionManifestPath(f,$=!1){let J=$?this.ensureSessionArtifactsDir(f):this.sessionArtifactsDir(f);return i6(J,`${f}.json`)}removeSessionDirIfEmpty(f){let $=this.sessionArtifactsDir(f),J=this.ensureSessionsDir();while($.startsWith(J)&&$!==J){if(!n6($)){$=xZ($);continue}try{if(dK($).length>0)break;rK($)}catch{break}$=xZ($)}}removeSessionDir(f){this.removeDir(this.sessionArtifactsDir(f))}removeDir(f){if(!n6(f))return;try{lK(f,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths(f,$,J){let{rootSessionId:W,fileStem:H}=iK(f),Q=this.sessionArtifactsDir(W);return{messagesPath:i6(Q,`${H}.messages.json`)}}}import{resolveDocumentsExtensionPath as nK}from"@cline/shared/storage";Lf();function gZ(f,$,J,W,H){if(J)o4(f.telemetry,{ulid:$,apiProvider:f.providerId,...H});else s4(f.telemetry,{ulid:$,apiProvider:f.providerId,...H});aK(f.telemetry,{workspacePath:W})}function aK(f,$){let J=nK("Hooks"),W=n0($.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())X6(f,Q,Z.global,Z.workspace)}function vZ(f,$){for(let J of $.mentions)Z6(f,J,$.matchedFiles.includes(J)?1:0,"file",!$.matchedFiles.includes(J));for(let J of $.matchedFiles)H6(f,"file",J.length);for(let J of $.ignoredMentions)Q6(f,"file","not_found",J)}var FB={};N(FB,{ProviderSettingsManager:()=>A0});import{chmodSync as yB,existsSync as P3,mkdirSync as FO,readFileSync as KO,writeFileSync as yO}from"node:fs";import{basename as UB,dirname as B3}from"node:path";import{resolveProviderSettingsPath as UO}from"@cline/shared/storage";var O={};N(O,{writeHubDiscovery:()=>FJ,writeGlobalSettings:()=>q$,withHubStartupLock:()=>KJ,verifyHubConnection:()=>J0,updateLocalProvider:()=>aJ,truncateNotificationBody:()=>D4,toggleDisabledTool:()=>Y6,toTeamProgressLifecycleEvent:()=>a1,toProviderConfig:()=>kf,toHubHealthUrl:()=>h9,toHookConfigFileName:()=>X8,summarizeUsageFromMessages:()=>G1,stopLocalHubServerGracefully:()=>m9,startLocalOAuthServer:()=>h0,startHubWebSocketServer:()=>o$,startHubServer:()=>TP,startClineDeviceAuth:()=>xW,splitCoreSessionConfig:()=>l8,spawnDetachedHubServerWithRetry:()=>r1,spawnDetachedHubServer:()=>b9,setTelemetryOptOutGlobally:()=>L7,setDisabledTools:()=>s5,setDisabledPlugin:()=>N7,sendHubCommand:()=>OA,saveLocalProviderSettings:()=>pH,saveLocalProviderOAuthCredentials:()=>tH,sanitizeSessionToken:()=>h$,safeParseSettings:()=>r6,safeCreateProviderConfig:()=>qW,runSubprocessEvent:()=>W2,runHook:()=>Q2,reviveTeamStateDates:()=>c4,restartLocalHubIfIdleAfterStartupTimeout:()=>GJ,resolveWorkspaceHubOwnerContext:()=>KX,resolveWorkflowsConfigSearchPaths:()=>x8,resolveSkillsConfigSearchPaths:()=>I8,resolveSharedHubOwnerContext:()=>Af,resolveSessionBackend:()=>WH,resolveRulesConfigSearchPaths:()=>m8,resolveProviderConfig:()=>K8,resolvePluginConfigSearchPaths:()=>H8,resolveMcpServerRegistrations:()=>K4,resolveLocalClineAuthToken:()=>sH,resolveHubUrl:()=>PH,resolveHubOwnerContext:()=>z0,resolveHubEndpointOptions:()=>gf,resolveHubBuildId:()=>Z$,resolveHooksConfigSearchPaths:()=>Z8,resolveDisabledToolNames:()=>nf,resolveDisabledPluginPaths:()=>f8,resolveDefaultMcpSettingsPath:()=>P$,resolveDefaultHubPort:()=>d1,resolveDefaultHubPathname:()=>w9,resolveDefaultHubHost:()=>q9,resolveCoreSelectedToolIds:()=>r4,resolveCompatibleLocalHubUrl:()=>Q4,resolveClineDir:()=>YX,resolveClineDataDir:()=>$4,resolveAndLoadAgentPlugins:()=>O1,resolveAgentPluginPaths:()=>b$,requestHubShutdown:()=>H4,requestDesktopToolApproval:()=>xH,rememberRecoverableLocalHubUrl:()=>j$,registerRemoteConfigSessionBlobUpload:()=>cJ,registerMcpServersFromSettingsFile:()=>$2,registerDisposable:()=>YO,refreshProviderModelsFromSource:()=>iH,refreshOpenAICodexToken:()=>N8,refreshOcaToken:()=>B8,refreshClineToken:()=>O8,readSessionCheckpointHistory:()=>_4,readRemoteConfigSessionBlobUploadMetadata:()=>NH,readHubDiscovery:()=>Bf,readGlobalSettings:()=>f0,probeHubServer:()=>Uf,probeHubConnection:()=>hA,prewarmFileIndex:()=>I4,prewarmDetachedHubServer:()=>yJ,prepareRemoteConfigCoreIntegration:()=>wH,parseWorkflowConfigFromMarkdown:()=>k8,parseUserCommandEnvelope:()=>BO,parseSkillConfigFromMarkdown:()=>E8,parseSettings:()=>d6,parseRuleConfigFromMarkdown:()=>S8,parseHookEventPayload:()=>H2,openaiCodexOAuthProvider:()=>dW,normalizeWorkspacePath:()=>O0,normalizeUserInput:()=>PO,normalizeRuntimeCapabilities:()=>Kf,normalizeProviderId:()=>E1,normalizeOpenAICodexCredentials:()=>cW,normalizeOAuthProvider:()=>nH,normalizeHubWebSocketUrl:()=>X$,noopBasicLogger:()=>AO,migrateLegacyProviderSettings:()=>q4,mergeRulesForSystemPrompt:()=>c1,mergeAgentHooks:()=>k$,makeTeamTaskSubSessionId:()=>c2,makeSubSessionId:()=>F1,loginOpenAICodex:()=>g1,loginOcaOAuth:()=>b1,loginLocalProvider:()=>aH,loginClineOAuth:()=>x1,loadOpenTelemetryAdapter:()=>eh,loadMcpSettingsFile:()=>F4,loadLlmsConfigFromFile:()=>j3,loadAgentPluginsFromPathsWithDiagnostics:()=>L0,loadAgentPluginsFromPaths:()=>K6,loadAgentPluginFromPath:()=>W8,listSessionHistoryFromBackend:()=>D9,listPluginTools:()=>r8,listLocalProviders:()=>rH,listHookConfigFiles:()=>n0,isToolDisabledGlobally:()=>h7,isTelemetryOptedOutGlobally:()=>B6,isRuleEnabled:()=>QJ,isPluginDisabledGlobally:()=>z7,isOpenAICodexTokenExpired:()=>uW,isHubReconnectableTransportError:()=>k9,isHubCommandTimeoutError:()=>UJ,isDiscoveryFilePresent:()=>RX,isClineAccountActionRequest:()=>a6,isBuiltInProviderId:()=>zW,identifyAccount:()=>D0,hasMcpSettingsFile:()=>f2,getValidOpenAICodexCredentials:()=>q8,getValidOcaCredentials:()=>Y8,getValidClineCredentials:()=>z8,getProviderConfigFields:()=>oH,getProviderConfig:()=>C6,getLocalProviderModels:()=>lH,getLiveModelsCatalog:()=>C1,getFileIndex:()=>F0,getCurrentContextSize:()=>n5,getCoreHeadlessToolNames:()=>u2,getCoreDefaultEnabledToolIds:()=>d4,getCoreBuiltinToolCatalog:()=>M$,getCoreAcpToolNames:()=>l4,getClineDefaultSystemPrompt:()=>$O,generateWorkspaceInfoWithDiagnostics:()=>T8,generateWorkspaceInfo:()=>k1,generateOcaOpcRequestId:()=>h6,formatRulesForSystemPrompt:()=>u1,formatDisplayUserInput:()=>XO,filterExtensionToolRegistrations:()=>R6,filterDisabledTools:()=>w$,filterDisabledPluginPaths:()=>V6,fetchClineRecommendedModels:()=>Q3,executeClineAccountAction:()=>t6,ensureHubWebSocketServer:()=>xJ,ensureHubServer:()=>DP,ensureDetachedHubServer:()=>UX,ensureCustomProvidersLoaded:()=>nJ,ensureCompatibleLocalHubUrl:()=>c$,enrichPromptWithMentions:()=>Z1,emptyWorkspaceManifest:()=>jO,emptyStoredProviderSettings:()=>e0,discoverPluginModulePaths:()=>Q8,deriveSubsessionStatus:()=>r2,deleteLocalProvider:()=>tJ,defineLlmsConfig:()=>Z3,createWorkflowsConfigDefinition:()=>u8,createUserInstructionConfigService:()=>$$,createToolPoliciesWithPreset:()=>x4,createTool:()=>ZO,createTeamName:()=>dJ,createSubprocessHooks:()=>qJ,createSpawnAgentTool:()=>d0,createSkillsConfigDefinition:()=>g8,createSessionHost:()=>o1,createRuntimeHost:()=>o1,createRulesConfigDefinition:()=>v8,createRemoteConfigSessionMessagesArtifactUploader:()=>qH,createProviderConfig:()=>NW,createOpenTelemetryTelemetryService:()=>T4,createOcaRequestHeaders:()=>KW,createOcaOAuthProvider:()=>FW,createOAuthClientCallbacks:()=>h8,createMcpTools:()=>J2,createLocalHubScheduleRuntimeHandlers:()=>gJ,createLlmsSdk:()=>A3,createInitialAccumulatedUsage:()=>Pf,createInMemoryHubOwnerContext:()=>VX,createHubServerUrl:()=>af,createHubAuthToken:()=>RJ,createHookConfigFileHooks:()=>A8,createHookConfigFileExtension:()=>w1,createHookAuditHooks:()=>q1,createDisabledMcpToolPolicy:()=>y4,createDisabledMcpToolPolicies:()=>OJ,createDelegatedAgentConfigProvider:()=>B1,createDelegatedAgent:()=>Y1,createDefaultToolsWithPreset:()=>g4,createDefaultTools:()=>v0,createDefaultMcpServerClientFactory:()=>e1,createDefaultExecutors:()=>j1,createCoreSettingsService:()=>x$,createCoreSessionSnapshot:()=>W0,createContributionRegistry:()=>QO,createContextCompactionPrepareTurn:()=>M2,createConfiguredTelemetryService:()=>C0,createConfiguredTelemetryHandle:()=>P2,createClineTelemetryServiceMetadata:()=>HO,createClineTelemetryServiceConfig:()=>WO,createClineOAuthProvider:()=>vW,createBuiltinTools:()=>L$,createAgentTeamsTools:()=>_$,createAgentRuntime:()=>RO,createAgentHooksExtension:()=>z1,connectToHub:()=>EJ,completeClineDeviceAuth:()=>gW,clearPrivateModelsCatalogCache:()=>hW,clearLiveModelsCatalogCache:()=>LW,clearHubDiscovery:()=>xf,captureWorkspacePathResolved:()=>y7,captureWorkspaceInitialized:()=>a4,captureWorkspaceInitError:()=>t4,captureToolUsage:()=>$6,captureTokenUsage:()=>e4,captureTaskRestarted:()=>o4,captureTaskCreated:()=>s4,captureTaskCompleted:()=>n2,captureSubagentExecution:()=>t2,captureSkillUsed:()=>J6,captureProviderApiError:()=>a2,captureModeSwitch:()=>f6,captureMentionUsed:()=>H6,captureMentionSearchResults:()=>Z6,captureMentionFailed:()=>Q6,captureHookDiscovery:()=>X6,captureExtensionActivated:()=>K7,captureDiffEditFailure:()=>W6,captureConversationTurnEvent:()=>y1,captureAuthSucceeded:()=>G0,captureAuthStarted:()=>U0,captureAuthLoggedOut:()=>l0,captureAuthFailed:()=>T0,captureAgentTeamCreated:()=>j6,captureAgentCreated:()=>p0,buildWorkspaceMetadata:()=>D8,buildTeamProgressSummary:()=>n1,buildRemoteConfigSessionBlobUploadMetadata:()=>vJ,buildDelegatedAgentConfig:()=>T$,bootstrapAgentTeams:()=>R1,addLocalProvider:()=>dH,accumulateUsageTotals:()=>Xf,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>C8,UnifiedConfigFileWatcher:()=>I$,ToolPresets:()=>Ef,TelemetryService:()=>X2,TelemetryLoggerSink:()=>G4,TEAM_TOOL_NAMES:()=>V1,SubprocessSandbox:()=>h1,StoredProviderSettingsSchema:()=>S1,StoredProviderSettingsEntrySchema:()=>l6,SqliteTeamStore:()=>e$,SqliteSessionStore:()=>Q0,SessionVersioningService:()=>Y$,SessionVersioningError:()=>zf,SessionSource:()=>Vf,SapSettingsSchema:()=>v6,SKILLS_CONFIG_DIRECTORY_NAME:()=>b8,SESSION_STATUSES:()=>l2,RpcClineAccountService:()=>L8,RemoteRuntimeHost:()=>i1,ReasoningSettingsSchema:()=>I6,RULES_CONFIG_DIRECTORY_NAME:()=>HJ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>uJ,ProviderSettingsSchema:()=>s0,ProviderSettingsManager:()=>A0,ProviderProtocolSchema:()=>E6,ProviderIdSchema:()=>U8,ProviderClientSchema:()=>S6,OpenTelemetryProvider:()=>A2,OcaSettingsSchema:()=>u6,OPENAI_COMPATIBLE_PROVIDERS:()=>F8,NodeHubClient:()=>tf,NativeHubTransportAdapter:()=>O4,ModelCatalogSettingsSchema:()=>c6,LocalRuntimeHost:()=>X0,Llms:()=>fO,InMemoryWorkspaceManager:()=>I1,InMemoryMcpManager:()=>i$,HubUIClient:()=>YH,HubTransportError:()=>Df,HubSessionClient:()=>BH,HubServerTransport:()=>Y2,HubScheduleService:()=>j2,HubScheduleCommandService:()=>Z2,HubRuntimeHost:()=>N0,HubCommandError:()=>l1,HookEventPayloadSchema:()=>NJ,HookEventNameSchema:()=>zJ,HookConfigFileName:()=>N1,HOOK_CONFIG_FILE_EVENT_MAP:()=>j8,HOOKS_CONFIG_DIRECTORY_NAME:()=>G6,GlobalSettingsSchema:()=>e2,GcpSettingsSchema:()=>x6,FileTeamPersistenceStore:()=>sJ,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>W5,DefaultToolNames:()=>Jf,DefaultRuntimeBuilder:()=>F2,DefaultLlmsSdk:()=>w4,DEFAULT_MODELS_CATALOG_URL:()=>b6,DEFAULT_HUB_PORT:()=>z9,DEFAULT_HUB_PATHNAME:()=>N9,DEFAULT_HUB_HOST:()=>O9,CoreSettingsService:()=>J$,CoreSessionService:()=>j0,ContributionRegistry:()=>JO,ClineCore:()=>V4,ClineAccountService:()=>M8,ChatViewStateSchema:()=>W3,ChatSummarySchema:()=>J5,ChatSessionStatusSchema:()=>eJ,ChatSessionConfigSchema:()=>oJ,ChatMessageSchema:()=>$5,ChatMessageRoleSchema:()=>f5,CORE_TELEMETRY_EVENTS:()=>v,CORE_BUILD_VERSION:()=>H3,BrowserWebSocketHubAdapter:()=>h4,BUILT_IN_PROVIDER_IDS:()=>OW,BUILT_IN_PROVIDER:()=>y8,AzureSettingsSchema:()=>g6,AwsSettingsSchema:()=>m6,AuthSettingsSchema:()=>k6,AgentTeamsRuntime:()=>p$,AgentTeam:()=>s1,Agent:()=>VO,ALL_DEFAULT_TOOL_NAMES:()=>k0});z(O,Xv);import*as fO from"@cline/llms";import{buildClineSystemPrompt as $O,ContributionRegistry as JO,createClineTelemetryServiceConfig as WO,createClineTelemetryServiceMetadata as HO,createContributionRegistry as QO,createTool as ZO,emptyWorkspaceManifest as jO,formatDisplayUserInput as XO,noopBasicLogger as AO,normalizeUserInput as PO,parseUserCommandEnvelope as BO,registerDisposable as YO}from"@cline/shared";import"@cline/shared/storage";var cZ={};N(cZ,{isClineAccountActionRequest:()=>a6,executeClineAccountAction:()=>t6,RpcClineAccountService:()=>L8,ClineAccountService:()=>M8});function tK(f){if(typeof f!=="object"||f===null||!("error"in f))return;let $=f.error;return typeof $==="string"&&$.trim()?$:void 0}function uZ(f,$,J){let W=tK(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 M8{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(uZ(Z.status,j,void 0));throw Error("Cline account response was not valid JSON")}if(!Z.ok)throw Error(uZ(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 a6(f){return f.action==="clineAccount"}async function t6(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 L8{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 dZ={};N(dZ,{createOAuthClientCallbacks:()=>h8});function h8(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}}Lf();var sZ={};N(sZ,{startClineDeviceAuth:()=>xW,refreshClineToken:()=>O8,loginClineOAuth:()=>x1,getValidClineCredentials:()=>z8,createClineOAuthProvider:()=>vW,completeClineDeviceAuth:()=>gW});import{getClineEnvironmentConfig as EW}from"@cline/shared";var s6={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},iZ={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},SW="https://api.workos.com",sK="/auth",rZ=Array.from({length:11},(f,$)=>48801+$),oK=300000,eK=30000,m1=30000,fy=300,$y=5;class f$ 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 Jy(f){let $=Date.parse(f);if(Number.isNaN($))throw Error(`Invalid expiresAt value: ${f}`);return $}function kW(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:Jy(f.expiresAt),accountId:W??void 0,email:f.userInfo.email||J.email,metadata:{provider:$,tokenType:f.tokenType,userInfo:f.userInfo}}}async function IW(f){if(!f)return{};return typeof f==="function"?await f():f}function lZ(f,$){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return $;return Math.floor(f)}async function pZ(f){await new Promise(($)=>setTimeout($,f))}function mW(f,$){if(!f.success||!f.data?.accessToken)throw Error($);return f.data}async function nZ(f,$){let J=await fetch(z$(SW,iZ.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:f}),signal:AbortSignal.timeout($?.requestTimeoutMs??m1)}),W=await J.json().catch(()=>({}));if(!J.ok)throw new f$(`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:lZ(W.expires_in,fy),pollIntervalSeconds:lZ(W.interval,$y)}}async function aZ(f){let $=Date.now()+f.expiresInSeconds*1000,J=Math.max(1,f.initialPollIntervalSeconds);while(Date.now()<=$){let W=await fetch(z$(f.workosApiBaseUrl,iZ.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 pZ(J*1000);break}case"slow_down":{J+=1,await pZ(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new f$(H.error_description||"WorkOS authorization failed",{status:W.status,errorCode:H.error});default:throw new f$(`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 tZ(f,$,J){let W={accessToken:f.accessToken,refreshToken:f.refreshToken},H=await fetch(z$($.apiBaseUrl,s6.register),{method:"POST",headers:{"Content-Type":"application/json",...await IW($.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout($.requestTimeoutMs??m1)});if(!H.ok){let Z=await H.text().catch(()=>""),j=D1(Z);throw new f$(`Token registration failed: ${H.status}${j.message?` - ${j.message}`:""}`,{status:H.status,errorCode:j.code})}let Q=await H.json();return kW(mW(Q,"Invalid token exchange response"),J??$.provider)}async function Wy(f,$,J,W){let H={grant_type:"authorization_code",code:f,client_type:"extension",redirect_uri:$,provider:W??J.provider},Q=await fetch(z$(J.apiBaseUrl,s6.token),{method:"POST",headers:{"Content-Type":"application/json",...await IW(J.headers)},body:JSON.stringify(H),signal:AbortSignal.timeout(J.requestTimeoutMs??m1)});if(!Q.ok){let j=await Q.text().catch(()=>""),X=D1(j);throw new f$(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let Z=await Q.json();return kW(mW(Z,"Invalid token exchange response"),W??J.provider)}async function x1(f){U0(f.telemetry,f.provider??"cline");let $=f.useWorkOSDeviceAuth??!0,J=f.callbackPorts?.length?f.callbackPorts:rZ,W=f.callbackPath??sK,H=$?null:await h0({ports:J,callbackPath:W,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),Q=H?.callbackUrl||`http://127.0.0.1:${J[0]??rZ[0]}${W}`;try{let Z;if($){let j=EW().workOsClientId,X=await nZ(j,f);f.callbacks.onAuth({url:X.verificationUriComplete??X.verificationUri,instructions:`Enter this code in your browser: ${X.userCode}`});let A=await aZ({clientId:j,deviceCode:X.deviceCode,expiresInSeconds:X.expiresInSeconds,initialPollIntervalSeconds:X.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??m1,workosApiBaseUrl:SW,onProgress:f.callbacks.onProgress});Z=await tZ(A,f,f.provider)}else{let j=new URL(z$(f.apiBaseUrl,s6.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 _1({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=T1(B,{includeProvider:!0});X=Y.code,A=Y.provider??A}if(!X)throw Error("Missing authorization code");Z=await Wy(X,Q,f,A)}return G0(f.telemetry,f.provider??"cline"),D0(f.telemetry,{id:Z.accountId,email:Z.email,provider:f.provider??"cline"}),Z}catch(Z){throw T0(f.telemetry,f.provider??"cline",Z instanceof Error?Z.message:String(Z)),Z}finally{H?.close()}}async function xW(f){return await nZ(EW().workOsClientId,f)}async function gW(f){let $=f.provider??"cline";U0(f.telemetry,$);try{let J=await aZ({clientId:EW().workOsClientId,deviceCode:f.deviceCode,expiresInSeconds:f.expiresInSeconds,initialPollIntervalSeconds:f.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??m1,workosApiBaseUrl:SW}),W=await tZ(J,{apiBaseUrl:f.apiBaseUrl,headers:f.headers,requestTimeoutMs:f.requestTimeoutMs,provider:f.provider},f.provider);return G0(f.telemetry,$),D0(f.telemetry,{id:W.accountId,email:W.email,provider:$}),W}catch(J){throw T0(f.telemetry,$,J instanceof Error?J.message:String(J)),J}}async function O8(f,$){let J=await fetch(z$($.apiBaseUrl,s6.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await IW($.headers)},body:JSON.stringify({refreshToken:f.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout($.requestTimeoutMs??m1)});if(!J.ok){let Q=await J.text().catch(()=>""),Z=D1(Q);throw new f$(`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 kW(mW(W,"Invalid token refresh response"),H,f)}async function z8(f,$,J){if(!f)return null;let W=J?.refreshBufferMs??oK,H=J?.retryableTokenGraceMs??eK;if(J?.forceRefresh!==!0&&!N$(f,W))return f;try{return await O8(f,$)}catch(Z){if(Z instanceof f$&&Z.isLikelyInvalidGrant())return l0($.telemetry,$.provider??"cline","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function vW(f){return{id:"cline",name:"Cline Account",usesCallbackServer:!(f.useWorkOSDeviceAuth??!0),async login($){return x1({...f,callbacks:$})},async refreshToken($){return O8($,f)},getApiKey($){return`workos:${$.access}`}}}Lf();var fj={};N(fj,{refreshOpenAICodexToken:()=>N8,openaiCodexOAuthProvider:()=>dW,normalizeOpenAICodexCredentials:()=>cW,loginOpenAICodex:()=>g1,isOpenAICodexTokenExpired:()=>uW,getValidOpenAICodexCredentials:()=>q8,OPENAI_CODEX_OAUTH_CONFIG:()=>e});import{nanoid as Hy}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 o6 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 Qy(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 Zy(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=D1(W);throw new o6(`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 o6)throw $;return{type:"failed"}}}async function jy(f="pi"){let{verifier:$,challenge:J}=await A6(),W=Hy(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 Xy(){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 oZ(f,$){let J=$?Rf($):Rf(f),W=J?J:Rf(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 eZ(f,$){let J=oZ(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 g1(f){U0(f.telemetry,"openai-codex");let $=Xy(),{verifier:J,state:W,url:H}=await jy(f.originator),Q=await h0({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 _1({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=T1(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 Qy(Z,J,$.redirectUri);if(X.type!=="success")throw Error("Token exchange failed");let A=eZ(X);return G0(f.telemetry,"openai-codex"),D0(f.telemetry,{id:A.accountId,email:A.email,provider:"openai-codex"}),A}catch(j){throw T0(f.telemetry,"openai-codex",j instanceof Error?j.message:String(j)),j}finally{Q.close()}}async function N8(f,$){let J=await Zy(f);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=eZ(J,$);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function q8(f,$){if(!f)return null;let J=$?.refreshBufferMs??e.refreshBufferMs,W=$?.retryableTokenGraceMs??e.retryableTokenGraceMs;if($?.forceRefresh!==!0&&!N$(f,J))return f;try{return await N8(f.refresh,f)}catch(Q){if(Q instanceof o6&&Q.isLikelyInvalidGrant())return l0($?.telemetry,"openai-codex","invalid_grant"),null;if(f.expires-Date.now()>W)return f;return null}}function uW(f,$=e.refreshBufferMs){return N$(f,$)}function cW(f){let $=f.accountId??oZ(f.access);if(!$)throw Error("Failed to extract accountId from token");return{...f,accountId:$,metadata:{...f.metadata??{},provider:"openai-codex"}}}var dW={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login(f){return g1({onAuth:f.onAuth,onPrompt:f.onPrompt,onProgress:f.onProgress,onManualCodeInput:f.onManualCodeInput})},async refreshToken(f){return N8(f.refresh,f)},getApiKey(f){return f.access}};var ZA={};N(ZA,{ClineCore:()=>V4});function $j(f){if(f===!0)return{};if(!f)return;return f}function Jj(f){if(f==="user")return"global";return f}class rW{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 Wj(f){let{host:$}=f;return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),H=await $.startSession({source:J.source?.trim()||Vf.CLI,interactive:!1,config:{providerId:E1(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:By(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:Py(H)}},async abortSession(J){return await $.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function e6(f){let $=Ay(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 Ay(f,$){if(!f)return;return{ingestEvent:(J)=>{$.ingestEvent(J)}}}function Py(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 By(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}var hj={};N(hj,{createCoreSettingsService:()=>x$,CoreSettingsService:()=>J$});import{existsSync as sW}from"node:fs";import{basename as _j,isAbsolute as gy,relative as vy}from"node:path";var yj={};N(yj,{resolveWorkflowsConfigSearchPaths:()=>x8,resolveSkillsConfigSearchPaths:()=>I8,resolveRulesConfigSearchPaths:()=>m8,parseWorkflowConfigFromMarkdown:()=>k8,parseSkillConfigFromMarkdown:()=>E8,parseRuleConfigFromMarkdown:()=>S8,createWorkflowsConfigDefinition:()=>u8,createUserInstructionConfigService:()=>$$,createSkillsConfigDefinition:()=>g8,createRulesConfigDefinition:()=>v8,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>C8,UnifiedConfigFileWatcher:()=>I$,SKILLS_CONFIG_DIRECTORY_NAME:()=>b8,RULES_CONFIG_DIRECTORY_NAME:()=>HJ});import{createHash as Yy}from"node:crypto";import{watch as Vy}from"node:fs";import{readdir as Ry,readFile as Fy}from"node:fs/promises";import{join as Ky}from"node:path";function yy(f){return Yy("sha1").update(f).digest("hex")}function Zj(f){return Boolean(f&&typeof f==="object"&&"code"in f)}function Hj(f){return Zj(f)&&f.code==="ENOENT"}function Qj(f){return Zj(f)&&(f.code==="EACCES"||f.code==="EPERM")}class I${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=Vy($,()=>{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(!Hj(J)&&!Qj(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 Fy(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:yy(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 Ry(f,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:f,fileName:J.name,filePath:Ky(f,J.name)})).sort((J,W)=>J.fileName.localeCompare(W.fileName))}catch($){if(Hj($)||Qj($))return[];throw $}}}import{readdir as lW,readFile as Uy,stat as jj}from"node:fs/promises";import{basename as m$,dirname as Gy,extname as pW,join as hf}from"node:path";import{RULES_CONFIG_DIRECTORY_NAME as HJ,resolveRulesConfigSearchPaths as Ty,resolveSkillsConfigSearchPaths as Dy,resolveWorkflowsConfigSearchPaths as _y,SKILLS_CONFIG_DIRECTORY_NAME as b8,WORKFLOWS_CONFIG_DIRECTORY_NAME as C8}from"@cline/shared/storage";import My from"yaml";var fJ="SKILL.md",Ly="managed.json",hy=new Set([".md",".markdown",".txt"]);function iW(f){return f.trim().toLowerCase()}function w8(f){let $=f;return $?.code==="ENOENT"||$?.code==="EACCES"||$?.code==="EPERM"}function $J(f){return hy.has(pW(f).toLowerCase())}async function nW(f){try{let $=await lW(f,{withFileTypes:!0}),J=[];for(let W of $){if(!W.isDirectory())continue;let H=hf(f,W.name),Q=hf(H,Ly);try{let Z=await Uy(Q,"utf8"),j=JSON.parse(Z);if(j&&typeof j==="object")J.push(H)}catch(Z){if(w8(Z))continue;if(Z?.name==="SyntaxError")continue;throw Z}}return J.sort((W,H)=>W.localeCompare(H))}catch($){if(w8($))return[];throw $}}function aW(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=My.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 JJ(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 v1(f,$){if(f===void 0||f===null)return;if(typeof f!=="boolean")throw Error(`Frontmatter field '${$}' must be a boolean.`);return f}function E8(f,$){let{data:J,body:W,parseError:H}=aW(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=JJ(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing skill name.");return{name:j,description:JJ(J.description,"description",!1),disabled:v1(J.disabled,"disabled")??(v1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function S8(f,$){let{data:J,body:W,parseError:H}=aW(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=JJ(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing rule name.");return{name:Z,disabled:v1(J.disabled,"disabled")??(v1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function k8(f,$){let{data:J,body:W,parseError:H}=aW(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=JJ(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing workflow name.");return{name:Z,disabled:v1(J.disabled,"disabled")??(v1(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function I8(f){return Dy(f)}function m8(f){return Ty(f)}function x8(f){return _y(f)}async function Xj(f){if(m$(f)===".cline"){let $=await nW(f);return(await Promise.all($.map((W)=>Xj(hf(W,b8))))).flat()}try{let $=await lW(f,{withFileTypes:!0}),J=[];for(let W of $){if(W.isFile()&&W.name===fJ){J.push({directoryPath:f,fileName:W.name,filePath:hf(f,W.name)});continue}if(W.isDirectory())J.push({directoryPath:hf(f,W.name),fileName:fJ,filePath:hf(f,W.name,fJ)})}return J}catch($){if(w8($))return[];throw $}}async function WJ(f){if(m$(f)===".cline"){let $=await nW(f);return(await Promise.all($.map((W)=>WJ(hf(W,"rules.md"))))).flat()}try{if((await jj(f)).isFile())return[{directoryPath:Gy(f),fileName:m$(f),filePath:f}]}catch($){if(!w8($))throw $}try{let J=(await lW(f,{withFileTypes:!0})).filter((H)=>H.isFile()&&$J(H.name)).map((H)=>({directoryPath:f,fileName:H.name,filePath:hf(f,H.name)})),W=hf(f,"AGENTS.md");try{if((await jj(W)).isFile()){if(!J.some((Z)=>Z.fileName==="AGENTS.md"))J.push({directoryPath:f,fileName:"AGENTS.md",filePath:W})}}catch{}return J}catch($){if(w8($))return[];throw $}}async function Oy(f){if(m$(f)===".cline"){let $=await nW(f);return(await Promise.all($.map((W)=>WJ(hf(W,C8))))).flat()}return WJ(f)}function g8(f){let $=f?.directories??I8(f?.workspacePath),J=f?.workspacePath?hf(f.workspacePath,".cline"):void 0;return{type:"skill",directories:J?[...$,J]:$,discoverFiles:Xj,includeFile:(W)=>W===fJ,parseFile:(W)=>E8(W.content,m$(W.directoryPath)),resolveId:(W)=>iW(W.name)}}function v8(f){let $=f?.directories??m8(f?.workspacePath),J=f?.workspacePath?hf(f.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...$,J]:$,discoverFiles:WJ,includeFile:(W,H)=>W===".clinerules"||$J(W)||$J(H),parseFile:(W)=>S8(W.content,m$(W.filePath,pW(W.filePath))),resolveId:(W)=>iW(W.name)}}function u8(f){let $=f?.directories??x8(f?.workspacePath),J=f?.workspacePath?hf(f.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...$,J]:$,discoverFiles:Oy,includeFile:(W)=>$J(W),parseFile:(W)=>k8(W.content,m$(W.filePath,pW(W.filePath))),resolveId:(W)=>iW(W.name)}}function Aj(f){let $=[g8(f?.skills),v8(f?.rules),u8(f?.workflows)];return new I$($,{debounceMs:f?.debounceMs,emitParseErrors:f?.emitParseErrors})}import{truncateSplit as Pj}from"@cline/shared";function zy(f,$){if(f.description?.trim())return Pj(f.description,".");if($==="workflow")return;return Pj(f.instructions,".")}function Ny(f){return f.disabled!==!0}function Bj(f,$){return[...f.getSnapshot($).entries()].map(([J,W])=>({id:J,record:W})).filter(({record:J})=>Ny(J.item)).map(({id:J,record:W})=>({id:J,name:W.item.name,instructions:W.item.instructions,description:zy(W.item,$),kind:$})).sort((J,W)=>J.name.localeCompare(W.name))}function c8(f){let $=new Map;for(let J of[...Bj(f,"workflow"),...Bj(f,"skill")])if(!$.has(J.name))$.set(J.name,J);return[...$.values()].sort((J,W)=>J.name.localeCompare(W.name))}function Yj(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=c8($).find((j)=>j.name===W);return Z?`${Z.instructions}${Q}`:f}var Rj={};N(Rj,{mergeRulesForSystemPrompt:()=>c1,loadRulesForSystemPromptFromWatcher:()=>tW,listEnabledRulesFromWatcher:()=>Vj,isRuleEnabled:()=>QJ,formatRulesForSystemPrompt:()=>u1});function QJ(f){return f.disabled!==!0}function u1(f){if(f.length===0)return"";return`
|
|
183
183
|
|
|
184
184
|
# Rules
|
|
185
185
|
${f.map((J)=>`## ${J.name}
|
|
186
186
|
${J.instructions}`).join(`
|
|
187
187
|
|
|
188
|
-
`)}`}function
|
|
188
|
+
`)}`}function c1(f,$){let J=f?.trim(),W=$?.trim();if(J&&W)return`${J}
|
|
189
189
|
|
|
190
|
-
${W}`;return J||W||void 0}function
|
|
191
|
-
<command-args>${
|
|
190
|
+
${W}`;return J||W||void 0}function Vj(f){return[...f.getSnapshot("rule").values()].map((J)=>J.item).filter(QJ).sort((J,W)=>J.name.localeCompare(W.name))}function tW(f){return u1(Vj(f))}function ZJ(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function qy(f){if(!f||f.length===0)return;let $=f.map(ZJ).filter((J)=>J.length>0);return $.length>0?new Set($):void 0}function wy(f,$,J){if(!J)return!0;let W=ZJ(f),H=ZJ($),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 d8(f,$){let J=qy($);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)=>wy(H.id,H.name,J))}function by(f,$){return d8(f,$).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,W)=>J.localeCompare(W))}function Cy(f,$,J){let W=ZJ($);if(!W)return{error:"Missing skill name."};let H=d8(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=by(f,J);return{error:A.length>0?`Skill "${$}" not found. Available skills: ${A.join(", ")}`:"No skills are currently available."}}function Ey(f,$=Promise.resolve(),J){let W=new Set,H=async(Q,Z)=>{await $;let j=Cy(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?`
|
|
191
|
+
<command-args>${P}</command-args>`:"",Y=A.description?.trim()?`Description: ${A.description.trim()}
|
|
192
192
|
|
|
193
|
-
`:"";return`<command-name>${
|
|
193
|
+
`:"";return`<command-name>${A.name}</command-name>${B}
|
|
194
194
|
<command-instructions>
|
|
195
|
-
${
|
|
196
|
-
</command-instructions>`}finally{W.delete(
|
|
195
|
+
${Y}${A.instructions}
|
|
196
|
+
</command-instructions>`}finally{W.delete(X)}};return Object.defineProperty(H,"configuredSkills",{get:()=>d8(f,J).map(({skill:Q,...Z})=>Z),enumerable:!0,configurable:!1}),H}function Fj(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:()=>tW(f.watcher)});if(f.registerSkillsTool)W.registerTool(K$(Ey(f.watcher,$,f.allowedSkillNames)));for(let H of c8(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}
|
|
197
197
|
|
|
198
|
-
${Z}`:H.instructions}})}}}class
|
|
199
|
-
${
|
|
198
|
+
${Z}`:H.instructions}})}}}class Kj{watcher;ready;stopped=!1;constructor(f){this.watcher=Aj(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 c8(this.watcher)}resolveRuntimeSlashCommand(f){return Yj(f,this.watcher)}hasConfiguredSkills(f){return d8(this.watcher,f).length>0}createExtension(f){return Fj({...f,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function $$(f){return new Kj(f)}import{readFile as Sy,writeFile as ky}from"node:fs/promises";import Gj from"yaml";function Iy(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=Gj.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:H,hadFrontmatter:!0}}function Uj(f,$){return`---
|
|
199
|
+
${Gj.stringify(f).trimEnd()}
|
|
200
200
|
---
|
|
201
|
-
${$}`}function PK(f,$){let{data:J,body:W,hadFrontmatter:H}=jK(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 tZ(J,W)}return J.disabled=!0,tZ(J,W)}async function oZ({filePath:f,enabled:$}){let J=await QK(f,"utf8"),W=PK(J,$);return await ZK(f,W),{filePath:f,enabled:$,disabled:!$}}G0();var eZ={};N(eZ,{listPluginTools:()=>g8});G0();function XK(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 g8(f){let $=O$({workspacePath:f.workspacePath,cwd:f.cwd}),J=rf(f.disabledToolNames),W=[];for(let H of $){let Q=await T0([H],{cwd:f.cwd,providerId:f.providerId,modelId:f.modelId});for(let Z of Q.plugins)for(let j of XK(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 a5(f,$){if(!$)return"global";let J=YK($,f);return!J.startsWith("..")&&!VK(J)?"workspace":"global"}function XJ(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 Jj(f){return f.workspaceRoot?.trim()||f.cwd?.trim()||""}async function $j(f,$){if(f.userInstructionService)return await $(f.userInstructionService);let J=Jj(f);if(!J)return await $(void 0);let W=o0({skills:{workspacePath:J},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await W.start(),await $(W)}finally{W.stop()}}function BK(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 e0{async list(f={}){return await $j(f,async($)=>{let J=Jj(f),W=[],H=[],Q=[],Z=[];if($){for(let j of $.listRecords("workflow")){let P=j.item;W.push({id:j.id,name:P.name,path:j.filePath,enabled:P.disabled!==!0,kind:"workflow",source:a5(j.filePath,J),description:P.instructions,toggleable:!1})}for(let j of $.listRecords("rule")){let P=j.item;H.push({id:j.id,name:P.name,path:j.filePath,enabled:P.disabled!==!0,kind:"rule",source:a5(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:a5(j.filePath,J),description:P.description,toggleable:!0})}}if(J)try{for(let j of await g8({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:XJ(W.filter((j)=>n5(j.path))),rules:XJ(H.filter((j)=>n5(j.path))),skills:XJ(Q.filter((j)=>n5(j.path))),tools:XJ(Z)}})}async toggle(f){if(f.type==="skills")return await $j(f,async($)=>{let J=BK($,f),W=J?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${f.id??f.name??fj(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??fj(f.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await oZ({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)j6(f.name);else AQ(f.name,!f.enabled);return{snapshot:await this.list(f),changedTypes:["tools"]}}throw Error(`Settings type '${f.type}' does not support toggles.`)}}function S$(){return new e0}function Hj(f){return{async list($){let J=f;if(J.listSettings)return await J.listSettings($);return await S$().list($)},async toggle($){let J=f;if(J.toggleSetting)return await J.toggleSetting($);return await S$().toggle($)}}}function Qj(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 Zj={};N(Zj,{splitCoreSessionConfig:()=>v8});function v8(f){let{hooks:$,logger:J,telemetry:W,extensionContext:H,extraTools:Q,extensions:Z,onTeamEvent:j,onConsecutiveMistakeLimitReached:P,checkpoint:X,compaction:V,...Y}=f,B={};if($)B.hooks=$;if(J)B.logger=J;if(W)B.telemetry=W;if(H)B.extensionContext=H;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 jj(f){let $=f.config;return"providerId"in $?{...f,config:{...$,...AK(f.localRuntime)},localRuntime:f.localRuntime}:f}function t5(f,$={}){let J=v8(f.config),W=Vf($.defaultCapabilities,f.capabilities),H=RK(J.localRuntime,f.localRuntime),Q=$.withExtensionContext?.(H?.extensionContext);if(Q)H={...H??{},extensionContext:Q};return{...f,...J,...H?{localRuntime:H}:{},...W?{capabilities:W}:{}}}function AK(f){if(!f)return{};let{modelCatalogDefaults:$,userInstructionService:J,configExtensions:W,onTeamRestored:H,...Q}=f;return Q}function RK(...f){let $={};for(let J of f)if(J)Object.assign($,J);return Object.keys($).length>0?$:void 0}Gf();function Pj(f){let $=f.input.config.telemetry??f.telemetry;if(!$)return;$.capture({event:g.SESSION.STARTED,properties:{sessionId:f.sessionId,source:f.input.source??Pf.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 u8(f){return!!f&&typeof f==="object"&&!Array.isArray(f)}function s5(f){let $=f?.trim();return $?$:void 0}function FK(f,$){let J=f?.trim();if(!J)return $;let W=Date.parse(J);if(!Number.isFinite(W))return $;return new Date(W).toISOString()}function Xj(f,$){return new Date(new Date(f).getTime()+Math.max(0,Math.floor($))*1000).toISOString()}function Vj(f,$){return new Date(new Date(f).getTime()-Math.max(0,Math.floor($))*1000).toISOString()}function yK(f,$){if(!f)return $;return new Date(f).getTime()>=new Date($).getTime()?f:$}function KK(f,$){let J=f.eventId.trim(),W=f.eventType.trim(),H=f.source.trim(),Q=s5(f.subject),Z=s5(f.dedupeKey)??`${W}:${H}:${Q??J}`;return{eventId:J,eventType:W,source:H,subject:Q,occurredAt:FK(f.occurredAt,$),workspaceRoot:s5(f.workspaceRoot),payload:u8(f.payload)?f.payload:void 0,attributes:u8(f.attributes)?f.attributes:void 0,dedupeKey:Z}}function o5(f,$){if(!$)return;let J=$.split("."),W=f;for(let H of J){if(!u8(W))return;W=W[H]}return W}function UK(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=o5(J,$);if(W!==void 0)return W;if(f.attributes){let H=o5(f.attributes,$);if(H!==void 0)return H}if(f.payload)return o5(f.payload,$);return}function VJ(f,$){if(Array.isArray($))return $.some((J)=>VJ(f,J));if(Array.isArray(f))return f.some((J)=>VJ(J,$));if(u8($)){if(!u8(f))return!1;return Object.entries($).every(([J,W])=>VJ(f[J],W))}return Object.is(f,$)}function GK(f,$){if(!$||Object.keys($).length===0)return!0;return Object.entries($).every(([J,W])=>VJ(UK(f,J),W))}class e5{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=KK(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 V of H){if(!GK(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,W.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(W.record.eventId,{status:P,matchedSpecCount:Z.length,queuedRunCount:j.length,suppressedCount:Q.filter((V)=>V.reason!=="filter_mismatch").length});let X=this.store.getEventLog(W.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:W.record.eventId,eventType:W.record.eventType,status:P,matchedSpecCount:Z.length,queuedRunCount:j.length}),{event:X??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 P=this.store.findQueuedEventRunForDedupe({specId:f.specId,dedupeKey:W});if(P){let X=yK(P.scheduledFor,Xj(J,H)),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:W,sinceIso:Vj(J,Q)}))return{reason:"dedupe_window"};let Z=f.cooldownSeconds??0;if(Z>0&&this.store.hasRecentEventRunForSpec({specId:f.specId,sinceIso:Vj(J,Z)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"event",triggerEventId:$.eventId,scheduledFor:H>0?Xj(J,H):J}),reason:"dedupe_window"}}}class c8{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 zK}from"node:path";import{buildClineSystemPrompt as OK}from"@cline/shared";import{nowIso as Yj}from"@cline/shared/db";import{mkdirSync as TK,writeFileSync as hK}from"node:fs";import{join as DK}from"node:path";import{resolveCronReportsDir as MK}from"@cline/shared/storage";function f$(f){if(/[:#\n]/.test(f)||f.includes('"'))return JSON.stringify(f);return f}function k$(f,$){if($===void 0||$===null)return;return`${f}: ${f$($)}`}function _K(f,$,J){let W=[`runId: ${f$(f.runId)}`,`specId: ${f$($.specId)}`,`externalId: ${f$($.externalId)}`,`title: ${f$($.title)}`,`triggerKind: ${f$(f.triggerKind)}`,`status: ${f$(f.status)}`,`sourcePath: ${f$($.sourcePath)}`],H=[k$("sessionId",f.sessionId),k$("startedAt",f.startedAt),k$("completedAt",f.completedAt),k$("triggerEventId",f.triggerEventId),k$("triggerEventType",J?.eventType),k$("triggerEventSource",J?.source),k$("triggerEventSubject",J?.subject)];for(let Q of H)if(Q)W.push(Q);return`---
|
|
201
|
+
${$}`}function my(f,$){let{data:J,body:W,hadFrontmatter:H}=Iy(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 Uj(J,W)}return J.disabled=!0,Uj(J,W)}async function Tj({filePath:f,enabled:$}){let J=await Sy(f,"utf8"),W=my(J,$);return await ky(f,W),{filePath:f,enabled:$,disabled:!$}}M0();var Dj={};N(Dj,{listPluginTools:()=>r8});M0();function xy(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 r8(f){let $=b$({workspacePath:f.workspacePath,cwd:f.cwd}),J=nf(f.disabledToolNames),W=[];for(let H of $){let Q=await L0([H],{cwd:f.cwd,providerId:f.providerId,modelId:f.modelId});for(let Z of Q.plugins)for(let j of xy(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 oW(f,$){if(!$)return"global";let J=vy($,f);return!J.startsWith("..")&&!gy(J)?"workspace":"global"}function jJ(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 Lj(f){return f.workspaceRoot?.trim()||f.cwd?.trim()||""}async function Mj(f,$){if(f.userInstructionService)return await $(f.userInstructionService);let J=Lj(f);if(!J)return await $(void 0);let W=$$({skills:{workspacePath:J},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await W.start(),await $(W)}finally{W.stop()}}function uy(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 Mj(f,async($)=>{let J=Lj(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:oW(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:oW(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:oW(j.filePath,J),description:X.description,toggleable:!0})}}if(J)try{for(let j of await r8({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:jJ(W.filter((j)=>sW(j.path))),rules:jJ(H.filter((j)=>sW(j.path))),skills:jJ(Q.filter((j)=>sW(j.path))),tools:jJ(Z)}})}async toggle(f){if(f.type==="skills")return await Mj(f,async($)=>{let J=uy($,f),W=J?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${f.id??f.name??_j(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??_j(f.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await Tj({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)Y6(f.name);else O7(f.name,!f.enabled);return{snapshot:await this.list(f),changedTypes:["tools"]}}throw Error(`Settings type '${f.type}' does not support toggles.`)}}function x$(){return new J$}function Oj(f){return{async list($){let J=f;if(J.listSettings)return await J.listSettings($);return await x$().list($)},async toggle($){let J=f;if(J.toggleSetting)return await J.toggleSetting($);return await x$().toggle($)}}}function zj(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 Nj={};N(Nj,{splitCoreSessionConfig:()=>l8});function l8(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 qj(f){let $=f.config;return"providerId"in $?{...f,config:{...$,...cy(f.localRuntime)},localRuntime:f.localRuntime}:f}function eW(f,$={}){let J=l8(f.config),W=Kf($.defaultCapabilities,f.capabilities),H=dy(J.localRuntime,f.localRuntime),Q=$.withExtensionContext?.(H?.extensionContext);if(Q)H={...H??{},extensionContext:Q};return{...f,...J,...H?{localRuntime:H}:{},...W?{capabilities:W}:{}}}function cy(f){if(!f)return{};let{modelCatalogDefaults:$,userInstructionService:J,configExtensions:W,onTeamRestored:H,...Q}=f;return Q}function dy(...f){let $={};for(let J of f)if(J)Object.assign($,J);return Object.keys($).length>0?$:void 0}Lf();function wj(f){let $=f.input.config.telemetry??f.telemetry;if(!$)return;$.capture({event:v.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 p8(f){return!!f&&typeof f==="object"&&!Array.isArray(f)}function f9(f){let $=f?.trim();return $?$:void 0}function ry(f,$){let J=f?.trim();if(!J)return $;let W=Date.parse(J);if(!Number.isFinite(W))return $;return new Date(W).toISOString()}function bj(f,$){return new Date(new Date(f).getTime()+Math.max(0,Math.floor($))*1000).toISOString()}function Cj(f,$){return new Date(new Date(f).getTime()-Math.max(0,Math.floor($))*1000).toISOString()}function ly(f,$){if(!f)return $;return new Date(f).getTime()>=new Date($).getTime()?f:$}function py(f,$){let J=f.eventId.trim(),W=f.eventType.trim(),H=f.source.trim(),Q=f9(f.subject),Z=f9(f.dedupeKey)??`${W}:${H}:${Q??J}`;return{eventId:J,eventType:W,source:H,subject:Q,occurredAt:ry(f.occurredAt,$),workspaceRoot:f9(f.workspaceRoot),payload:p8(f.payload)?f.payload:void 0,attributes:p8(f.attributes)?f.attributes:void 0,dedupeKey:Z}}function $9(f,$){if(!$)return;let J=$.split("."),W=f;for(let H of J){if(!p8(W))return;W=W[H]}return W}function iy(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=$9(J,$);if(W!==void 0)return W;if(f.attributes){let H=$9(f.attributes,$);if(H!==void 0)return H}if(f.payload)return $9(f.payload,$);return}function XJ(f,$){if(Array.isArray($))return $.some((J)=>XJ(f,J));if(Array.isArray(f))return f.some((J)=>XJ(J,$));if(p8($)){if(!p8(f))return!1;return Object.entries($).every(([J,W])=>XJ(f[J],W))}return Object.is(f,$)}function ny(f,$){if(!$||Object.keys($).length===0)return!0;return Object.entries($).every(([J,W])=>XJ(iy(f,J),W))}class J9{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=py(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(!ny(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=ly(X.scheduledFor,bj(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:Cj(J,Q)}))return{reason:"dedupe_window"};let Z=f.cooldownSeconds??0;if(Z>0&&this.store.hasRecentEventRunForSpec({specId:f.specId,sinceIso:Cj(J,Z)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"event",triggerEventId:$.eventId,scheduledFor:H>0?bj(J,H):J}),reason:"dedupe_window"}}}class i8{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 $U}from"node:path";import{buildClineSystemPrompt as JU}from"@cline/shared";import{nowIso as Ej}from"@cline/shared/db";import{mkdirSync as ay,writeFileSync as ty}from"node:fs";import{join as sy}from"node:path";import{resolveCronReportsDir as oy}from"@cline/shared/storage";function W$(f){if(/[:#\n]/.test(f)||f.includes('"'))return JSON.stringify(f);return f}function g$(f,$){if($===void 0||$===null)return;return`${f}: ${W$($)}`}function ey(f,$,J){let W=[`runId: ${W$(f.runId)}`,`specId: ${W$($.specId)}`,`externalId: ${W$($.externalId)}`,`title: ${W$($.title)}`,`triggerKind: ${W$(f.triggerKind)}`,`status: ${W$(f.status)}`,`sourcePath: ${W$($.sourcePath)}`],H=[g$("sessionId",f.sessionId),g$("startedAt",f.startedAt),g$("completedAt",f.completedAt),g$("triggerEventId",f.triggerEventId),g$("triggerEventType",J?.eventType),g$("triggerEventSource",J?.source),g$("triggerEventSubject",J?.subject)];for(let Q of H)if(Q)W.push(Q);return`---
|
|
202
202
|
${W.join(`
|
|
203
203
|
`)}
|
|
204
204
|
---
|
|
205
|
-
`}function
|
|
205
|
+
`}function fU(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
|
|
206
206
|
|
|
207
207
|
${W.join(`
|
|
208
208
|
`)}
|
|
@@ -221,17 +221,17 @@ ${W.join(`
|
|
|
221
221
|
${J.join(`
|
|
222
222
|
`)}
|
|
223
223
|
`)}return $.join(`
|
|
224
|
-
`)}function
|
|
225
|
-
${
|
|
226
|
-
`)}class
|
|
224
|
+
`)}function W9(f){let $=oy(f.specs);ay($,{recursive:!0});let J=sy($,`${f.run.runId}.md`),W=`${ey(f.run,f.spec,f.data.triggerEvent)}
|
|
225
|
+
${fU(f.data)}`;return ty(J,W,"utf8"),J}class H9{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 WU=15000,HU=90,Sj=["rules","skills","plugins"];function QU(f,$){return new Set(f.extensions??Sj).has($)}function ZU(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 jU(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(`
|
|
226
|
+
`)}class Q9 extends Error{constructor(f){super(f);this.name="TimeoutError"}}async function XU(f,$){if($<=0)return f;let J,W=new Promise((H,Q)=>{J=setTimeout(()=>{Q(new Q9("cron run timed out"))},$)});try{return await Promise.race([f,W])}finally{if(J)clearTimeout(J)}}class n8{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 H9(f.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,(f.claimLeaseSeconds??HU)*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??WU);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:Ej(),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 XU(V,R)).result,F=Date.now(),y=W9({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,Ej())}catch(P){let B=P instanceof Q9;if(Z&&B)try{await this.options.runtimeHandlers.abortSession(Z)}catch{}let Y=P instanceof Error?P.message:String(P),V=Date.now(),R=W9({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}
|
|
227
227
|
|
|
228
228
|
Trigger event:
|
|
229
|
-
${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=
|
|
229
|
+
${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=jU(f.notesDirectory),Q=c1(void 0,H),Z=await D8($),j=JU({ide:"Cline Cron",workspaceRoot:$,workspaceName:$U($),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?c1(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:ZU(f,Z),configExtensions:Sj.filter((j)=>QU(f,j))}}}import{existsSync as bU,readdirSync as CU,readFileSync as EU,statSync as SU}from"node:fs";import{relative as kU}from"node:path";import{resolveCronSpecsDir as IU}from"@cline/shared/storage";function a8(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 AU=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],Ij=["sun","mon","tue","wed","thu","fri","sat"];function t8(f,$,J){let W=f[$];if(typeof W!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${$+1}`);return W}function Z9(f,$){let J=f[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${$}`);return J}function j9(f){let $=f.trim().split(/\s+/);if($.length!==5)throw Error(`Invalid cron pattern "${f}": expected 5 fields, got ${$.length}`);return{minutes:a8(t8($,0,f),0,59),hours:a8(t8($,1,f),0,23),daysOfMonth:a8(t8($,2,f),1,31),months:a8(t8($,3,f),1,12,AU),daysOfWeek:a8(t8($,4,f),0,6,Ij)}}function X9(f){j9(f)}function mj(f,$,J=Date.now()){v$(f,J,$)}var kj=new Map,PU=new Map(Ij.map((f,$)=>[f,$]));function xj(f){let $=f?.trim();return $?$:void 0}function gj(f){let $=kj.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 kj.set(f,J),J}function BU(f){let $=xj(f);if(!$)return;gj($).format(new Date)}function YU(f,$){let J=gj($).formatToParts(new Date(f)),W=new Map(J.map((Z)=>[Z.type,Z.value])),H=W.get("weekday")?.toLowerCase().slice(0,3)??"",Q=PU.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 VU(f){let $=new Date(f);return{month:$.getMonth()+1,dayOfMonth:$.getDate(),dayOfWeek:$.getDay(),hour:$.getHours(),minute:$.getMinutes()}}function RU(f,$){return f.months.includes($.month)&&f.daysOfMonth.includes($.dayOfMonth)&&f.daysOfWeek.includes($.dayOfWeek)&&f.hours.includes($.hour)&&f.minutes.includes($.minute)}function FU(f,$,J){let W=j9(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(RU(W,YU(Q,J)))return Q;Q+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${f}" in timezone "${J}"`)}function v$(f,$,J){let W=xj(J);if(W)return BU(W),FU(f,$,W);let H=j9(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}=VU(Q.getTime());if(!H.months.includes(j)){let Y=H.months.find((R)=>R>j)??Z9(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)??Z9(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)??Z9(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{createHash as KU}from"node:crypto";import yU from"yaml";function UU(f){let $=f.replace(/\\/g,"/");if($.startsWith("events/")&&$.endsWith(".event.md"))return"event";if($.endsWith(".cron.md"))return"schedule";return"one_off"}function GU(f){let $=f.replace(/\r\n/g,`
|
|
230
230
|
`);if(!$.startsWith(`---
|
|
231
231
|
`))return{frontmatter:void 0,body:f};let J=$.slice(4),W=J.indexOf(`
|
|
232
232
|
---`);if(W===-1)return{frontmatter:void 0,body:f};let H=J.slice(0,W),Q=J.slice(W+4);if(Q.startsWith(`
|
|
233
|
-
`))Q=Q.slice(1);return{frontmatter:H,body:Q}}function
|
|
234
|
-
`),J.update($),J.digest("hex")}function
|
|
233
|
+
`))Q=Q.slice(1);return{frontmatter:H,body:Q}}function If(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function TU(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 B9(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return f}function DU(f){let $=B9(f);if(!$)return;let J=If($.providerId),W=If($.modelId);if(J===void 0&&W===void 0)return;return{providerId:J,modelId:W}}function _U(f){if(typeof f!=="string")return;let $=f.trim().toLowerCase();if($==="act"||$==="plan"||$==="yolo")return $;return}function uj(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 MU=new Set(k0);function LU(f){let $=uj(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((W)=>!MU.has(W));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return $}var hU=new Set(["rules","skills","plugins"]);function OU(f){let $=uj(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((W)=>!hU.has(W));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return $}function A9(f){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return;return Math.floor(f)}function P9(f){if(typeof f!=="number"||!Number.isFinite(f)||f<0)return;return Math.floor(f)}function Y9(f){if(f===null||typeof f!=="object")return JSON.stringify(f??null);if(Array.isArray(f))return`[${f.map((J)=>Y9(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)}:${Y9(W)}`).join(",")}}`}function cj(f,$){let J=KU("sha256");return J.update(Y9(f)),J.update(`
|
|
234
|
+
`),J.update($),J.digest("hex")}function zU(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var NU=["schedule","timezone"],qU=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],wU=["cwd"];function vj(f,$,J,W,H){return{externalId:f,relativePath:f,triggerKind:$,body:J,contentHash:cj(W,J),error:H}}function $0(f,$,J,W,H,Q){return{externalId:f,relativePath:$,triggerKind:J,body:W,contentHash:H,error:Q}}function dj(f){let $=f.relativePath.replace(/\\/g,"/"),J=UU($),{frontmatter:W,body:H}=GU(f.raw),Q={};if(W!==void 0&&W.trim().length>0)try{let y=yU.parse(W);if(y&&typeof y==="object"&&!Array.isArray(y))Q=y;else if(y!==null&&y!==void 0)return vj($,J,H,{},"frontmatter must be a YAML mapping")}catch(y){return vj($,J,H,{},y instanceof Error?`failed to parse frontmatter: ${y.message}`:"failed to parse frontmatter")}let Z=cj(Q,H),j=If(Q.id),X=j??$;if(J!=="schedule"){for(let y of NU)if(Q[y]!==void 0)return $0(X,$,J,H,Z,`field "${y}" is only allowed on *.cron.md specs`)}for(let y of wU)if(Q[y]!==void 0)return $0(X,$,J,H,Z,`field "${y}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let y of qU)if(Q[y]!==void 0)return $0(X,$,J,H,Z,`field "${y}" is only allowed on .event.md specs`)}let A=If(Q.prompt),P=H.trim(),B=A??(P.length>0?P:void 0);if(!B)return $0(X,$,J,H,Z,"prompt is required (frontmatter `prompt` or markdown body)");let Y=If(Q.workspaceRoot);if(!Y)return $0(X,$,J,H,Z,"workspaceRoot is required");let V,R;try{V=LU(Q.tools),R=OU(Q.extensions)}catch(y){return $0(X,$,J,H,Z,y instanceof Error?y.message:String(y))}let U=_U(Q.mode);if(Q.mode!==void 0&&U===void 0)return $0(X,$,J,H,Z,"mode must be one of: act, plan, yolo");let K={id:j,title:If(Q.title)??j??zU($),prompt:B,workspaceRoot:Y,mode:U??"yolo",systemPrompt:If(Q.systemPrompt),modelSelection:DU(Q.modelSelection),maxIterations:A9(Q.maxIterations),timeoutSeconds:A9(Q.timeoutSeconds),tools:V,notesDirectory:If(Q.notesDirectory),extensions:R,source:If(Q.source)??"user",tags:TU(Q.tags),enabled:typeof Q.enabled==="boolean"?Q.enabled:!0,metadata:B9(Q.metadata)},F;if(J==="schedule"){let y=If(Q.schedule);if(!y)return $0(X,$,J,H,Z,"schedule is required for *.cron.md specs");let D=If(Q.timezone);try{mj(y,D)}catch(T){return $0(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=If(Q.event);if(!y)return $0(X,$,J,H,Z,"event is required for .event.md specs");F={...K,triggerKind:"event",event:y,filters:B9(Q.filters),debounceSeconds:P9(Q.debounceSeconds),dedupeWindowSeconds:P9(Q.dedupeWindowSeconds),cooldownSeconds:P9(Q.cooldownSeconds),maxParallel:A9(Q.maxParallel)}}else F={...K,triggerKind:"one_off"};return{externalId:X,relativePath:$,triggerKind:J,body:H,contentHash:Z,spec:F}}function mU(f,$){return kU(f,$).replace(/\\/g,"/")}function xU(f){if(!bU(f))return[];let $=[],J=[f];while(J.length>0){let W=J.pop();if(!W)continue;let H;try{H=CU(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 V9{store;cronDir;constructor(f){this.store=f.store,this.cronDir=IU(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:[]},$=xU(this.cronDir),J=new Set;for(let H of $){let Q=mU(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=EU($,"utf8"),H=SU($).mtimeMs}catch{return}let Z=dj({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=v$(f.scheduleExpr,W,f.timezone),Q=new Date(H).toISOString();if(f.nextRunAt!==Q)this.store.updateSpecNextRunAt(f.specId,Q)}catch{}}}import{existsSync as gU,mkdirSync as vU,watch as uU}from"node:fs";import{relative as cU,resolve as dU}from"node:path";var rU=250;class R9{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor(f){this.reconciler=f.reconciler,this.debounceMs=Math.max(0,f.debounceMs??rU),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{vU(f,{recursive:!0}),this.watcher=uU(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 $=dU(this.reconciler.getCronDir(),f);if(!gU($)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=cU(this.reconciler.getCronDir(),$).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,$),await this.onReconciled()}catch($){this.onError($)}}}import{randomUUID as s8}from"node:crypto";import{asOptionalString as k,asString as t,loadSqliteDb as pU,nowIso as yf}from"@cline/shared/db";import{resolveCronDbPath as iU}from"@cline/shared/storage";var lU=[`CREATE TABLE IF NOT EXISTS cron_specs (
|
|
235
235
|
spec_id TEXT PRIMARY KEY,
|
|
236
236
|
external_id TEXT NOT NULL,
|
|
237
237
|
source_path TEXT NOT NULL UNIQUE,
|
|
@@ -322,17 +322,17 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
322
322
|
ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
|
|
323
323
|
ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
|
|
324
324
|
ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
|
|
325
|
-
ON cron_specs(source_path);`];function
|
|
325
|
+
ON cron_specs(source_path);`];function rj(f){f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec("PRAGMA foreign_keys = ON;");for(let $ of lU)f.exec($)}function AJ(f){if(!f)return;try{let $=JSON.parse(f);if($&&typeof $==="object"&&!Array.isArray($))return $}catch{}return}function F9(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 u$(f){if(typeof f==="number"&&Number.isFinite(f))return f;if(typeof f==="bigint")return Number(f);return}function H$(f){return{specId:t(f.spec_id),externalId:t(f.external_id),sourcePath:t(f.source_path),triggerKind:t(f.trigger_kind),sourceMtimeMs:u$(f.source_mtime_ms),sourceHash:k(f.source_hash),parseStatus:t(f.parse_status)==="invalid"?"invalid":"valid",parseError:k(f.parse_error),enabled:Number(f.enabled??0)===1,removed:Number(f.removed??0)===1,title:t(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:AJ(k(f.filters_json)),debounceSeconds:u$(f.debounce_seconds),dedupeWindowSeconds:u$(f.dedupe_window_seconds),cooldownSeconds:u$(f.cooldown_seconds),mode:k(f.mode),systemPrompt:k(f.system_prompt),providerId:k(f.provider_id),modelId:k(f.model_id),maxIterations:u$(f.max_iterations),timeoutSeconds:u$(f.timeout_seconds),maxParallel:u$(f.max_parallel),tools:F9(k(f.tools_json),{preserveEmpty:!0}),notesDirectory:k(f.notes_directory),extensions:F9(k(f.extensions_json),{preserveEmpty:!0}),source:k(f.source),tags:F9(k(f.tags_json)),metadata:AJ(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:t(f.created_at),updatedAt:t(f.updated_at)}}function K9(f){return{runId:t(f.run_id),specId:t(f.spec_id),specRevision:Number(f.spec_revision??1),triggerKind:t(f.trigger_kind),status:t(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:t(f.created_at),updatedAt:t(f.updated_at)}}function lj(f){return{eventId:t(f.event_id),eventType:t(f.event_type),source:t(f.source),subject:k(f.subject),occurredAt:t(f.occurred_at),receivedAt:t(f.received_at),workspaceRoot:k(f.workspace_root),dedupeKey:k(f.dedupe_key),payload:AJ(k(f.payload_json)),attributes:AJ(k(f.attributes_json)),processingStatus:t(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:t(f.created_at),updatedAt:t(f.updated_at)}}function pj(f){return f?JSON.stringify(f):null}var nU=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function ij(f){if(f===void 0)return null;if(f&&typeof f==="object")return JSON.stringify(f);return f}function aU(f,$,J,W){for(let H of nU){let Q=f[H],Z=$[H];if(ij(Q)!==ij(Z))return!0}if(J===!1&&W===!0)return!0;return!1}function tU(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function sU(f){return`hub/schedules/${f}.cron.md`}function oU(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 y9(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:oU(f)}}function nj(f){return JSON.stringify(y9(f))}function eU(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 o8{db;constructor(f={}){let $=f.dbPath??iU();this.db=pU($),rj(this.db)}close(){this.db.close?.()}getSpecBySourcePath(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get(f);return $?H$($):void 0}getSpec(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f);return $?H$($):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 $?H$($):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)=>H$(Z))}createHubSchedule(f){let $=`sched_${s8()}`,J=this.upsertSpec({externalId:$,sourcePath:sU($),triggerKind:"schedule",sourceHash:nj(f),parseStatus:"valid",spec:y9(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
|
|
326
326
|
WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
|
|
327
|
-
ORDER BY created_at ASC LIMIT 1`).get(f);return
|
|
327
|
+
ORDER BY created_at ASC LIMIT 1`).get(f);return $?H$($):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
|
|
328
328
|
WHERE ${$.join(" AND ")}
|
|
329
|
-
ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Q)
|
|
329
|
+
ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Q)=>H$(Q))}updateHubSchedule(f,$){let J=this.getHubSchedule(f);if(!J)return;let W=eU(J,$),H=this.upsertSpec({externalId:f,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:nj(W),parseStatus:"valid",spec:y9(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
|
|
330
330
|
WHERE trigger_kind = 'event'
|
|
331
331
|
AND event_type = ?
|
|
332
332
|
AND enabled = 1
|
|
333
333
|
AND removed = 0
|
|
334
334
|
AND parse_status = 'valid'
|
|
335
|
-
ORDER BY created_at ASC`).all(f).map((J)
|
|
335
|
+
ORDER BY created_at ASC`).all(f).map((J)=>H$(J))}upsertSpec(f){let $=yf(),J=this.getSpecBySourcePath(f.sourcePath),W=f.spec,H={title:W?.title??J?.title??tU(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_${s8()}`;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&&aU(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 (
|
|
336
336
|
spec_id, external_id, source_path, trigger_kind,
|
|
337
337
|
source_mtime_ms, source_hash, parse_status, parse_error,
|
|
338
338
|
enabled, removed, title, prompt, workspace_root,
|
|
@@ -355,7 +355,7 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
355
355
|
tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
|
|
356
356
|
tags_json = ?, metadata_json = ?,
|
|
357
357
|
revision = ?, updated_at = ?
|
|
358
|
-
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(
|
|
358
|
+
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(v$($.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=H$(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(v$(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_${s8()}`,j;try{j=new Date(v$(H.scheduleExpr,$,H.timezone)).toISOString()}catch{j=void 0}return this.db.prepare(`INSERT INTO cron_runs (
|
|
359
359
|
run_id, spec_id, spec_revision, trigger_kind, status,
|
|
360
360
|
scheduled_for, trigger_event_id, attempt_count,
|
|
361
361
|
created_at, updated_at
|
|
@@ -364,22 +364,22 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
364
364
|
last_run_at = ?,
|
|
365
365
|
next_run_at = ?,
|
|
366
366
|
updated_at = ?
|
|
367
|
-
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 $?
|
|
367
|
+
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 $?K9($):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 (
|
|
368
368
|
event_id, event_type, source, subject,
|
|
369
369
|
occurred_at, received_at, workspace_root, dedupe_key,
|
|
370
370
|
payload_json, attributes_json, processing_status,
|
|
371
371
|
matched_spec_count, queued_run_count, suppressed_count,
|
|
372
372
|
error, created_at, updated_at
|
|
373
|
-
) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(H,Q,Z,f.subject?.trim()||null,j,W,f.workspaceRoot?.trim()||null,f.dedupeKey?.trim()||null,
|
|
373
|
+
) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(H,Q,Z,f.subject?.trim()||null,j,W,f.workspaceRoot?.trim()||null,f.dedupeKey?.trim()||null,pj(f.payload),pj(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 $?lj($):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}
|
|
374
374
|
ORDER BY received_at DESC, created_at DESC
|
|
375
|
-
LIMIT ?`).all(...J,H).map((Z)=>
|
|
375
|
+
LIMIT ?`).all(...J,H).map((Z)=>lj(Z))}updateEventLogProcessing(f,$){return(this.db.prepare(`UPDATE cron_event_log SET
|
|
376
376
|
processing_status = ?,
|
|
377
377
|
matched_spec_count = COALESCE(?, matched_spec_count),
|
|
378
378
|
queued_run_count = COALESCE(?, queued_run_count),
|
|
379
379
|
suppressed_count = COALESCE(?, suppressed_count),
|
|
380
380
|
error = ?,
|
|
381
381
|
updated_at = ?
|
|
382
|
-
WHERE event_id = ?`).run($.status,$.matchedSpecCount??null,$.queuedRunCount??null,$.suppressedCount??null,$.error??null,
|
|
382
|
+
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)=>K9(Z))}hasRecentEventRunForDedupe(f){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
|
|
383
383
|
INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
|
|
384
384
|
WHERE r.spec_id = ?
|
|
385
385
|
AND r.trigger_kind = 'event'
|
|
@@ -397,7 +397,7 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
397
397
|
AND r.status = 'queued'
|
|
398
398
|
AND e.dedupe_key = ?
|
|
399
399
|
ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
|
|
400
|
-
LIMIT 1`).get(f.specId,f.dedupeKey);return $?
|
|
400
|
+
LIMIT 1`).get(f.specId,f.dedupeKey);return $?K9($):void 0}updateQueuedEventRunForDebounce(f){let $=yf();if((this.db.prepare(`UPDATE cron_runs SET
|
|
401
401
|
trigger_event_id = ?,
|
|
402
402
|
scheduled_for = ?,
|
|
403
403
|
updated_at = ?
|
|
@@ -406,12 +406,12 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
406
406
|
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
|
|
407
407
|
WHERE spec_id = ? AND spec_revision = ?
|
|
408
408
|
AND trigger_kind = 'one_off'
|
|
409
|
-
LIMIT 1`).get(f,$)}enqueueRun(f){let $=`crun_${
|
|
409
|
+
LIMIT 1`).get(f,$)}enqueueRun(f){let $=`crun_${s8()}`,J=yf();this.db.prepare(`INSERT INTO cron_runs (
|
|
410
410
|
run_id, spec_id, spec_revision, trigger_kind, status,
|
|
411
411
|
scheduled_for, trigger_event_id, attempt_count,
|
|
412
412
|
created_at, updated_at
|
|
413
413
|
) 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 = ?
|
|
414
|
-
WHERE spec_id = ? AND status = 'queued'`).run(
|
|
414
|
+
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
|
|
415
415
|
WHERE (
|
|
416
416
|
status = 'queued'
|
|
417
417
|
OR (
|
|
@@ -423,7 +423,7 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
423
423
|
)
|
|
424
424
|
AND (scheduled_for IS NULL OR scheduled_for <= ?)
|
|
425
425
|
ORDER BY COALESCE(scheduled_for, created_at) ASC
|
|
426
|
-
LIMIT ?`).all($,$,H);for(let j of Z){let
|
|
426
|
+
LIMIT ?`).all($,$,H);for(let j of Z){let X=t(j.run_id);if(!X)continue;let A=`cclaim_${s8()}`;if((this.db.prepare(`UPDATE cron_runs SET
|
|
427
427
|
status = 'running',
|
|
428
428
|
claim_token = ?,
|
|
429
429
|
claim_started_at = ?,
|
|
@@ -444,8 +444,8 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
444
444
|
AND claim_until_at <= ?
|
|
445
445
|
AND completed_at IS NULL
|
|
446
446
|
)
|
|
447
|
-
)`).run(
|
|
448
|
-
WHERE run_id = ? AND claim_token = ?`).run(J,
|
|
447
|
+
)`).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 = ?
|
|
448
|
+
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
|
|
449
449
|
status = ?,
|
|
450
450
|
session_id = COALESCE(?, session_id),
|
|
451
451
|
report_path = COALESCE(?, report_path),
|
|
@@ -455,7 +455,7 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
455
455
|
claim_token = NULL,
|
|
456
456
|
claim_until_at = NULL,
|
|
457
457
|
updated_at = ?
|
|
458
|
-
${W}`).run($.status,$.sessionId??null,$.reportPath??null,$.error??null,J,J,f,...$.claimToken?[$.claimToken]:[]).changes??0)>0}requeueRun(f){let $=
|
|
458
|
+
${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
|
|
459
459
|
status = 'queued',
|
|
460
460
|
claim_started_at = NULL,
|
|
461
461
|
claim_token = NULL,
|
|
@@ -467,40 +467,40 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
467
467
|
error = ?,
|
|
468
468
|
scheduled_for = COALESCE(?, scheduled_for),
|
|
469
469
|
updated_at = ?
|
|
470
|
-
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($,
|
|
471
|
-
`).trim()}function
|
|
472
|
-
`)[0]??H);return
|
|
473
|
-
`,{encoding:"utf8",mode:384}),await
|
|
474
|
-
`,"utf8");try{return await $()}finally{await uj(J)}}catch(H){if((H instanceof Error&&"code"in H?String(H.code):"")!=="EEXIST")throw H;let Z=await JG(J),j=Z?Date.now()-Date.parse(Z.acquiredAt):vj+1;if(!Z||!eU(Z.pid)||j>vj){await uj(J);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${J}`);await fG(tU)}}async function Bf(f){try{let $=await fetch(hH(f));if(!$.ok)return;return await $.json()}catch{return}}function lf(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function hH(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function ij(f){return lU(f)}import{CLINE_HUB_DEV_PORT as WG,CLINE_HUB_PORT as HG,resolveClineBuildEnv as QG}from"@cline/shared";var ZG="CLINE_HUB_HOST",jG="CLINE_HUB_PORT",PG="CLINE_HUB_PATHNAME",DH="127.0.0.1",MH=HG,_H="/hub";function nj(f){return QG(f)==="development"?WG:MH}function LH(f={}){return(f.env??process.env)[ZG]?.trim()||DH}function v1(f={}){let J=(f.env??process.env)[jG]?.trim();if(!J)return nj(f);let W=Number.parseInt(J,10);if(!Number.isInteger(W)||W<1||W>65535)return nj(f);return W}function zH(f={}){return(f.env??process.env)[PG]?.trim()||_H}function Sf(f={},$={}){return{host:f.host??LH($),port:f.port??v1($),pathname:f.pathname??zH($)}}var XG="shared:cline";function aj(f){let $=D0(f.trim());return M0(`workspace:${$||f.trim()}`)}function Qf(f=XG){return M0(f)}var TG=8000,hG=200,DG=3000,MG=100,_G="--cline-hub-daemon";function LG(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function zG(){try{let f=yG(t8(),"logs","hub-daemon.log");return BG(FG(f),{recursive:!0}),{fd:AG(f,"a"),logPath:f}}catch{return}}function s8(f){let $=f.buildId?.trim();return!!$&&$===J$()}async function OG(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await Bf(f).catch(()=>{return}))?.url)return!0;await new Promise((H)=>setTimeout(H,MG))}return!1}async function o8(f,$){if(s8(f))return;if(await e8(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await OG(f.url,DG),await Ef($).catch(()=>{return})}function NG(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return KG(new URL(`./entry.${f}`,import.meta.url))}function qG(f,$){let J=NG(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let H=RG(W).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),Z=H&&J.toLowerCase().endsWith(".ts"),j=Q?[_G]:[...Z?["--conditions=development"]:[],J];return{launcher:W,args:[...j,"--cwd",f,...LG($)],cwd:f,env:{...GG(process.env),CLINE_NO_INTERACTIVE:"1",[UG]:"1"}}}function u1(f,$={}){if(tj())return;let J=qG(f,$),W=zG();try{VG(J.launcher,J.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(W)YG(W.fd)}}function GJ(f,$={}){if(tj())return;let J=Qf(),W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),H=Sf($),Q=lf(H.host,H.port,H.pathname);Zf(J.discoveryPath).then(async(Z)=>{if(Z?.url){let V=await Bf(Z.url);if(V?.url&&s8(V)&&await f0(V.url,{authToken:Z.authToken}))return;if(V?.url)await o8({...V,authToken:Z.authToken},J.discoveryPath);else await Ef(J.discoveryPath).catch(()=>{return})}let j=await Bf(Q);if(j?.url)await o8(j,J.discoveryPath);let X=!W&&H.port!==0?{...H,port:0}:H;u1(f,X)}).catch(()=>{})}async function sj(f,$={}){let J=Qf(),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=Sf($),Z=lf(Q.host,Q.port,Q.pathname),j=(A)=>{if(!W)W$(A.url,A.authToken);return A},P=await Zf(J.discoveryPath);if(P?.url){let A=await Bf(P.url);if(A?.url&&s8(A)&&await f0(A.url,{authToken:P.authToken}))return j({url:A.url,authToken:P.authToken});if(A?.url)await o8({...A,authToken:P.authToken},J.discoveryPath);else await Ef(J.discoveryPath).catch(()=>{return})}let X=await Bf(Z);if(X?.url)await o8(X,J.discoveryPath);let Y=!H&&Q.port!==0?{...Q,port:0}:Q;u1(f,Y);let B=Date.now()+TG;while(Date.now()<B){let A=await Zf(J.discoveryPath);if(A?.url){let U=await Bf(A.url);if(U?.url&&s8(U)&&await f0(U.url,{authToken:A.authToken}))return j({url:U.url,authToken:A.authToken})}let R=await Bf(Z);if(R?.url&&!s8(R))await o8(R,J.discoveryPath);await new Promise((U)=>setTimeout(U,hG))}throw Error("Timed out waiting for detached hub startup.")}function CG(){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 JP(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 JP(f.data);return String(f)}function EG(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 oj(f){let $=f,J=EG($.reason);return new yf("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:OH,{closeCode:$.code,closeReason:J||void 0})}function SG(f,$){if(f instanceof yf)return f;if(f instanceof Error)return new yf("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new yf("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 yf("hub_connect_failed",J);let W=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new yf("hub_connect_failed",W?`Failed to connect to hub at ${$.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var kG=8000,mG=200,ej="*",fP=8000,IG="cline-hub-auth.",WP=new Map,HP=new Set,xG=3000,gG=3000,vG=100,OH="Hub connection closed",uG=250,cG=5000,$P=0.5;class yf extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function bH(f){return f instanceof yf}class c1 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function TJ(f,$){return f instanceof c1&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function QP(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=wH(f.toString());return J?WP.get(J):void 0}function dG(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 wH(f){if(!dG(f))return;let $=new URL(H$(f));return $.search="",$.hash="",$.toString()}function NH(f){let $=wH(f);return!!$&&HP.has($)}function W$(f,$){let J=wH(f);if(J){if(HP.add(J),$?.trim())WP.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 yf("hub_connection_closed",OH);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()||QP(f);f.hash="";let W=new(CG())(f.toString(),$?[`${IG}${$}`]:void 0);this.socket=W;let H=!1;this.connectPromise=new Promise((Q,Z)=>{let j=!1,P=setTimeout(()=>{if(j)return;j=!0,H=!0,this.lastCloseError=new yf("hub_connect_timeout",`Timed out connecting to hub after ${fP}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}Z(this.lastCloseError)},fP);W.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(P),Q()}),W.addEventListener("error",(X)=>{if(j)return;j=!0,clearTimeout(P),this.lastCloseError=SG(X,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)}),W.addEventListener("close",(X)=>{if(j)return;if(j=!0,clearTimeout(P),!H)this.lastCloseError=oj(X),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)})}),W.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(JP(Q)))}),W.addEventListener("close",(Q)=>{if(this.socket!==W)return;if(!H)this.lastCloseError=oj(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=bG("hubreq_"),Q=wG(f,W?.timeoutMs),Z=new Promise((P,X)=>{let V=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(H))return;X(new c1(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:(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:H,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:$}})}catch(P){throw this.pendingReplies.delete(H),P}let j=await Z;if(!j.ok)throw new c1(f,j.error?.code,j.error?.message??`Hub command ${f} failed`);return j}async recoverLocalHubTransport(f){if(!NH(this.currentUrl)||!bH(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await g$({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(uG*2**this.reconnectAttempt,cG),$=Math.round(f*(1-$P)+Math.random()*f*$P);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(!NH(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await g$({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 yf("hub_connection_closed",OH),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 yf("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??ej}subscriptionSessionIdFromKey(f){return f===ej?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 H$(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function f0(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 qH(f,$){let J=H$(f),W=await Bf(J);if(!W)return{status:"unreachable",url:J};let H=J$(),Q=W.buildId?.trim();if(!Q||Q!==H)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await f0(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function rG(f){let $=Date.now()+kG;while(Date.now()<$){let J=await Zf(f.discoveryPath);if(J?.url){let W=await qH(J.url,{verifyConnection:!0,authToken:J.authToken});if(W.status==="compatible")return W$(W.url,J.authToken)}await new Promise((W)=>setTimeout(W,mG))}return}async function lG(f){let $=Date.now()+gG;while(Date.now()<$){if(!(await Bf(f).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,vG))}return!1}function pG(f,$){try{return H$(f)===H$($)}catch{return!1}}function iG(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 nG(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:xG});return!iG(H.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function f4(f={}){if(f.endpoint?.trim()){let H=await qH(f.endpoint);return H.status==="compatible"?H.url:void 0}let $=Qf(),J=await Zf($.discoveryPath);if(!J?.url)return;let W=await qH(J.url);if(W.status==="compatible")return W$(W.url,J.authToken);if(W.status==="build_mismatch")await Ef($.discoveryPath).catch(()=>{return});return}async function g$(f={}){let $=await f4(f);if($&&await f0($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=Qf();return u1(f.workspaceRoot??process.cwd()),await rG(J)}async function e8(f,$){let J=new URL(f),W=$?.trim()||QP(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 CH(){let f=Qf(),$=await Zf(f.discoveryPath);if(!$?.url)return!1;try{if(await e8($.url,$.authToken))return!0}catch{}return!1}async function hJ(f){if(!NH(f.url))return;let $=Qf(),J=await Zf($.discoveryPath);if(!J?.url||!pG(J.url,f.url))return;if(!await nG(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await CH())return;if(!await lG(J.url))return;return await Ef($.discoveryPath).catch(()=>{return}),await g$({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}var FP={};N(FP,{HubRuntimeHost:()=>_0});import{createSessionId as jP,HUB_CHECKPOINT_CAPABILITY as oG,HUB_COMPACTION_CAPABILITY as eG,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as fT,HUB_HOOK_CAPABILITY_PREFIX as $T,HUB_MISTAKE_LIMIT_CAPABILITY as JT,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as WT,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as HT,isHubToolExecutorName as QT}from"@cline/shared";var ZP={};N(ZP,{createCoreSessionSnapshot:()=>$0,coreSessionSnapshotToRecord:()=>DJ});function aG(f){return f?JSON.parse(JSON.stringify(f)):void 0}function tG(f){return f?JSON.parse(JSON.stringify(f)):void 0}function sG(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():"",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}:{}}]}),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 $0(f){let{session:$}=f,J=aG($.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:tG(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...(()=>{let W=sG(J);return W?{checkpoint:W}:{}})()}}function DJ(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 d1(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var ZT=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function PP(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function XP(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function VP(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 v$(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function YP(f,$){let J={manifest:[],handlers:new Map};for(let H of Object.keys($.toolExecutors??{}).filter(QT)){let Q=$.toolExecutors?.[H];if(typeof Q!=="function")continue;v$(J,{kind:"toolExecutor",executor:H,capabilityName:`${WT}${H}`},async({payload:Z,abortSignal:j})=>{let P=Array.isArray(Z.args)?[...Z.args]:[],X={...VP(Z.context),signal:j};return{result:await Q(...P,X)}})}for(let H of f?.extraTools??[])v$(J,{kind:"tool",name:H.name,description:H.description,inputSchema:d1(H.inputSchema)??{},...H.lifecycle?{lifecycle:d1(H.lifecycle)}:{},capabilityName:`${fT}${H.name}`},async({payload:Q,abortSignal:Z,progress:j})=>{let P={...VP(Q.context),signal:Z};return{result:await H.execute(Q.input,{...P,emitUpdate:(V)=>{j({update:V})}})}});let W=f?.hooks;if(W)for(let H of ZT){let Q=W[H];if(typeof Q!=="function")continue;v$(J,{kind:"hook",name:H,capabilityName:`${$T}${H}`},async({payload:Z})=>({control:await Q(Z.context)}))}if(f?.compaction?.compact){let H=f.compaction.compact;v$(J,{kind:"compaction",capabilityName:eG,config:PP(f.compaction)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.checkpoint?.createCheckpoint){let H=f.checkpoint.createCheckpoint;v$(J,{kind:"checkpoint",capabilityName:oG,config:PP(f.checkpoint)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.onConsecutiveMistakeLimitReached){let H=f.onConsecutiveMistakeLimitReached;v$(J,{kind:"mistakeLimit",capabilityName:JT},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.userInstructionService){let H=f.userInstructionService;v$(J,{kind:"userInstructionService",capabilityName:HT},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 jT(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 PT(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function XT(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function VT(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 YT(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,W=XT(J)?J:J==="failed"?"error":"completed",H=VT(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 EH(f,$){return f.error?.message??`hub command failed: ${$}`}function $4(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function RP(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:Pf.CORE,pid:typeof $?.pid==="number"?$.pid:void 0,startedAt:new Date(f.createdAt).toISOString(),endedAt:$4(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:$4(f.status)==="completed"?0:$4(f.status)==="failed"?1:void 0,status:$4(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 u$(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 BT(f){let $=u$(f?.snapshot);if($)return DJ($);let J=f?.session;return J?RP(J):void 0}function BP(f,$,J){let W=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return Uf.parse({version:1,session_id:f,source:$.source??Pf.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:$4(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 AP(f,$){return Uf.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 a8;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=Vf(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(!TJ(f,"session.create"))return!1;let $=await hJ({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=YP(f.localRuntime,$),W=f.config.sessionId?.trim()||jP(),H=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:d1({...f.config,sessionId:W}),metadata:{...f.sessionMetadata??{},source:f.source??Pf.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:d1(f.toolPolicies),initialMessages:f.initialMessages});this.registerPlannedSession(W,$,J.handlers);let Q;try{Q=await H()}catch(X){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(X)){this.registerPlannedSession(W,$,J.handlers);try{Q=await H()}catch(V){throw this.cleanupPlannedSession(W),V}}else throw X}let Z=u$(Q.payload?.snapshot),j=Q.payload?.session,P=(Z?.sessionId??j?.sessionId)?.trim();if(!P)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(P!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(P,$,J.handlers);return{sessionId:P,manifest:Z?AP(Z,f):BP(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 W=f.start,H=W?this.resolveCapabilities(W):void 0,Q=W?YP(W.localRuntime,H??{}):{manifest:[],handlers:new Map},Z=W?W.config.sessionId?.trim()||jP():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:d1({...W.config,sessionId:Z}),metadata:{...W.sessionMetadata??{},source:W.source??Pf.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:d1(W.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=u$(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&&H)this.sessionCapabilities.set(V,H);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?AP(P,W??{}):BP(V,W??{},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=u$($.payload?.snapshot);if(J?.usage)return{...J.usage};let W=$.payload?.session;return W?.usage?{...W.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 BT($.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=u$(H);return Q?[DJ(Q)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(RP)}async listSettings(f){let $=await this.client.command("settings.list",XP(f));if(!$.ok)throw Error(EH($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",XP(f));if(!$.ok)throw Error(EH($,"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(EH(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 Vf(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:YT(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=u$(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"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=u$(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 P=(X)=>{this.client.command("capability.progress",{requestId:W,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:W,ok:!0,payload:X},$)}catch(X){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:X instanceof Error?X.message:String(X)},$)}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(jT(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=PT(f.payload?.inputJson);this.pendingApprovalToolCallIds.add(H),this.emitToolCallContentStart({sessionId:$,toolCallId:H,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:H,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:W,approved:P.approved,reason:P.reason},$).catch(()=>{})}}var yP={};N(yP,{RemoteRuntimeHost:()=>r1});class r1 extends _0{constructor(f){super({url:H$(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 KP={};N(KP,{SqliteSessionStore:()=>W0});import{existsSync as AT,mkdirSync as RT}from"node:fs";import{join as FT}from"node:path";import{asBool as J4,asOptionalString as J0,asString as L0,ensureSessionSchema as yT,loadSqliteDb as KT,nowIso as MJ,toBoolInt as W4}from"@cline/shared/db";import{resolveDbDataDir as UT}from"@cline/shared/storage";class W0{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??UT()}init(){this.getRawDb()}ensureSessionsDir(){if(!AT(this.sessionsDirPath))RT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return FT(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=KT(this.sessionDbPath());return yT(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 $=MJ();this.run(`INSERT OR REPLACE INTO sessions (
|
|
470
|
+
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)}}class e8{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new o8({dbPath:f.dbPath});let $=f.specs;this.reconciler=new V9({store:this.store,specs:$}),this.materializer=new i8({store:this.store}),this.eventIngress=new J9({store:this.store,logger:f.logger}),this.runner=new n8({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 R9({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 WX={};N(WX,{manifestToSessionRecord:()=>YJ,listSessionHistoryFromBackend:()=>D9,listSessionHistory:()=>VJ,hydrateSessionHistory:()=>JX});import{readdir as WG,readFile as ej}from"node:fs/promises";import{join as fX}from"node:path";import{formatDisplayUserInput as HG,normalizeUserInput as QG}from"@cline/shared";import{resolveSessionDataDir as $X}from"@cline/shared/storage";import{existsSync as fG}from"node:fs";import{readFile as $G}from"node:fs/promises";import{formatDisplayUserInput as aj}from"@cline/shared";class f4{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 Q$(f){let $=f?.trim();if(!$||!fG($))return[];try{let J=(await $G($,"utf8")).trim();if(!J)return[];let W=JSON.parse(J);if(Array.isArray(W))return tj(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let H=W.messages;if(Array.isArray(H))return tj(H)}return[]}catch{return[]}}function JG(f){if(f.role!=="user")return f;if(typeof f.content==="string")return{...f,content:aj(f.content)};return{...f,content:f.content.map(($)=>{if($.type!=="text"||typeof $.text!=="string")return $;return{...$,text:aj($.text)}})}}function tj(f){return f.map(JG)}function U9(f){return f?{...f}:void 0}async function sj(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 PJ(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function mf(f){let $=PJ(f);if(!$)return;return $.toLowerCase()==="unknown"?void 0:$}function BJ(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function ZG(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return{...f}}function T9(f){let $=f??200;return Number.isFinite($)?Math.max(0,Math.floor($)):200}function jG(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 YJ(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 XG(f){let $=T9(f);if($===0)return[];let J=$X(),H=(await WG(J,{withFileTypes:!0}).catch(()=>[])).filter((Z)=>Z.isDirectory()).map((Z)=>({entry:Z,recency:jG(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=fX(J,j,`${j}.json`),A=await ej(X,"utf8").catch(()=>{return});if(!A)return;let P;try{P=JSON.parse(A)}catch{return}let B=Mf.safeParse(P);if(!B.success)return;return YJ(B.data)}))).filter((Z)=>Boolean(Z)).sort((Z,j)=>j.startedAt.localeCompare(Z.startedAt)).slice(0,$)}async function AG(f,$){let J=T9($);if(J===0)return await f.listSessions(0),[];return(await f.listSessions(J)).slice(0,J)}function PG(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(`
|
|
471
|
+
`).trim()}function oj(f){return f.replace(/\s+/g," ").trim()}function BG(f,$){if(f.length<=$)return f;return`${f.slice(0,Math.max(0,$-3)).trimEnd()}...`}function YG(f){for(let $ of["user","assistant"])for(let J of f){if(J.role!==$)continue;let W=oj(PG(J.content));if(!W)continue;let H=$==="user"?oj(HG(W)):W,Q=QG(H.split(`
|
|
472
|
+
`)[0]??H);return BG(Q,50)}return}function VG(f){let $=0;for(let J of f)$+=BJ(J.metrics?.cost)??0;return $}function RG(f){let $,J;for(let W=f.length-1;W>=0;W-=1){let H=f[W];if(!$)$=mf(H.modelInfo?.provider);if(!J)J=mf(H.modelInfo?.id);if($&&J)break}return{provider:$,model:J}}function FG(f){return mf(f?.provider)??mf(f?.provider&&typeof f.provider==="object"&&!Array.isArray(f.provider)?f.provider.id:void 0)}function KG(f){return mf(f?.model)??mf(f?.model&&typeof f.model==="object"&&!Array.isArray(f.model)?f.model.id:void 0)}function G9(f,$){let J=ZG(f.metadata),W=PJ($?.title)??PJ(J?.title),H=BJ($?.totalCost)??BJ(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:mf($?.provider)??mf(f.provider)??FG(J)??"",model:mf($?.model)??mf(f.model)??KG(J)??"",metadata:Q}}async function JX(f,$){return await Promise.all($.map(async(J)=>{let W=G9(J),H=Boolean(PJ(W.metadata?.title)),Q=Boolean(mf(W.provider)),Z=Boolean(mf(W.model)),j=BJ(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=RG(A),B=VG(A);return G9(J,{title:H?void 0:YG(A),provider:Q?void 0:P.provider,model:Z?void 0:P.model,totalCost:X||B<=0?void 0:B})}))}async function VJ(f,$={}){let J=T9($.limit),W=await AG(f,J),H=$.includeManifestFallback===!0&&W.length<J?await XG(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)=>G9(j));return await JX(f,Z)}async function yG(f){let $=f.trim();if(!$)return;let J=fX($X(),$,`${$}.json`),W=await ej(J,"utf8").catch(()=>{return});if(!W)return;try{let H=Mf.safeParse(JSON.parse(W));return H.success?H.data.messages_path:void 0}catch{return}}async function D9(f,$={}){let J=new Map;return await VJ({listSessions:async(H)=>{let Q=await f.listSessions(H);J.clear();for(let Z of Q)J.set(Z.sessionId,Z);return Q.map(p2)},readSessionMessages:async(H)=>{let Q=J.get(H)?.messagesPath??await yG(H);return await Q$(Q)}},$)}var QA={};N(QA,{resolveSessionBackend:()=>WH,createRuntimeHost:()=>o1});import{createSessionId as jT,resolveHubCommandTimeoutMs as XT}from"@cline/shared";import{spawn as gG}from"node:child_process";import{closeSync as vG,mkdirSync as uG,openSync as cG}from"node:fs";import{basename as dG,dirname as rG,join as lG}from"node:path";import{fileURLToPath as pG}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as iG,isHubDaemonProcess as yX,withResolvedClineBuildEnv as nG}from"@cline/shared";import{createHash as UG,randomBytes as GG}from"node:crypto";import{existsSync as TG}from"node:fs";import{chmod as DG,mkdir as _9,readFile as AX,rm as M9,writeFile as PX}from"node:fs/promises";import{dirname as BX,join as L9}from"node:path";import{resolveClineDataDir as $4,resolveClineDir as YX}from"@cline/shared/storage";var QX="0.0.39";var ZX={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:QX,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 _G="CLINE_HUB_DISCOVERY_PATH",MG="CLINE_HUB_BUILD_ID",jX=30000,LG=15000,hG=100;function OG(f){return f.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function zG(f){return UG("sha256").update(f).digest("hex").slice(0,12)}function NG(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 RJ(){return GG(32).toString("hex")}function qG(f){return new Promise(($)=>setTimeout($,f))}function wG(f){return`${f}.lock`}async function bG(f){try{let $=JSON.parse(await AX(L9(f,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function XX(f){await M9(f,{recursive:!0,force:!0}).catch(()=>{return})}function Z$(){return process.env[MG]?.trim()||String(ZX.version)}function z0(f=process.argv[1]?.trim()||process.cwd()){let $=`hub-${zG(f)}`,J=process.env[_G]?.trim()||L9($4(),"locks","hub","owners",`${OG($)}.json`);return{ownerId:$,discoveryPath:J}}function VX(f=`hub-${Date.now().toString(36)}`){return z0(f)}async function Bf(f){try{let $=JSON.parse(await AX(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 FJ(f,$){await _9(BX(f),{recursive:!0}),await M9(f,{force:!0}).catch(()=>{return}),await PX(f,`${JSON.stringify($,null,2)}
|
|
473
|
+
`,{encoding:"utf8",mode:384}),await DG(f,384)}async function xf(f){await M9(f,{force:!0}).catch(()=>{return})}async function KJ(f,$){let J=wG(f);await _9(BX(J),{recursive:!0});let W=Date.now()+LG;while(!0)try{await _9(J,{recursive:!1}),await PX(L9(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
474
|
+
`,"utf8");try{return await $()}finally{await XX(J)}}catch(H){if((H instanceof Error&&"code"in H?String(H.code):"")!=="EEXIST")throw H;let Z=await bG(J),j=Z?Date.now()-Date.parse(Z.acquiredAt):jX+1;if(!Z||!NG(Z.pid)||j>jX){await XX(J);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${J}`);await qG(hG)}}async function Uf(f){try{let $=await fetch(h9(f));if(!$.ok)return;return await $.json()}catch{return}}function af(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function h9(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function RX(f){return TG(f)}import{CLINE_HUB_DEV_PORT as CG,CLINE_HUB_PORT as EG,resolveClineBuildEnv as SG}from"@cline/shared";var kG="CLINE_HUB_HOST",IG="CLINE_HUB_PORT",mG="CLINE_HUB_PATHNAME",O9="127.0.0.1",z9=EG,N9="/hub";function FX(f){return SG(f)==="development"?CG:z9}function q9(f={}){return(f.env??process.env)[kG]?.trim()||O9}function d1(f={}){let J=(f.env??process.env)[IG]?.trim();if(!J)return FX(f);let W=Number.parseInt(J,10);if(!Number.isInteger(W)||W<1||W>65535)return FX(f);return W}function w9(f={}){return(f.env??process.env)[mG]?.trim()||N9}function gf(f={},$={}){return{host:f.host??q9($),port:f.port??d1($),pathname:f.pathname??w9($)}}var xG="shared:cline";function KX(f){let $=O0(f.trim());return z0(`workspace:${$||f.trim()}`)}function Af(f=xG){return z0(f)}var aG=8000,tG=200,sG=3000,oG=100,eG=[100,250,500,1000,2000],fT="--cline-hub-daemon";function $T(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function JT(){try{let f=lG($4(),"logs","hub-daemon.log");return uG(rG(f),{recursive:!0}),{fd:cG(f,"a"),logPath:f}}catch{return}}function J4(f){let $=f.buildId?.trim();return!!$&&$===Z$()}async function WT(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await Uf(f).catch(()=>{return}))?.url)return!0;await new Promise((H)=>setTimeout(H,oG))}return!1}async function W4(f,$){if(J4(f))return;if(await H4(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await WT(f.url,sG),await xf($).catch(()=>{return})}function HT(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return pG(new URL(`./entry.${f}`,import.meta.url))}function QT(f,$){let J=HT(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let H=dG(W).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),Z=H&&J.toLowerCase().endsWith(".ts"),j=Q?[fT]:[...Z?["--conditions=development"]:[],J];return{launcher:W,args:[...j,"--cwd",f,...$T($)],cwd:f,env:{...nG(process.env),CLINE_NO_INTERACTIVE:"1",[iG]:"1"}}}function ZT(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 b9(f,$={}){if(yX())return;let J=QT(f,$),W=JT();try{gG(J.launcher,J.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(W)vG(W.fd)}}async function r1(f,$={}){for(let J=0;;J++)try{b9(f,$);return}catch(W){let H=eG[J];if(!ZT(W)||H===void 0)throw W;await new Promise((Q)=>setTimeout(Q,H))}}function yJ(f,$={}){if(yX())return;let J=Af(),W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),H=gf($),Q=af(H.host,H.port,H.pathname);Bf(J.discoveryPath).then(async(Z)=>{if(Z?.url){let P=await Uf(Z.url);if(P?.url&&J4(P)&&await J0(P.url,{authToken:Z.authToken}))return;if(P?.url)await W4({...P,authToken:Z.authToken},J.discoveryPath);else await xf(J.discoveryPath).catch(()=>{return})}let j=await Uf(Q);if(j?.url)await W4(j,J.discoveryPath);let A=!W&&H.port!==0?{...H,port:0}:H;await r1(f,A)}).catch(()=>{})}async function UX(f,$={}){let J=Af(),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=gf($),Z=af(Q.host,Q.port,Q.pathname),j=(V)=>{if(!W)j$(V.url,V.authToken);return V},X=await Bf(J.discoveryPath);if(X?.url){let V=await Uf(X.url);if(V?.url&&J4(V)&&await J0(V.url,{authToken:X.authToken}))return j({url:V.url,authToken:X.authToken});if(V?.url)await W4({...V,authToken:X.authToken},J.discoveryPath);else await xf(J.discoveryPath).catch(()=>{return})}let A=await Uf(Z);if(A?.url)await W4(A,J.discoveryPath);let B=!H&&Q.port!==0?{...Q,port:0}:Q;await r1(f,B);let Y=Date.now()+aG;while(Date.now()<Y){let V=await Bf(J.discoveryPath);if(V?.url){let U=await Uf(V.url);if(U?.url&&J4(U)&&await J0(U.url,{authToken:V.authToken}))return j({url:U.url,authToken:V.authToken})}let R=await Uf(Z);if(R?.url&&!J4(R))await W4(R,J.discoveryPath);await new Promise((U)=>setTimeout(U,tG))}throw Error("Timed out waiting for detached hub startup.")}function AT(){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 MX(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 MX(f.data);return String(f)}function PT(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 GX(f){let $=f,J=PT($.reason);return new Df("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:C9,{closeCode:$.code,closeReason:J||void 0})}function BT(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 YT=8000,VT=200,TX="*",DX=8000,RT="cline-hub-auth.",LX=new Map,hX=new Set,FT=3000,KT=3000,yT=100,C9="Hub connection closed",UT=250,GT=5000,_X=0.5;class Df extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function k9(f){return f instanceof Df}class l1 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function UJ(f,$){return f instanceof l1&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function OX(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=I9(f.toString());return J?LX.get(J):void 0}function TT(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 I9(f){if(!TT(f))return;let $=new URL(X$(f));return $.search="",$.hash="",$.toString()}function E9(f){let $=I9(f);return!!$&&hX.has($)}function j$(f,$){let J=I9(f);if(J){if(hX.add(J),$?.trim())LX.set(J,$)}return f}class tf{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",C9);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()||OX(f);f.hash="";let W=new(AT())(f.toString(),$?[`${RT}${$}`]: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 ${DX}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}Z(this.lastCloseError)},DX);W.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(X),Q()}),W.addEventListener("error",(A)=>{if(j)return;j=!0,clearTimeout(X),this.lastCloseError=BT(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=GX(A),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)})}),W.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(MX(Q)))}),W.addEventListener("close",(Q)=>{if(this.socket!==W)return;if(!H)this.lastCloseError=GX(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=jT("hubreq_"),Q=XT(f,W?.timeoutMs),Z=new Promise((X,A)=>{let P=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(H))return;A(new l1(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 l1(f,j.error?.code,j.error?.message??`Hub command ${f} failed`);return j}async recoverLocalHubTransport(f){if(!E9(this.currentUrl)||!k9(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await c$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let f=Math.min(UT*2**this.reconnectAttempt,GT),$=Math.round(f*(1-_X)+Math.random()*f*_X);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(!E9(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await c$({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(f){this.currentUrl=f,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let f=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!f)return;this.lastCloseError=new Df("hub_connection_closed",C9),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??TX}subscriptionSessionIdFromKey(f){return f===TX?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 X$(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function J0(f,$){let J=new tf({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 S9(f,$){let J=X$(f),W=await Uf(J);if(!W)return{status:"unreachable",url:J};let H=Z$(),Q=W.buildId?.trim();if(!Q||Q!==H)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await J0(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function DT(f){let $=Date.now()+YT;while(Date.now()<$){let J=await Bf(f.discoveryPath);if(J?.url){let W=await S9(J.url,{verifyConnection:!0,authToken:J.authToken});if(W.status==="compatible")return j$(W.url,J.authToken)}await new Promise((W)=>setTimeout(W,VT))}return}async function _T(f){let $=Date.now()+KT;while(Date.now()<$){if(!(await Uf(f).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,yT))}return!1}function MT(f,$){try{return X$(f)===X$($)}catch{return!1}}function LT(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 hT(f,$,J){let W=new tf({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:FT});return!LT(H.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function Q4(f={}){if(f.endpoint?.trim()){let H=await S9(f.endpoint);return H.status==="compatible"?H.url:void 0}let $=Af(),J=await Bf($.discoveryPath);if(!J?.url)return;let W=await S9(J.url);if(W.status==="compatible")return j$(W.url,J.authToken);if(W.status==="build_mismatch")await xf($.discoveryPath).catch(()=>{return});return}async function c$(f={}){let $=await Q4(f);if($&&await J0($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=Af();return await r1(f.workspaceRoot??process.cwd()),await DT(J)}async function H4(f,$){let J=new URL(f),W=$?.trim()||OX(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 m9(){let f=Af(),$=await Bf(f.discoveryPath);if(!$?.url)return!1;try{if(await H4($.url,$.authToken))return!0}catch{}return!1}async function GJ(f){if(!E9(f.url))return;let $=Af(),J=await Bf($.discoveryPath);if(!J?.url||!MT(J.url,f.url))return;if(!await hT(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await m9())return;if(!await _T(J.url))return;return await xf($.discoveryPath).catch(()=>{return}),await c$({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}var mX={};N(mX,{HubRuntimeHost:()=>N0});import{createSessionId as NX,HUB_CHECKPOINT_CAPABILITY as qT,HUB_COMPACTION_CAPABILITY as wT,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as bT,HUB_HOOK_CAPABILITY_PREFIX as CT,HUB_MISTAKE_LIMIT_CAPABILITY as ET,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ST,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as kT,isHubToolExecutorName as IT}from"@cline/shared";var zX={};N(zX,{createCoreSessionSnapshot:()=>W0,coreSessionSnapshotToRecord:()=>TJ});function OT(f){return f?JSON.parse(JSON.stringify(f)):void 0}function zT(f){return f?JSON.parse(JSON.stringify(f)):void 0}function NT(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=OT($.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:zT(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...f.aggregateUsage?{aggregateUsage:{...f.aggregateUsage}}:{},...(()=>{let W=NT(J);return W?{checkpoint:W}:{}})()}}function TJ(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 p1(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var mT=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function qX(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function wX(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function bX(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 d$(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function CX(f,$){let J={manifest:[],handlers:new Map};for(let H of Object.keys($.toolExecutors??{}).filter(IT)){let Q=$.toolExecutors?.[H];if(typeof Q!=="function")continue;d$(J,{kind:"toolExecutor",executor:H,capabilityName:`${ST}${H}`},async({payload:Z,abortSignal:j})=>{let X=Array.isArray(Z.args)?[...Z.args]:[],A={...bX(Z.context),signal:j};return{result:await Q(...X,A)}})}for(let H of f?.extraTools??[])d$(J,{kind:"tool",name:H.name,description:H.description,inputSchema:p1(H.inputSchema)??{},...H.lifecycle?{lifecycle:p1(H.lifecycle)}:{},capabilityName:`${bT}${H.name}`},async({payload:Q,abortSignal:Z,progress:j})=>{let X={...bX(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 mT){let Q=W[H];if(typeof Q!=="function")continue;d$(J,{kind:"hook",name:H,capabilityName:`${CT}${H}`},async({payload:Z})=>({control:await Q(Z.context)}))}if(f?.compaction?.compact){let H=f.compaction.compact;d$(J,{kind:"compaction",capabilityName:wT,config:qX(f.compaction)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.checkpoint?.createCheckpoint){let H=f.checkpoint.createCheckpoint;d$(J,{kind:"checkpoint",capabilityName:qT,config:qX(f.checkpoint)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.onConsecutiveMistakeLimitReached){let H=f.onConsecutiveMistakeLimitReached;d$(J,{kind:"mistakeLimit",capabilityName:ET},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.userInstructionService){let H=f.userInstructionService;d$(J,{kind:"userInstructionService",capabilityName:kT},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 xT(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 gT(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function vT(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function uT(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 EX(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 g9(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function A$(f,$){return g9(f?.[$])??0}function cT(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:g9($?.totalCost),totalInputTokens:A$(J,"inputTokens"),totalOutputTokens:A$(J,"outputTokens"),totalCacheReadTokens:A$(J,"cacheReadTokens"),totalCacheWriteTokens:A$(J,"cacheWriteTokens"),totalCost:g9(J?.totalCost)},teamAgentId:typeof W?.teamAgentId==="string"?W.teamAgentId:void 0,teamRole:H}}function dT(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,W=vT(J)?J:J==="failed"?"error":"completed",H=uT(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 x9(f,$){return f.error?.message??`hub command failed: ${$}`}function Z4(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function IX(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:Z4(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:Z4(f.status)==="completed"?0:Z4(f.status)==="failed"?1:void 0,status:Z4(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 r$(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 rT(f){let $=r$(f?.snapshot);if($)return TJ($);let J=f?.session;return J?IX(J):void 0}function SX(f,$,J){let W=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return Mf.parse({version:1,session_id:f,source:$.source??Vf.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:Z4(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 kX(f,$){return Mf.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 N0{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new f4;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=Kf(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 tf({...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(!UJ(f,"session.create"))return!1;let $=await GJ({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=CX(f.localRuntime,$),W=f.config.sessionId?.trim()||NX(),H=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:p1({...f.config,sessionId:W}),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:p1(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=r$(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?kX(Z,f):SX(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?CX(W.localRuntime,H??{}):{manifest:[],handlers:new Map},Z=W?W.config.sessionId?.trim()||NX():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:p1({...W.config,sessionId:Z}),metadata:{...W.sessionMetadata??{},source:W.source??Vf.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:p1(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=r$(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?kX(X,W??{}):SX(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=r$($.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=EX(W?.usage),Q=EX(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 rT($.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=r$(H);return Q?[TJ(Q)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(IX)}async listSettings(f){let $=await this.client.command("settings.list",wX(f));if(!$.ok)throw Error(x9($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",wX(f));if(!$.ok)throw Error(x9($,"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(x9(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 Kf(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:dT(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=r$(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=cT(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=r$(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(xT(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=gT(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 xX={};N(xX,{RemoteRuntimeHost:()=>i1});class i1 extends N0{constructor(f){super({url:X$(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 gX={};N(gX,{SqliteSessionStore:()=>Q0});import{existsSync as lT,mkdirSync as pT}from"node:fs";import{join as iT}from"node:path";import{asBool as j4,asOptionalString as H0,asString as q0,ensureSessionSchema as nT,loadSqliteDb as aT,nowIso as DJ,toBoolInt as X4}from"@cline/shared/db";import{resolveDbDataDir as tT}from"@cline/shared/storage";class Q0{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??tT()}init(){this.getRawDb()}ensureSessionsDir(){if(!lT(this.sessionsDirPath))pT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return iT(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=aT(this.sessionDbPath());return nT(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 $=DJ();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,
|
|
479
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,0,X4(f.interactive),f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,X4(f.enableTools),X4(f.enableSpawn),X4(f.enableTeams),f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,X4(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(DJ()),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:DJ(),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:
|
|
485
|
-
`,"utf8")}readSessionManifest(f){return this.readManifestFile(f).manifest}readManifestFile(f){let $=this.artifacts.sessionManifestPath(f,!1);if(!
|
|
486
|
-
`;if(
|
|
487
|
-
`,"utf8")}}import{appendFileSync as
|
|
488
|
-
`,"utf8")}}import{formatUserInputBlock as
|
|
484
|
+
FROM sessions WHERE session_id = ?`,[f]);if(!$)return;return{sessionId:q0($.session_id),source:q0($.source),pid:Number($.pid??0),startedAt:q0($.started_at),endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:q0($.status),interactive:j4($.interactive),provider:q0($.provider),model:q0($.model),cwd:q0($.cwd),workspaceRoot:q0($.workspace_root),teamName:H0($.team_name),enableTools:j4($.enable_tools),enableSpawn:j4($.enable_spawn),enableTeams:j4($.enable_teams),parentSessionId:H0($.parent_session_id),parentAgentId:H0($.parent_agent_id),agentId:H0($.agent_id),conversationId:H0($.conversation_id),isSubagent:j4($.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)??DJ()}}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(q0(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}}_J();import{existsSync as s9,mkdirSync as zD,readFileSync as tX,renameSync as ND,writeFileSync as qD}from"node:fs";import{join as sX}from"node:path";import{resolveSessionDataDir as wD}from"@cline/shared/storage";import{dirname as hD}from"node:path";import{nanoid as OD}from"nanoid";import{appendFileSync as AD,existsSync as PD,mkdirSync as vX,readFileSync as BD,writeFileSync as uX}from"node:fs";import{dirname as cX,join as YD}from"node:path";import{ensureHookLogDir as VD}from"@cline/shared/storage";class v9{adapter;messagesArtifactUploader;artifacts;constructor(f,$){this.adapter=f;this.messagesArtifactUploader=$;this.artifacts=new CW(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile(f,$,J){Y7($,J,p5(f))}writeSessionManifest(f,$){vX(cX(f),{recursive:!0}),uX(f,`${JSON.stringify(Mf.parse($),null,2)}
|
|
485
|
+
`,"utf8")}readSessionManifest(f){return this.readManifestFile(f).manifest}readManifestFile(f){let $=this.artifacts.sessionManifestPath(f,!1);if(!PD($))return{path:$};try{return{path:$,manifest:Mf.parse(JSON.parse(BD($,"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=i5({updatedAt:s(),context:p5(f),messages:$,systemPrompt:J}),Q=`${JSON.stringify(H,null,2)}
|
|
486
|
+
`;if(vX(cX(W),{recursive:!0}),uX(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)??YD(VD(),"hooks.jsonl");AD(Z,`${JSON.stringify({ts:f,hookName:"session_shutdown",reason:W,sessionId:$,pid:J,source:H})}
|
|
487
|
+
`,"utf8")}}import{appendFileSync as RD}from"node:fs";import{join as FD}from"node:path";import{resolveRootSessionId as dX}from"@cline/shared";import{ensureHookLogDir as KD}from"@cline/shared/storage";import{z as u9}from"zod";var yD="subagent",UD=u9.looseObject({task:u9.string().optional(),systemPrompt:u9.string().optional()});class MJ{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:yD,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:i2({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 $=dX(f.sessionContext);if(!$)return;let J=UD.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=F1($,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:i2({metadata:H.metadata??void 0,prompt:H.prompt??j??null}),expectedStatusLock:H.statusLock}),W}async upsertSubagentSessionFromHook(f){if(!f.parent_agent_id)return;let $=dX(f.sessionContext);if(!$)return;if(f.hookName==="session_shutdown"){let J=F1($,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,r2($))}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=c2(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)??FD(KD(),"hooks.jsonl");RD(J,`${JSON.stringify({ts:s(),...f})}
|
|
488
|
+
`,"utf8")}}import{formatUserInputBlock as LD}from"@cline/shared";var aX={};N(aX,{toTeamProgressLifecycleEvent:()=>a1,sanitizeTeamName:()=>H7,reviveTeamStateDates:()=>c4,createWorkerReviewerTeam:()=>nX,createSpawnAgentTool:()=>d0,createDelegatedAgentConfigProvider:()=>B1,createDelegatedAgent:()=>Y1,createAgentTeamsTools:()=>_$,createAgentTeam:()=>d9,buildTeamProgressSummary:()=>n1,buildDelegatedAgentConfig:()=>T$,bootstrapAgentTeams:()=>R1,AgentTeamsRuntime:()=>p$,AgentTeam:()=>s1});function Z0(){return new Date().toISOString()}function rX(f,$){if($<=0)return 0;return Math.round(f/$*100)}function GD(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 n1(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:rX(B,$.tasks.length)},runs:{total:$.runs.length,byStatus:H,activeRunIds:V,latestRunId:R},outcomes:{total:$.outcomes.length,byStatus:Q,finalizedPct:rX(Q.finalized,$.outcomes.length),missingRequiredSections:GD($.outcomes,$.outcomeFragments)},fragments:{total:$.outcomeFragments.length,byStatus:Z}}}function a1(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 TD,TeamMessageType as C}from"@cline/shared";import{nanoid as DD}from"nanoid";import{TeamMessageType as qS}from"@cline/shared";function c9(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 lX(f,$){return f?.status==="stopped"&&c9($)}var _D=600000,pX="recovered_queued";function MD(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
|
|
490
|
+
${f.message}`}class s1{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 c0(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
|
|
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 d9(f,$){return new s1(f,$)}function nX(f){let $=d9({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
|
-
${H.text}`);return{workerResult:H,reviewResult:Q}},J}class
|
|
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_${TD(DD(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,t1(f.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,t1(f.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,t1(f.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,t1((f.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,t1((f.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,t1((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:_D,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 c0(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(!c9(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 W.agent.continue(Q):await W.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(H){let Q=H instanceof Error?H:Error(String(H));if(this.emitEvent({type:w.TaskEnd,agentId:f,error:Q,messages:W.agent.getMessages()}),!MP(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:w.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===_P;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 W=$?lT(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:w.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(MP(Q,W))f.status="cancelled",f.currentActivity="cancelled",this.emitEvent({type:w.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: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 LP($);return{...J}}async awaitAllRuns(f=250){while(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))await LP(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: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 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:w.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=_P,!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,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: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,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: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 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: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(!mH($))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:w.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
|
|
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()}),!lX(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===pX;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=$?MD(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(lX(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 iX($);return{...J}}async awaitAllRuns(f=250){while(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))await iX(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=pX,!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(!c9($))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 iX(f){return new Promise(($)=>setTimeout($,f))}function t1(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 r9(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}),LJ(f);break}default:break}}async function l9(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 p9(f,$,J,W){if(!f.runtime.teamRuntime)return;let H=f.runtime.teamRuntime.getTeamName();W({type:"team_progress",payload:{sessionId:$,teamName:H,lifecycle:a1({teamName:H,sessionId:$,event:J}),summary:n1(H,f.runtime.teamRuntime.exportState())}})}function A4(f){return f.activeTeamRunIds.size>0||f.pendingTeamRunUpdates.length>0}function i9(f,$){if(f.aborting)return!1;if(!($==="completed"||$==="max_iterations"))return!1;return f.config.enableAgentTeams===!0&&A4(f)}function LJ(f){let $=f.teamRunWaiters.splice(0);for(let J of $)J()}async function n9(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 a9(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 P4(`System-delivered teammate async run updates:
|
|
499
499
|
${J.join(`
|
|
500
500
|
`)}
|
|
501
501
|
|
|
502
|
-
${H}`,f.config.mode)}function
|
|
503
|
-
`,"utf8"),
|
|
502
|
+
${H}`,f.config.mode)}function P4(f,$){return LD(f,$==="plan"?"plan":$==="yolo"?"yolo":"act")}var t9=4;class w0{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 v9(f,$.messagesArtifactUploader),this.teamChildren=new MJ(f,this.manifestStore,(J,W,H)=>this.toPersistedMessages(J,W,H),w0.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages(f,$,J){if(!f)return;return $?i4($.messages,$,J):p4(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()}_${OD(5)}`,H=this.manifestStore.artifacts.sessionMessagesPath(W),Q=this.manifestStore.artifacts.sessionManifestPath(W),Z=i2({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:r0(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 R7(()=>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})},t9)).updated){if($==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions(f,"cancelled");return{updated:!0,endedAt:W}}return{updated:!1}}async updateSession(f){for(let $=0;$<t9;$++){let J=await this.adapter.getSession(f.sessionId);if(!J)return{updated:!1};let W=J.metadata??void 0,H=f.metadata!==void 0?r0(f.metadata)??{}:r0(W)??{},Q=O$(typeof W?.title==="string"?W.title:void 0),Z=f.title!==void 0?O$(f.title):Q??l5(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?r0(f.metadata)??{}:r0(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=p4($);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=w0.STALE_REASON;for(let W=0;W<t9;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:w0.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=V7(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,w0.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=r0(H.metadata??void 0),Z=this.manifestStore.readSessionManifest(H.sessionId),j=O$(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 AW(H.cwd,H.sessionId),_8(H.messagesPath),_8(this.manifestStore.artifacts.sessionManifestPath(H.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(H.sessionId)}))}if(await AW(J.cwd,$),_8(J.messagesPath),_8(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(hD(H));for(let H of W)this.manifestStore.artifacts.removeDir(H)}return{deleted:!0}}}function o9(){return new Date().toISOString()}function oX(f,$){let J=`${f}.tmp`;qD(J,`${JSON.stringify($,null,2)}
|
|
503
|
+
`,"utf8"),ND(J,f)}class eX{sessionsDirPath;constructor(f=wD()){this.sessionsDirPath=f}ensureSessionsDir(){if(!s9(this.sessionsDirPath))zD(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return sX(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return sX(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let f=this.indexPath();if(!s9(f))return{version:1,sessions:{}};try{let $=JSON.parse(tX(f,"utf8"));if($?.version===1&&$.sessions)return $}catch{}return{version:1,sessions:{}}}writeIndex(f){oX(this.indexPath(),f)}readQueue(){let f=this.spawnQueuePath();if(!s9(f))return{version:1,nextId:1,requests:[]};try{let $=JSON.parse(tX(f,"utf8"));if($?.version===1&&typeof $.nextId==="number"&&Array.isArray($.requests))return $}catch{}return{version:1,nextId:1,requests:[]}}writeQueue(f){oX(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:o9()};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:o9()}),$.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=o9(),this.writeQueue(J),W.task}}class e9 extends w0{constructor(f,$={}){super(new eX(f),$)}ensureSessionsDir(){return super.ensureSessionsDir()}}var JA={};N(JA,{CoreSessionService:()=>j0});import{existsSync as bD,mkdirSync as CD}from"node:fs";import{resolveSessionDataDir as ED}from"@cline/shared/storage";var fH=`
|
|
504
504
|
session_id AS sessionId,
|
|
505
505
|
source,
|
|
506
506
|
pid,
|
|
@@ -527,56 +527,56 @@ ${H}`,f.config.mode)}function Q4(f,$){return pT(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
|
|
530
|
+
updated_at AS updatedAt`;function $H(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 JH(f){if(!f||Object.keys(f).length===0)return null;return JSON.stringify(f)}function fA(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 $A{store;sessionsDirPath;constructor(f,$=ED()){this.store=f;this.sessionsDirPath=$}ensureSessionsDir(){if(!bD(this.sessionsDirPath))CD(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,
|
|
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,JH(f.metadata),"",f.hookPath??"",f.messagesPath??null,f.updatedAt])}async getSession(f){let $=this.store.queryOne(`SELECT ${fH} FROM sessions WHERE session_id = ?`,[f]);return $?$H($):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 ${fH}
|
|
536
536
|
FROM sessions
|
|
537
537
|
${W}
|
|
538
538
|
ORDER BY started_at DESC
|
|
539
|
-
LIMIT ?`,[...J,f.limit]).map(
|
|
539
|
+
LIMIT ?`,[...J,f.limit]).map($H)}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(
|
|
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(JH(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
|
|
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 w0{store;constructor(f,$={}){super(new $A(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
|
|
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 SD(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 B4,Y4;function kD(f,$){if(f!=="auto"&&f!=="hub")return;if($.hub?.endpoint?.trim())return;yJ($.hub?.workspaceRoot?.trim()||$.hub?.cwd?.trim()||process.cwd())}async function ID(f){await f.reconcileDeadSessions?.().catch(()=>{})}function HA(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 e9(void 0,{messagesArtifactUploader:f.messagesArtifactUploader})}}function WA(f,$,J){return new X0({sessionService:J??f.sessionService??HA(f),capabilities:f.capabilities,telemetry:f.telemetry,toolPolicies:f.toolPolicies,distinctId:$,fetch:f.fetch})}async function WH(f){if(B4)return B4;if(Y4)return await Y4;return Y4=(async()=>{return B4=HA(f),await ID(B4),B4})().finally(()=>{Y4=void 0}),await Y4}async function o1(f){let $=l$(f.distinctId);f.telemetry?.setDistinctId($);let J=SD(f);if(kD(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 i1({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 c$({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 N0({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 Q4({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 N0({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"}),WA(f,$)}return WA(f,$)}class V4{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=Oj(f),this.pendingPrompts=zj(f),this.automation=new rW(()=>{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 e8({workspaceRoot:X.workspaceRoot??process.cwd(),specs:{cronSpecsDir:X.cronSpecsDir??X.cronDir,scope:Jj(X.cronScope),workspaceRoot:X.workspaceRoot},runtimeHandlers:Wj({host:f,getExtensionContext:()=>e6({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 $=Kf(f.capabilities),J=await o1({...f,capabilities:$}),W=$j(f.automation),H=new V4(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 $=qj(f),J=await this.prepare?.($);try{let W=J?await J.applyToStartSessionInput($):$,H=await this.host.startSession(eW(W,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>e6({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 wj({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 VJ(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?eW(f.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>e6({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 jA={};N(jA,{resolvePluginConfigSearchPaths:()=>H8,resolveAndLoadAgentPlugins:()=>O1,resolveAgentPluginPaths:()=>b$,loadAgentPluginsFromPathsWithDiagnostics:()=>L0,loadAgentPluginsFromPaths:()=>K6,loadAgentPluginFromPath:()=>W8,discoverPluginModulePaths:()=>Q8});var yA={};N(yA,{resolveMcpServerRegistrations:()=>K4,resolveDefaultMcpSettingsPath:()=>P$,registerMcpServersFromSettingsFile:()=>$2,loadMcpSettingsFile:()=>F4,hasMcpSettingsFile:()=>f2,createMcpTools:()=>J2,createDisabledMcpToolPolicy:()=>y4,createDisabledMcpToolPolicies:()=>OJ,createDefaultMcpServerClientFactory:()=>e1,InMemoryMcpManager:()=>i$});import{spawn as mD}from"node:child_process";import{StringDecoder as BA}from"node:string_decoder";var xD="2024-11-05",gD=5000,vD=1500;function XA(f){return f instanceof Error?f.message:String(f)}function AA(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
|
|
554
|
-
`,"utf8")}class
|
|
553
|
+
`,"utf8");return Buffer.concat([J,$])}function PA(f){return Buffer.from(`${JSON.stringify(f)}
|
|
554
|
+
`,"utf8")}class HH{buffer="";decoder=new BA("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 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
|
|
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 rP{registration;process;nextRequestId=1;pending=new Map;framedParser=new oH;newlineParser=new eH;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:Zh,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},Ph),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 oH,this.newlineParser=new eH,this.stderrBuffer="",this.protocolMode=f;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=Qh($.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: ${vP(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}": ${vP(f)}.${J}`)),$.kill()}async request(f,$,J=jh){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,P)=>{let X=setTimeout(()=>{this.pending.delete(H),P(Error(`MCP request timed out for "${this.registration.name}" (${f}).`))},J);this.pending.set(H,{resolve:j,reject:P,timeout:X})});try{W.stdin.write(this.protocolMode==="framed"?uP(Q):cP(Q))}catch(j){let P=this.pending.get(H);if(P)clearTimeout(P.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"?uP(W):cP(W))}failAllPending(f){for(let[$,J]of this.pending)clearTimeout(J.timeout),this.pending.delete($),J.reject(f)}}function t1(){return(f)=>new rP(f)}import{existsSync as Xh,readFileSync as Vh}from"node:fs";import{resolveMcpSettingsPath as Yh}from"@cline/shared/storage";import{z as k}from"zod";var X4=k.record(k.string(),k.string()),lP=k.record(k.string(),k.unknown()),Bh=k.object({type:k.literal("stdio"),command:k.string().min(1),args:k.array(k.string()).optional(),cwd:k.string().min(1).optional(),env:X4.optional()}),Ah=k.object({type:k.literal("sse"),url:k.string().url(),headers:X4.optional()}),Rh=k.object({type:k.literal("streamableHttp"),url:k.string().url(),headers:X4.optional()}),Fh=k.discriminatedUnion("type",[Bh,Ah,Rh]),yh=k.object({transport:Fh,disabled:k.boolean().optional(),metadata:lP.optional()}),Kh=k.enum(["stdio","sse","http","streamableHttp"]).optional(),pP=k.object({type:k.enum(["stdio","sse","streamableHttp"]).optional(),transportType:Kh,disabled:k.boolean().optional(),metadata:lP.optional()});function f9(f){if(!f)return;if(f==="http")return"streamableHttp";return f}var Uh=pP.extend({command:k.string().min(1),args:k.array(k.string()).optional(),cwd:k.string().min(1).optional(),env:X4.optional()}).superRefine((f,$)=>{let J=f.type??f9(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})),Gh=pP.extend({url:k.string().url(),headers:X4.optional()}).superRefine((f,$)=>{let J=f.type??f9(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??f9(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}}),Th=k.union([yh,Uh,Gh]),hh=k.object({mcpServers:k.record(k.string(),Th)}).strict();function Q$(){return Yh()}function V4(f={}){let $=f.filePath??Q$(),J=Vh($,"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=hh.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 s1(f={}){let $=f.filePath??Q$();return Xh($)}function Y4(f={}){let $=V4(f);return Object.entries($.mcpServers).map(([J,W])=>({name:J,transport:W.transport,disabled:W.disabled,metadata:W.metadata}))}async function o1(f,$={}){let J=Y4($);for(let W of J)await f.registerServer(W);return J}function kf(){return Date.now()}function Dh(f){return f.map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}class r${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),W=await(await this.ensureConnectedClient($)).listTools(),H=Dh(W);return $.toolCache=H,$.toolCacheUpdatedAt=kf(),$.updatedAt=kf(),H})}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(),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 Mh}from"node:crypto";var iP=128,_h=/[^a-zA-Z0-9_-]+/g,nP=8,Lh=1,zh="mcp_tool";function Oh(f){return Mh("sha1").update(f).digest("hex").slice(0,nP)}function Nh(f){return f.replace(_h,"_")}var OJ=({serverName:f,toolName:$})=>{let J=`${f}__${$}`,W=Nh(J);if(W===J&&J.length<=iP)return J;let H=Oh(J),Q=iP-Lh-nP;return`${W.slice(0,Q)||zh}_${H}`};function B4(f){return{[(f.nameTransform??OJ)({serverName:f.serverName,toolName:f.toolName})]:{enabled:!1}}}function NJ(f){let $={};for(let J of f.toolNames)Object.assign($,B4({serverName:f.serverName,toolName:J,nameTransform:f.nameTransform}));return $}import{createTool as qh}from"@cline/shared";function bh(f,$){let J=$.description?.trim();if(J)return J;return`Execute MCP tool "${$.name}" from server "${f}".`}async function e1(f){let $=await f.provider.listTools(f.serverName),J=f.nameTransform??OJ;return $.map((W)=>{let H=J({serverName:f.serverName,toolName:W.name});return qh({name:H,description:bh(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 oP={};N(oP,{toHookConfigFileName:()=>H8,runSubprocessEvent:()=>f2,runHook:()=>J2,resolveHooksConfigSearchPaths:()=>J8,parseHookEventPayload:()=>$2,mergeAgentHooks:()=>w$,listHookConfigFiles:()=>l0,createSubprocessHooks:()=>wJ,createHookConfigFileHooks:()=>Q8,createHookConfigFileExtension:()=>L1,createHookAuditHooks:()=>_1,createAgentHooksExtension:()=>D1,HookEventPayloadSchema:()=>bJ,HookEventNameSchema:()=>qJ,HookConfigFileName:()=>M1,HOOK_CONFIG_FILE_EVENT_MAP:()=>W8,HOOKS_CONFIG_DIRECTORY_NAME:()=>F6});import{HookEventNameSchema as qJ,HookEventPayloadSchema as bJ,parseHookEventPayload as $2,resolveHookSessionContext as Ih}from"@cline/shared";import{z as l$}from"zod";import{spawn as wh}from"node:child_process";import{augmentNodeCommandForDebug as Ch,withResolvedClineBuildEnv as Eh}from"@cline/shared";function Sh(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 kh(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 mh(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 f2(f,$){let J=Ch($.command,{env:$.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!$.detached,H=wh(J[0],J.slice(1),{cwd:$.cwd,env:Eh($.env),stdio:W?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W}),Q=new Promise((B)=>{H.once("spawn",()=>{try{$.onSpawn?.({command:J,pid:H.pid??void 0,detached:W})}catch{}B()})}),Z=new Promise((B,A)=>{H.once("error",(R)=>{A(kh(R,J))})});if(await mh(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="",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}=Sh(j);B({exitCode:A,stdout:j,stderr:P,parsedJson:R,parseError:U,timedOut:X})})});return await Promise.race([Y,Z])}var xh=l$.object({contextModification:l$.string().optional(),cancel:l$.boolean().optional(),review:l$.boolean().optional(),errorMessage:l$.string().optional(),context:l$.string().optional(),overrideInput:l$.unknown().optional()}).passthrough();var gh=["agent","hook"];async function J2(f,$={}){let J=$.command??gh;return await f2(f,{command:J,cwd:$.cwd,env:$.env,detached:$.detached,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn})}function sP(f){return f instanceof Error?f:Error(String(f))}function vh(f){if(!f||typeof f!=="object")return;let $=xh.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 tP(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 O0(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:Ih(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 uh(f){return{name:f.name,message:f.message,stack:f.stack}}function ch(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function dh(f){return{agentId:f.snapshot.agentId,conversationId:f.snapshot.conversationId??f.snapshot.runId??f.snapshot.agentId,parentAgentId:f.snapshot.parentAgentId??null}}function rh(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function lh(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 ph(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 p$(f,$){try{let J=await J2(f,{command:$.command,cwd:$.cwd,env:$.env,detached:!0,onSpawn:$.onSpawn});$.onDispatch?.({payload:f,result:J,detached:!0})}catch(J){$.onDispatchError?.(sP(J),f)}}function wJ(f={}){return{hooks:{beforeRun:async(j)=>{let P=dh(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 p$(V,f)}else{let V={...O0("agent_start",P,f),hookName:"agent_start",taskStart:{taskMetadata:{}}};await p$(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:tP(j.input)}};try{let V=await J2(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 ph(vh(V?.parsedJson))}catch(V){f.onDispatchError?.(sP(V),X);return}},afterTool:async(j)=>{let P=lh(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:tP(P.input),result:typeof P.output==="string"?P.output:JSON.stringify(P.output),success:!P.error,executionTimeMs:P.durationMs}};await p$(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 p$(B,f);return}let V=P.status==="aborted"||ch(P.error?.message)?"agent_abort":"agent_error",Y=V==="agent_error"?{...O0(V,X,f),hookName:V,iteration:P.iterations,error:uh(P.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...O0(V,X,f),hookName:V,reason:P.error?.message,taskCancel:{taskMetadata:{}}};await p$(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:rh(j.message.content),attachments:[]}};await p$(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 p$(Y,f)}}}var fV={};N(fV,{writeHubDiscovery:()=>KJ,withHubStartupLock:()=>UJ,verifyHubConnection:()=>f0,truncateNotificationBody:()=>y4,toHubHealthUrl:()=>hH,stopLocalHubServerGracefully:()=>CH,startHubWebSocketServer:()=>t$,startHubServer:()=>oX,spawnDetachedHubServer:()=>u1,sendHubCommand:()=>HX,restartLocalHubIfIdleAfterStartupTimeout:()=>hJ,resolveWorkspaceHubOwnerContext:()=>aj,resolveSharedHubOwnerContext:()=>Qf,resolveHubUrl:()=>H9,resolveHubOwnerContext:()=>M0,resolveHubEndpointOptions:()=>Sf,resolveHubBuildId:()=>J$,resolveDefaultHubPort:()=>v1,resolveDefaultHubPathname:()=>zH,resolveDefaultHubHost:()=>LH,resolveCompatibleLocalHubUrl:()=>f4,resolveClineDir:()=>lj,resolveClineDataDir:()=>t8,requestHubShutdown:()=>e8,rememberRecoverableLocalHubUrl:()=>W$,readHubDiscovery:()=>Zf,probeHubServer:()=>Bf,probeHubConnection:()=>WX,prewarmDetachedHubServer:()=>GJ,normalizeHubWebSocketUrl:()=>H$,isHubReconnectableTransportError:()=>bH,isHubCommandTimeoutError:()=>TJ,isDiscoveryFilePresent:()=>ij,ensureHubWebSocketServer:()=>vJ,ensureHubServer:()=>eX,ensureDetachedHubServer:()=>sj,ensureCompatibleLocalHubUrl:()=>g$,createLocalHubScheduleRuntimeHandlers:()=>uJ,createInMemoryHubOwnerContext:()=>pj,createHubServerUrl:()=>lf,createHubAuthToken:()=>yJ,createConfiguredTelemetryService:()=>i$,createConfiguredTelemetryHandle:()=>j2,connectToHub:()=>kJ,clearHubDiscovery:()=>Ef,NodeHubClient:()=>pf,NativeHubTransportAdapter:()=>h4,HubUIClient:()=>Z9,HubTransportError:()=>yf,HubSessionClient:()=>Q9,HubServerTransport:()=>X2,HubScheduleService:()=>H2,HubScheduleCommandService:()=>W2,HubCommandError:()=>c1,DEFAULT_HUB_PORT:()=>MH,DEFAULT_HUB_PATHNAME:()=>_H,DEFAULT_HUB_HOST:()=>DH,BrowserWebSocketHubAdapter:()=>T4});import{createSessionId as ih}from"@cline/shared";function mf(f,$){return{version:f.version,requestId:f.requestId,ok:!0,payload:$}}function eP(f,$,J){return{version:f.version,requestId:f.requestId??ih("hubreq_"),ok:!1,error:{code:$,message:J}}}class W2{schedules;constructor(f){this.schedules=f}async handleCommand(f){try{switch(f.command){case"schedule.create":return mf(f,{schedule:this.schedules.createSchedule(this.toCreateInput(f.payload??{}))});case"schedule.list":return mf(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 mf(f,{schedule:this.schedules.getSchedule(String(f.payload?.scheduleId??""))});case"schedule.update":return mf(f,{schedule:this.schedules.updateSchedule(String(f.payload?.scheduleId??""),this.toUpdateInput(f.payload??{}))});case"schedule.delete":return mf(f,{deleted:this.schedules.deleteSchedule(String(f.payload?.scheduleId??""))});case"schedule.enable":return mf(f,{schedule:this.schedules.resumeSchedule(String(f.payload?.scheduleId??""))});case"schedule.disable":return mf(f,{schedule:this.schedules.pauseSchedule(String(f.payload?.scheduleId??""))});case"schedule.trigger":return mf(f,{execution:await this.schedules.triggerScheduleNow(String(f.payload?.scheduleId??""))});case"schedule.list_executions":return mf(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 mf(f,{stats:this.schedules.getScheduleStats(String(f.payload?.scheduleId??""))});case"schedule.active":return mf(f,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return mf(f,{runs:this.schedules.getUpcomingRuns(typeof f.payload?.limit==="number"?f.payload.limit:void 0)});default:return eP(f,"unsupported_command",`Unsupported hub schedule command: ${f.command}`)}}catch($){return eP(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:$}}}function EJ(f){return f?new Date(f).getTime():void 0}function nh(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function CJ(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:EJ(f.nextRunAt),lastRunAt:EJ(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:nh(f)}}function ah(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function fX(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:EJ(f.startedAt),endedAt:EJ(f.completedAt),status:ah(f.status),errorMessage:f.error}}class H2{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new i8({dbPath:f.dbPath}),this.materializer=new c8({store:this.store}),this.runner=new d8({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(QH(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return CJ(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?CJ($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>CJ($))}updateSchedule(f,$){if($.cronPattern!==void 0)QH($.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?CJ(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 fX(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 fX(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}))}}SJ();function UD(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 GD="cline-hub-auth.";function TD(f){return f.host!==void 0||f.port!==void 0||f.pathname!==void 0}function hD(f,$){let J=new URL(f),W=new URL($);return J.search="",J.hash="",W.search="",W.hash="",J.toString()===W.toString()}async function DD(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=Qf(),W=await Zf(J.discoveryPath);if(W?.url&&hD(f.toString(),W.url))return W.authToken;return}async function H9(f={}){let $=Sf(f);if(!TD(f)){let J=Qf(),W=await Zf(J.discoveryPath);if(W?.url)return W.url}return lf($.host,$.port,$.pathname)}async function kJ(f){return await new Promise(($,J)=>{(async()=>{let W=new URL(f),H=await DD(W);W.hash="";let Q=new WebSocket(W.toString(),H?[`${GD}${H}`]: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(UD(P,f))})})().catch(J)})}async function WX(f){try{return(await kJ(f)).close(),!0}catch{return!1}}async function HX(f,$){let J=await H9(f),W=await kJ(J);try{return await W.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{W.close()}}function j0(f){return f?JSON.parse(JSON.stringify(f)):{}}function mJ(f){let $=f?.session&&typeof f.session==="object"?f.session:void 0;if(!$)return;let J=$.metadata&&typeof $.metadata==="object"?j0($.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 QX(f,$){return f.error?.message??`hub command failed: ${$}`}function MD(f){let $=j0(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 _D(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 LD(f){let $=f.sessionId?.trim();if(!$)return;switch(f.event){case"iteration.started":return{sessionId:$,eventType:"runtime.chat.iteration_start",payload:j0(f.payload)};case"iteration.finished":return{sessionId:$,eventType:"runtime.chat.iteration_end",payload:j0(f.payload)};case"assistant.delta":return{sessionId:$,eventType:"runtime.chat.text_delta",payload:j0(f.payload)};case"tool.started":return{sessionId:$,eventType:"runtime.chat.tool_call_start",payload:j0(f.payload)};case"tool.finished":return{sessionId:$,eventType:"runtime.chat.tool_call_end",payload:j0(f.payload)};case"approval.requested":return{sessionId:$,eventType:"approval.requested",payload:j0(f.payload)};case"run.aborted":return{sessionId:$,eventType:"runtime.chat.aborted",payload:j0(f.payload)};case"run.failed":return{sessionId:$,eventType:"runtime.chat.failed",payload:MD(f.payload)};case"run.completed":return{sessionId:$,eventType:"runtime.chat.completed",payload:j0(f.payload)};default:return}}class Q9{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=mJ($.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 mJ($.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(QX(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(QX(H,"session.restore"));let Q=mJ(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=_D(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)=>mJ({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=LD(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 Z9{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}})}}function zD(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(`
|
|
559
|
-
`).trim()||void 0}var ZX=120,j9="...";function y4(f){let $=f.trim();if(!$)return"";if(Buffer.byteLength($,"utf8")<=ZX)return $;let J=ZX-Buffer.byteLength(j9,"utf8");if(J<=0)return j9;let W="";for(let H of $){if(Buffer.byteLength(W+H,"utf8")>J)break;W+=H}return`${W}${j9}`}async function jX(f){let $=f?.sessionId?.trim()||"unknown",J=typeof f?.metadata?.messagesPath==="string"?f.metadata.messagesPath:void 0,H=[...await x$(J)].reverse().find((P)=>P.role==="assistant"),Q=H?zD(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:y4(Q&&Q.length>0?Q:j.length>0?j:Z),severity:"info"}}import{createSessionId as HM}from"@cline/shared";import{createSessionId as bD}from"@cline/shared";import{createSessionId as qD}from"@cline/shared";function OD(f){switch(f){case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function ND(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 IJ(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:OD(f.status),participants:$?[...$.participants.values()]:[],metadata:ND(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 xJ(f){return f&&typeof f==="object"&&!Array.isArray(f)?f:void 0}function hf(f){if(typeof f.payload?.sessionId==="string")return f.payload.sessionId.trim();return f.sessionId?.trim()??""}function n$(f,$,J){return{version:"v1",event:f,eventId:qD("hevt_"),sessionId:J,timestamp:Date.now(),payload:$}}async function If(f,$){let J=await f.sessionHost.getSession($);if(!J)return;return IJ(J,f.sessionState.get($))}async function xf(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 $0({session:J,messages:W,usage:H})}function gJ(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 P9(f,$){let J=bD("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 X9(f,$,J){let W=f.pendingApprovals.get($);if(!W)return;return f.pendingApprovals.delete($),W.resolve(J),{sessionId:W.sessionId}}function V9(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 PX(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=X9(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)),v($,{approvalId:J,approved:Q})}import{createSessionId as ED}from"@cline/shared";function wD(f){if(f instanceof Error)return{name:f.name,message:f.message,stack:f.stack};if(f===void 0)return;return f}var XX={debug:10,info:20,warn:30,error:40,silent:50};function CD(){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(XX[f]<XX[CD()])return;let W=JSON.stringify({ts:new Date().toISOString(),level:f,component:"hub",message:$,...Object.fromEntries(Object.entries(J).map(([H,Q])=>[H,wD(Q)]).filter(([,H])=>H!==void 0))});if(f==="error"||f==="warn"){console.error(`[hub] ${W}`);return}console.log(`[hub] ${W}`)}function Y9(f,$){let J=$ instanceof Error?$.stack||$.message:String($);x("error",f,{error:J})}async function VX(f,$,J,W,H,Q){let Z=ED("capreq_"),j=performance.now();return x("info","capability.request.start",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H}),await new Promise((P,X)=>{f.pendingCapabilityRequests.set(Z,{sessionId:$,targetClientId:H,capabilityName:J,onProgress:Q,resolve:(V)=>{if(x(V.ok?"info":"warn","capability.request.end",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H,ok:V.ok,error:V.error,durationMs:Math.round(performance.now()-j)}),!V.ok){X(Error(V.error||`Capability ${J} was rejected by ${H}.`));return}P(V.payload)}}),f.publish(f.buildEvent("capability.requested",{requestId:Z,targetClientId:H,capabilityName:J,payload:W},$)),x("info","capability.request.published",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H})})}function YX(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),v($,{requestId:J})}function Z$(f,$,J){let W=0;for(let[H,Q]of[...f.pendingCapabilityRequests.entries()]){if(!$({requestId:H,...Q}))continue;f.pendingCapabilityRequests.delete(H),x("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 BX(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 v($,Z)}catch(Q){return m($,"capability_request_failed",Q instanceof Error?Q.message:String(Q))}}function AX(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 x(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)),v($,{requestId:J,ok:j})}import{createSessionId as SD}from"@cline/shared";function RX(f,$){let J=$.payload,W=J?.clientId?.trim()||$.clientId?.trim()||SD("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()})),v($,{clientId:W})}function FX(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=xJ($.payload?.metadata);if(W.lastSeenAt=Date.now(),H)W.metadata=JSON.parse(JSON.stringify(H));return v($)}function yX(f,$,J){let W=$.clientId?.trim();if(W)f.clients.delete(W),J(W),f.publish(f.buildEvent("hub.client.disconnected",{clientId:W}));return v($)}function KX(f,$){return v($,{clients:[...f.clients.values()]})}var kD=30000;function mD(f){if(f==="aborted")return"run.aborted";if(f==="error"||f==="failed")return"run.failed";return"run.completed"}function ID(f){if(f.finishReason!=="error")return;return f.text.trim()||void 0}function xD(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 gD(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 V=Math.round(performance.now()-H);x("warn","run.heartbeat",{...Z,elapsedMs:V}),f.publish(f.buildEvent("run.heartbeat",{requestId:$.requestId,elapsedMs:V,...W?{timeoutMs:W}:{}},J.sessionId))},kD),P=f.sessionHost.runTurn(J);P.then((V)=>{if(!Q)return;x("warn","run.late_end",{...Z,elapsedMs:Math.round(performance.now()-H),finishReason:V?.finishReason})},(V)=>{if(!Q)return;x("error","run.late_error",{...Z,elapsedMs:Math.round(performance.now()-H),error:V})});let X;try{if(!W)return await P;return await Promise.race([P,new Promise((V,Y)=>{X=setTimeout(()=>{let B=`Hub run ${$.command} timed out after ${W}ms.`;Q=!0,clearInterval(j),Y(Error(B)),x("error","run.timeout",{...Z,elapsedMs:Math.round(performance.now()-H)}),V9(f,(A)=>A.sessionId===J.sessionId,B),Z$(f,(A)=>A.sessionId===J.sessionId,B),f.sessionHost.abort(J.sessionId,B).catch((A)=>{x("error","run.timeout_abort_failed",{...Z,error:A})})},W)})])}finally{if(Q=!0,clearInterval(j),X)clearTimeout(X)}}async function UX(f,$){let J=hf($),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((V)=>typeof V==="string"):void 0,j=xD(W);f.suppressNextTerminalEventBySession.set(J,"run.start.reply");let P;try{P=await gD(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(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=ID(P);if(f.publish(f.buildEvent(mD(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 GX(f,$){let J=hf($),W=typeof $.payload?.reason==="string"?$.payload.reason:"Run was aborted before pending approval or capability request was resolved.";return V9(f,(H)=>H.sessionId===J,W),await f.sessionHost.abort(J,$.payload?.reason),Z$(f,(H)=>H.sessionId===J,W),f.publish(f.buildEvent("run.aborted",{reason:W},J)),v($,{applied:!0})}async function TX(f,$){let J=$2($.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 hX(f,$){switch($.type){case"chunk":return;case"agent_event":vD(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([If(f,$.payload.sessionId),xf(f,$.payload.sessionId)]);if(J)f.publish(f.buildEvent("session.updated",{session:J,...W?{snapshot:W}:{}},$.payload.sessionId));return}case"ended":await uD(f,$);return;default:return}}function vD(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==="done")f.publish(f.buildEvent("agent.done",{reason:W.reason,text:W.text,iterations:W.iterations,usage:W.usage},J))}async function uD(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([If(f,$.payload.sessionId),xf(f,$.payload.sessionId)]);if($.payload.reason==="completed"){let Z=await jX(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 OX,parseRuntimeConfigExtensions as NX}from"@cline/shared";var LX={};N(LX,{SessionVersioningService:()=>j$,SessionVersioningError:()=>Df});var _X={};N(_X,{trimMessagesToCheckpoint:()=>MX,trimMessagesBeforeCheckpoint:()=>A9,readSessionCheckpointHistory:()=>K4,createRestoredCheckpointMetadata:()=>B9,createCheckpointRestorePlan:()=>R9,applyCheckpointToWorktree:()=>F9});import{execFile as cD}from"node:child_process";import{promisify as dD}from"node:util";var P2=dD(cD);function K4(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 B9(f,$){let J=K4(f).filter((H)=>H.runCount<=$),W=J.at(-1);return W?{latest:W,history:J}:void 0}function rD(f,$){return f.reduce((J,W)=>{if(W.runCount>$)return J;if(!J||W.runCount>J.runCount)return W;return J},void 0)}function DX(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 MX(f,$){let J=DX(f,$);return f.slice(0,J+1)}function A9(f,$){let J=DX(f,$);return f.slice(0,J)}function R9(f){let $=f.checkpointRunCount;if(!Number.isInteger($)||$<1)throw Error("checkpointRunCount must be a positive integer");let J=rD(K4(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:MX(f.messages??[],$)}:{}}}async function F9(f,$){if((await P2("git",["-C",f,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${f} is not a git repository`);if(await P2("git",["-C",f,"cat-file","-e",`${$.ref}^{commit}`],{windowsHide:!0}),await P2("git",["-C",f,"reset","--hard"],{windowsHide:!0}),await P2("git",["-C",f,"clean","-fd"],{windowsHide:!0}),$.kind==="commit"){await P2("git",["-C",f,"reset","--hard",$.ref],{windowsHide:!0});return}await P2("git",["-C",f,"stash","apply",$.ref],{windowsHide:!0})}class Df extends Error{code;constructor(f,$){super($);this.code=f;this.name="SessionVersioningError"}}function lD(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 j${async restoreCheckpoint(f){let $=f.restore?.messages!==!1,J=f.restore?.workspace!==!1,W=lD({sessionId:f.sessionId,restoreMessages:$,restoreWorkspace:J,requiresStart:f.start===void 0,checkpointRunCount:f.checkpointRunCount}),H=await f.getSession(W);if(!H)throw new Df("session_not_found",`Session ${W} not found`);let Q=$?await f.readMessages(W):void 0;if($&&Q?.length===0)throw new Df("session_messages_not_found",`No messages found for session ${W}`);let Z=R9({session:H,messages:Q,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restoreMessages:$});if(J)await(f.applyWorkspaceCheckpoint??F9)(Z.cwd,Z.checkpoint);let j=$0({session:H,messages:Q});if(!$)return{checkpoint:Z.checkpoint,sourceSnapshot:j};let P=B9(H,f.checkpointRunCount),X=f.restore?.omitCheckpointMessageFromSession?A9(Q??[],f.checkpointRunCount):Z.messages??[],V={sourceSession:H,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??SQ)(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:$0({session:R,messages:X})}:{}}}}import{HUB_CHECKPOINT_CAPABILITY as qm,HUB_COMPACTION_CAPABILITY as bm,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as wm,HUB_HOOK_CAPABILITY_PREFIX as Cm,HUB_MISTAKE_LIMIT_CAPABILITY as Em,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Sm,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as km,isHubToolExecutorName as pD}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as vm,HUB_COMPACTION_CAPABILITY as um,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as cm,HUB_HOOK_CAPABILITY_PREFIX as dm,HUB_MISTAKE_LIMIT_CAPABILITY as rm,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as lm,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as pm}from"@cline/shared";var iD=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function a$(f){return f&&typeof f==="object"&&!Array.isArray(f)?JSON.parse(JSON.stringify(f)):void 0}function nD(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=a$(f.inputSchema);if(!J||!W||!Q||!H||$.has(H))return;return $.add(H),{kind:"tool",capabilityName:H,name:J,description:W,inputSchema:Q,...a$(f.lifecycle)?{lifecycle:a$(f.lifecycle)}:{}}}function K9(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=nD(H,J);if(j)$.push(j);continue}if(Q==="toolExecutor"){let j=H.executor;if(!pD(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,...a$(H.config)?{config:a$(H.config)}:{}});continue}if(Q==="checkpoint"){J.add(Z),$.push({kind:"checkpoint",capabilityName:Z,...a$(H.config)?{config:a$(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 zX(f){return{agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,metadata:f.metadata}}function aD(f){return Object.hasOwn(f,"update")?f.update:f}function U4(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function tD(f){let $=(f??[]).map(U4).filter(Boolean);return $.length>0?new Set($):void 0}function sD(f,$,J){if(!J)return!0;let W=U4(f),H=U4($),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 y9(f,$){let J=tD($);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)=>sD(W.id,W.name,J))}function oD(f,$){let J=async(W,H)=>{let Q=U4(W),j=y9(f,$).filter((B)=>B.id===Q||U4(B.name)===Q||B.id.endsWith(`:${Q}`)).filter((B)=>!B.disabled);if(j.length!==1)return j.length>1?`Skill "${W}" is ambiguous. Use one of: ${j.map((B)=>B.id).join(", ")}`:`Skill "${W}" not found.`;let P=j[0].skill,X=H?.trim(),V=X?`
|
|
560
|
-
<command-args>${
|
|
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 QH{buffer="";decoder=new BA("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 YA{registration;process;nextRequestId=1;pending=new Map;framedParser=new HH;newlineParser=new QH;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:xD,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},vD),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 HH,this.newlineParser=new QH,this.stderrBuffer="",this.protocolMode=f;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=mD($.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: ${XA(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}": ${XA(f)}.${J}`)),$.kill()}async request(f,$,J=gD){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"?AA(Q):PA(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"?AA(W):PA(W))}failAllPending(f){for(let[$,J]of this.pending)clearTimeout(J.timeout),this.pending.delete($),J.reject(f)}}function e1(){return(f)=>new YA(f)}import{existsSync as uD,readFileSync as cD}from"node:fs";import{resolveMcpSettingsPath as dD}from"@cline/shared/storage";import{z as I}from"zod";var R4=I.record(I.string(),I.string()),VA=I.record(I.string(),I.unknown()),rD=I.object({type:I.literal("stdio"),command:I.string().min(1),args:I.array(I.string()).optional(),cwd:I.string().min(1).optional(),env:R4.optional()}),lD=I.object({type:I.literal("sse"),url:I.string().url(),headers:R4.optional()}),pD=I.object({type:I.literal("streamableHttp"),url:I.string().url(),headers:R4.optional()}),iD=I.discriminatedUnion("type",[rD,lD,pD]),nD=I.object({transport:iD,disabled:I.boolean().optional(),metadata:VA.optional()}),aD=I.enum(["stdio","sse","http","streamableHttp"]).optional(),RA=I.object({type:I.enum(["stdio","sse","streamableHttp"]).optional(),transportType:aD,disabled:I.boolean().optional(),metadata:VA.optional()});function ZH(f){if(!f)return;if(f==="http")return"streamableHttp";return f}var tD=RA.extend({command:I.string().min(1),args:I.array(I.string()).optional(),cwd:I.string().min(1).optional(),env:R4.optional()}).superRefine((f,$)=>{let J=f.type??ZH(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})),sD=RA.extend({url:I.string().url(),headers:R4.optional()}).superRefine((f,$)=>{let J=f.type??ZH(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??ZH(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}}),oD=I.union([nD,tD,sD]),eD=I.object({mcpServers:I.record(I.string(),oD)}).strict();function P$(){return dD()}function F4(f={}){let $=f.filePath??P$(),J=cD($,"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=eD.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 f2(f={}){let $=f.filePath??P$();return uD($)}function K4(f={}){let $=F4(f);return Object.entries($.mcpServers).map(([J,W])=>({name:J,transport:W.transport,disabled:W.disabled,metadata:W.metadata}))}async function $2(f,$={}){let J=K4($);for(let W of J)await f.registerServer(W);return J}function vf(){return Date.now()}function f_(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=f_(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 $_}from"node:crypto";var FA=128,J_=/[^a-zA-Z0-9_-]+/g,KA=8,W_=1,H_="mcp_tool";function Q_(f){return $_("sha1").update(f).digest("hex").slice(0,KA)}function Z_(f){return f.replace(J_,"_")}var hJ=({serverName:f,toolName:$})=>{let J=`${f}__${$}`,W=Z_(J);if(W===J&&J.length<=FA)return J;let H=Q_(J),Q=FA-W_-KA;return`${W.slice(0,Q)||H_}_${H}`};function y4(f){return{[(f.nameTransform??hJ)({serverName:f.serverName,toolName:f.toolName})]:{enabled:!1}}}function OJ(f){let $={};for(let J of f.toolNames)Object.assign($,y4({serverName:f.serverName,toolName:J,nameTransform:f.nameTransform}));return $}import{createTool as j_}from"@cline/shared";function X_(f,$){let J=$.description?.trim();if(J)return J;return`Execute MCP tool "${$.name}" from server "${f}".`}async function J2(f){let $=await f.provider.listTools(f.serverName),J=f.nameTransform??hJ;return $.map((W)=>{let H=J({serverName:f.serverName,toolName:W.name});return j_({name:H,description:X_(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 TA={};N(TA,{toHookConfigFileName:()=>X8,runSubprocessEvent:()=>W2,runHook:()=>Q2,resolveHooksConfigSearchPaths:()=>Z8,parseHookEventPayload:()=>H2,mergeAgentHooks:()=>k$,listHookConfigFiles:()=>n0,createSubprocessHooks:()=>qJ,createHookConfigFileHooks:()=>A8,createHookConfigFileExtension:()=>w1,createHookAuditHooks:()=>q1,createAgentHooksExtension:()=>z1,HookEventPayloadSchema:()=>NJ,HookEventNameSchema:()=>zJ,HookConfigFileName:()=>N1,HOOK_CONFIG_FILE_EVENT_MAP:()=>j8,HOOKS_CONFIG_DIRECTORY_NAME:()=>G6});import{HookEventNameSchema as zJ,HookEventPayloadSchema as NJ,parseHookEventPayload as H2,resolveHookSessionContext as F_}from"@cline/shared";import{z as n$}from"zod";import{spawn as A_}from"node:child_process";import{augmentNodeCommandForDebug as P_,withResolvedClineBuildEnv as B_}from"@cline/shared";function Y_(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 V_(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 R_(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 W2(f,$){let J=P_($.command,{env:$.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!$.detached,H=A_(J[0],J.slice(1),{cwd:$.cwd,env:B_($.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(V_(R,J))})});if(await R_(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}=Y_(j);Y({exitCode:V,stdout:j,stderr:X,parsedJson:R,parseError:U,timedOut:A})})});return await Promise.race([B,Z])}var K_=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 y_=["agent","hook"];async function Q2(f,$={}){let J=$.command??y_;return await W2(f,{command:J,cwd:$.cwd,env:$.env,detached:$.detached,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn})}function GA(f){return f instanceof Error?f:Error(String(f))}function U_(f){if(!f||typeof f!=="object")return;let $=K_.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 UA(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 b0(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:F_(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 G_(f){return{name:f.name,message:f.message,stack:f.stack}}function T_(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function D_(f){return{agentId:f.snapshot.agentId,conversationId:f.snapshot.conversationId??f.snapshot.runId??f.snapshot.agentId,parentAgentId:f.snapshot.parentAgentId??null}}function __(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function M_(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 L_(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 Q2(f,{command:$.command,cwd:$.cwd,env:$.env,detached:!0,onSpawn:$.onSpawn});$.onDispatch?.({payload:f,result:J,detached:!0})}catch(J){$.onDispatchError?.(GA(J),f)}}function qJ(f={}){return{hooks:{beforeRun:async(j)=>{let X=D_(j);if((f.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let P={...b0("agent_resume",X,f),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await a$(P,f)}else{let P={...b0("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={...b0("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:UA(j.input)}};try{let P=await Q2(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 L_(U_(P?.parsedJson))}catch(P){f.onDispatchError?.(GA(P),A);return}},afterTool:async(j)=>{let X=M_(j),A={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},P={...b0("tool_result",A,f),hookName:"tool_result",iteration:j.snapshot.iteration,tool_result:X,postToolUse:{toolName:X.name,parameters:UA(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={...b0("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"||T_(X.error?.message)?"agent_abort":"agent_error",B=P==="agent_error"?{...b0(P,A,f),hookName:P,iteration:X.iterations,error:G_(X.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...b0(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={...b0("prompt_submit",X,f),hookName:"prompt_submit",userPromptSubmit:{prompt:__(j.message.content),attachments:[]}};await a$(A,f)}},shutdown:async({agentId:j,conversationId:X,parentAgentId:A,reason:P})=>{let B={...b0("session_shutdown",{agentId:j,conversationId:X,parentAgentId:A},f),hookName:"session_shutdown",reason:P};await a$(B,f)}}}var _P={};N(_P,{writeHubDiscovery:()=>FJ,withHubStartupLock:()=>KJ,verifyHubConnection:()=>J0,truncateNotificationBody:()=>D4,toHubHealthUrl:()=>h9,stopLocalHubServerGracefully:()=>m9,startHubWebSocketServer:()=>o$,startHubServer:()=>TP,spawnDetachedHubServerWithRetry:()=>r1,spawnDetachedHubServer:()=>b9,sendHubCommand:()=>OA,restartLocalHubIfIdleAfterStartupTimeout:()=>GJ,resolveWorkspaceHubOwnerContext:()=>KX,resolveSharedHubOwnerContext:()=>Af,resolveHubUrl:()=>PH,resolveHubOwnerContext:()=>z0,resolveHubEndpointOptions:()=>gf,resolveHubBuildId:()=>Z$,resolveDefaultHubPort:()=>d1,resolveDefaultHubPathname:()=>w9,resolveDefaultHubHost:()=>q9,resolveCompatibleLocalHubUrl:()=>Q4,resolveClineDir:()=>YX,resolveClineDataDir:()=>$4,requestHubShutdown:()=>H4,rememberRecoverableLocalHubUrl:()=>j$,readHubDiscovery:()=>Bf,probeHubServer:()=>Uf,probeHubConnection:()=>hA,prewarmDetachedHubServer:()=>yJ,normalizeHubWebSocketUrl:()=>X$,isHubReconnectableTransportError:()=>k9,isHubCommandTimeoutError:()=>UJ,isDiscoveryFilePresent:()=>RX,ensureHubWebSocketServer:()=>xJ,ensureHubServer:()=>DP,ensureDetachedHubServer:()=>UX,ensureCompatibleLocalHubUrl:()=>c$,createLocalHubScheduleRuntimeHandlers:()=>gJ,createInMemoryHubOwnerContext:()=>VX,createHubServerUrl:()=>af,createHubAuthToken:()=>RJ,createConfiguredTelemetryService:()=>C0,createConfiguredTelemetryHandle:()=>P2,connectToHub:()=>EJ,clearHubDiscovery:()=>xf,NodeHubClient:()=>tf,NativeHubTransportAdapter:()=>O4,HubUIClient:()=>YH,HubTransportError:()=>Df,HubSessionClient:()=>BH,HubServerTransport:()=>Y2,HubScheduleService:()=>j2,HubScheduleCommandService:()=>Z2,HubCommandError:()=>l1,DEFAULT_HUB_PORT:()=>z9,DEFAULT_HUB_PATHNAME:()=>N9,DEFAULT_HUB_HOST:()=>O9,BrowserWebSocketHubAdapter:()=>h4});import{createSessionId as h_}from"@cline/shared";function uf(f,$){return{version:f.version,requestId:f.requestId,ok:!0,payload:$}}function DA(f,$,J){return{version:f.version,requestId:f.requestId??h_("hubreq_"),ok:!1,error:{code:$,message:J}}}class Z2{schedules;constructor(f){this.schedules=f}async handleCommand(f){try{switch(f.command){case"schedule.create":return uf(f,{schedule:this.schedules.createSchedule(this.toCreateInput(f.payload??{}))});case"schedule.list":return uf(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 uf(f,{schedule:this.schedules.getSchedule(String(f.payload?.scheduleId??""))});case"schedule.update":return uf(f,{schedule:this.schedules.updateSchedule(String(f.payload?.scheduleId??""),this.toUpdateInput(f.payload??{}))});case"schedule.delete":return uf(f,{deleted:this.schedules.deleteSchedule(String(f.payload?.scheduleId??""))});case"schedule.enable":return uf(f,{schedule:this.schedules.resumeSchedule(String(f.payload?.scheduleId??""))});case"schedule.disable":return uf(f,{schedule:this.schedules.pauseSchedule(String(f.payload?.scheduleId??""))});case"schedule.trigger":return uf(f,{execution:await this.schedules.triggerScheduleNow(String(f.payload?.scheduleId??""))});case"schedule.list_executions":return uf(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 uf(f,{stats:this.schedules.getScheduleStats(String(f.payload?.scheduleId??""))});case"schedule.active":return uf(f,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return uf(f,{runs:this.schedules.getUpcomingRuns(typeof f.payload?.limit==="number"?f.payload.limit:void 0)});default:return DA(f,"unsupported_command",`Unsupported hub schedule command: ${f.command}`)}}catch($){return DA(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:$}}}function bJ(f){return f?new Date(f).getTime():void 0}function O_(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function wJ(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:bJ(f.nextRunAt),lastRunAt:bJ(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:O_(f)}}function z_(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function _A(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:bJ(f.startedAt),endedAt:bJ(f.completedAt),status:z_(f.status),errorMessage:f.error}}class j2{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new o8({dbPath:f.dbPath}),this.materializer=new i8({store:this.store}),this.runner=new n8({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(X9(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return wJ(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?wJ($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>wJ($))}updateSchedule(f,$){if($.cronPattern!==void 0)X9($.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?wJ(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 _A(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 _A(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}))}}CJ();function t_(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 s_="cline-hub-auth.";function o_(f){return f.host!==void 0||f.port!==void 0||f.pathname!==void 0}function e_(f,$){let J=new URL(f),W=new URL($);return J.search="",J.hash="",W.search="",W.hash="",J.toString()===W.toString()}async function fM(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=Af(),W=await Bf(J.discoveryPath);if(W?.url&&e_(f.toString(),W.url))return W.authToken;return}async function PH(f={}){let $=gf(f);if(!o_(f)){let J=Af(),W=await Bf(J.discoveryPath);if(W?.url)return W.url}return af($.host,$.port,$.pathname)}async function EJ(f){return await new Promise(($,J)=>{(async()=>{let W=new URL(f),H=await fM(W);W.hash="";let Q=new WebSocket(W.toString(),H?[`${s_}${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(t_(X,f))})})().catch(J)})}async function hA(f){try{return(await EJ(f)).close(),!0}catch{return!1}}async function OA(f,$){let J=await PH(f),W=await EJ(J);try{return await W.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{W.close()}}function sf(f){return f?JSON.parse(JSON.stringify(f)):{}}function SJ(f){let $=f?.session&&typeof f.session==="object"?f.session:void 0;if(!$)return;let J=$.metadata&&typeof $.metadata==="object"?sf($.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 zA(f,$){return f.error?.message??`hub command failed: ${$}`}function $M(f){let $=sf(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 JM(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 WM(f){let $=f.sessionId?.trim();if(!$)return;switch(f.event){case"iteration.started":return{sessionId:$,eventType:"runtime.chat.iteration_start",payload:sf(f.payload)};case"iteration.finished":return{sessionId:$,eventType:"runtime.chat.iteration_end",payload:sf(f.payload)};case"assistant.delta":return{sessionId:$,eventType:"runtime.chat.text_delta",payload:sf(f.payload)};case"usage.updated":return{sessionId:$,eventType:"runtime.chat.usage",payload:sf(f.payload)};case"tool.started":return{sessionId:$,eventType:"runtime.chat.tool_call_start",payload:sf(f.payload)};case"tool.finished":return{sessionId:$,eventType:"runtime.chat.tool_call_end",payload:sf(f.payload)};case"approval.requested":return{sessionId:$,eventType:"approval.requested",payload:sf(f.payload)};case"run.aborted":return{sessionId:$,eventType:"runtime.chat.aborted",payload:sf(f.payload)};case"run.failed":return{sessionId:$,eventType:"runtime.chat.failed",payload:$M(f.payload)};case"run.completed":return{sessionId:$,eventType:"runtime.chat.completed",payload:sf(f.payload)};default:return}}class BH{options;client;metadataApplied=!1;constructor(f){this.options=f;this.client=new tf({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=SJ($.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 SJ($.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(zA(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(zA(H,"session.restore"));let Q=SJ(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=JM(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)=>SJ({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=WM(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 YH{client;constructor(f){this.client=new tf({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}})}}function HM(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(`
|
|
559
|
+
`).trim()||void 0}var NA=120,VH="...";function D4(f){let $=f.trim();if(!$)return"";if(Buffer.byteLength($,"utf8")<=NA)return $;let J=NA-Buffer.byteLength(VH,"utf8");if(J<=0)return VH;let W="";for(let H of $){if(Buffer.byteLength(W+H,"utf8")>J)break;W+=H}return`${W}${VH}`}async function qA(f){let $=f?.sessionId?.trim()||"unknown",J=typeof f?.metadata?.messagesPath==="string"?f.metadata.messagesPath:void 0,H=[...await Q$(J)].reverse().find((X)=>X.role==="assistant"),Q=H?HM(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:D4(Q&&Q.length>0?Q:j.length>0?j:Z),severity:"info"}}import{createSessionId as IM}from"@cline/shared";import{createSessionId as XM}from"@cline/shared";import{createSessionId as jM}from"@cline/shared";function QM(f){switch(f){case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function ZM(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 kJ(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:QM(f.status),participants:$?[...$.participants.values()]:[],metadata:ZM(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 IJ(f){return f&&typeof f==="object"&&!Array.isArray(f)?f:void 0}function Of(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:jM("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 kJ(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 mJ(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 RH(f,$){let J=XM("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 FH(f,$,J){let W=f.pendingApprovals.get($);if(!W)return;return f.pendingApprovals.delete($),W.resolve(J),{sessionId:W.sessionId}}function KH(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 wA(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=FH(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 BM}from"@cline/shared";function AM(f){if(f instanceof Error)return{name:f.name,message:f.message,stack:f.stack};if(f===void 0)return;return f}var bA={debug:10,info:20,warn:30,error:40,silent:50};function PM(){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(bA[f]<bA[PM()])return;let W=JSON.stringify({ts:new Date().toISOString(),level:f,component:"hub",message:$,...Object.fromEntries(Object.entries(J).map(([H,Q])=>[H,AM(Q)]).filter(([,H])=>H!==void 0))});if(f==="error"||f==="warn"){console.error(`[hub] ${W}`);return}console.log(`[hub] ${W}`)}function yH(f,$){let J=$ instanceof Error?$.stack||$.message:String($);g("error",f,{error:J})}async function CA(f,$,J,W,H,Q){let Z=BM("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 EA(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 B$(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 SA(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 kA(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 YM}from"@cline/shared";function IA(f,$){let J=$.payload,W=J?.clientId?.trim()||$.clientId?.trim()||YM("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 mA(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=IJ($.payload?.metadata);if(W.lastSeenAt=Date.now(),H)W.metadata=JSON.parse(JSON.stringify(H));return u($)}function xA(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 gA(f,$){return u($,{clients:[...f.clients.values()]})}var VM=30000;function RM(f){if(f==="aborted")return"run.aborted";if(f==="error"||f==="failed")return"run.failed";return"run.completed"}function FM(f){if(f.finishReason!=="error")return;return f.text.trim()||void 0}function KM(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 yM(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))},VM),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)}),KH(f,(V)=>V.sessionId===J.sessionId,Y),B$(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 vA(f,$){let J=Of($),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=KM(W);f.suppressNextTerminalEventBySession.set(J,"run.start.reply");let X;try{X=await yM(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=FM(X);if(f.publish(f.buildEvent(RM(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 uA(f,$){let J=Of($),W=typeof $.payload?.reason==="string"?$.payload.reason:"Run was aborted before pending approval or capability request was resolved.";return KH(f,(H)=>H.sessionId===J,W),await f.sessionHost.abort(J,$.payload?.reason),B$(f,(H)=>H.sessionId===J,W),f.publish(f.buildEvent("run.aborted",{reason:W},J)),u($,{applied:!0})}async function cA(f,$){let J=H2($.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 dA(f,$){switch($.type){case"chunk":return;case"agent_event":await UM(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 GM(f,$);return;default:return}}async function UM(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 GM(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 qA(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 aA,parseRuntimeConfigExtensions as tA}from"@cline/shared";var iA={};N(iA,{SessionVersioningService:()=>Y$,SessionVersioningError:()=>zf});var pA={};N(pA,{trimMessagesToCheckpoint:()=>lA,trimMessagesBeforeCheckpoint:()=>GH,readSessionCheckpointHistory:()=>_4,createRestoredCheckpointMetadata:()=>UH,createCheckpointRestorePlan:()=>TH,applyCheckpointToWorktree:()=>DH});import{execFile as TM}from"node:child_process";import{promisify as DM}from"node:util";var B2=DM(TM);function _4(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 UH(f,$){let J=_4(f).filter((H)=>H.runCount<=$),W=J.at(-1);return W?{latest:W,history:J}:void 0}function _M(f,$){return f.reduce((J,W)=>{if(W.runCount>$)return J;if(!J||W.runCount>J.runCount)return W;return J},void 0)}function rA(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 lA(f,$){let J=rA(f,$);return f.slice(0,J+1)}function GH(f,$){let J=rA(f,$);return f.slice(0,J)}function TH(f){let $=f.checkpointRunCount;if(!Number.isInteger($)||$<1)throw Error("checkpointRunCount must be a positive integer");let J=_M(_4(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:lA(f.messages??[],$)}:{}}}async function DH(f,$){if((await B2("git",["-C",f,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${f} is not a git repository`);if(await B2("git",["-C",f,"cat-file","-e",`${$.ref}^{commit}`],{windowsHide:!0}),await B2("git",["-C",f,"reset","--hard"],{windowsHide:!0}),await B2("git",["-C",f,"clean","-fd"],{windowsHide:!0}),$.kind==="commit"){await B2("git",["-C",f,"reset","--hard",$.ref],{windowsHide:!0});return}await B2("git",["-C",f,"stash","apply",$.ref],{windowsHide:!0})}class zf extends Error{code;constructor(f,$){super($);this.code=f;this.name="SessionVersioningError"}}function MM(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 Y${async restoreCheckpoint(f){let $=f.restore?.messages!==!1,J=f.restore?.workspace!==!1,W=MM({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=TH({session:H,messages:Q,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restoreMessages:$});if(J)await(f.applyWorkspaceCheckpoint??DH)(Z.cwd,Z.checkpoint);let j=W0({session:H,messages:Q});if(!$)return{checkpoint:Z.checkpoint,sourceSnapshot:j};let X=UH(H,f.checkpointRunCount),A=f.restore?.omitCheckpointMessageFromSession?GH(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??a7)(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})}:{}}}}import{HUB_CHECKPOINT_CAPABILITY as Gm,HUB_COMPACTION_CAPABILITY as Tm,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Dm,HUB_HOOK_CAPABILITY_PREFIX as _m,HUB_MISTAKE_LIMIT_CAPABILITY as Mm,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Lm,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as hm,isHubToolExecutorName as LM}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as wm,HUB_COMPACTION_CAPABILITY as bm,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Cm,HUB_HOOK_CAPABILITY_PREFIX as Em,HUB_MISTAKE_LIMIT_CAPABILITY as Sm,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as km,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Im}from"@cline/shared";var hM=["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 OM(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=s$(f.inputSchema);if(!J||!W||!Q||!H||$.has(H))return;return $.add(H),{kind:"tool",capabilityName:H,name:J,description:W,inputSchema:Q,...s$(f.lifecycle)?{lifecycle:s$(f.lifecycle)}:{}}}function MH(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=OM(H,J);if(j)$.push(j);continue}if(Q==="toolExecutor"){let j=H.executor;if(!LM(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,...s$(H.config)?{config:s$(H.config)}:{}});continue}if(Q==="checkpoint"){J.add(Z),$.push({kind:"checkpoint",capabilityName:Z,...s$(H.config)?{config:s$(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 nA(f){return{agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,metadata:f.metadata}}function zM(f){return Object.hasOwn(f,"update")?f.update:f}function M4(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function NM(f){let $=(f??[]).map(M4).filter(Boolean);return $.length>0?new Set($):void 0}function qM(f,$,J){if(!J)return!0;let W=M4(f),H=M4($),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 _H(f,$){let J=NM($);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)=>qM(W.id,W.name,J))}function wM(f,$){let J=async(W,H)=>{let Q=M4(W),j=_H(f,$).filter((Y)=>Y.id===Q||M4(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?`
|
|
560
|
+
<command-args>${A}</command-args>`:"",B=X.description?.trim()?`Description: ${X.description.trim()}
|
|
561
561
|
|
|
562
|
-
`:"";return`<command-name>${
|
|
562
|
+
`:"";return`<command-name>${X.name}</command-name>${P}
|
|
563
563
|
<command-instructions>
|
|
564
|
-
${
|
|
565
|
-
</command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>
|
|
564
|
+
${B}${X.instructions}
|
|
565
|
+
</command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>_H(f,$).map(({skill:W,...H})=>H),enumerable:!0}),J}function bM(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)=>_H(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:()=>u1(H.records.rule.map((X)=>X.item).filter((X)=>X.disabled!==!0))});if(Z.registerSkillsTool)j.registerTool(K$(wM(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}
|
|
566
566
|
|
|
567
|
-
${V}`:P.instructions}})}})}}function fM(f,$,J,W){let H=J.map((Q)=>[Q.executor,async(...Z)=>{let j=Z.at(-1),P=Z.slice(0,-1);return(await W(f,Q.capabilityName,{executor:Q.executor,args:P,context:zX(j)},$))?.result}]);return H.length>0?Object.fromEntries(H):void 0}function $M(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:zX(Z)},$,Z.emitUpdate?(P)=>{Z.emitUpdate?.(aD(P))}:void 0))?.result}}))}function JM(f,$,J,W){let H=new Map(J.map((Z)=>[Z.name,Z])),Q={};for(let Z of iD){let j=H.get(Z);if(!j)continue;Q[Z]=async(P)=>{return(await W(f,j.capabilityName,{context:P},$))?.control}}return Object.keys(Q).length>0?Q:void 0}function U9(f){let $=f.contributions.filter((P)=>P.kind==="toolExecutor"),J=f.contributions.filter((P)=>P.kind==="tool"),W=f.contributions.filter((P)=>P.kind==="hook"),H=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:fM(f.sessionId,f.targetClientId,$,f.requestCapability),localRuntime:{...W.length>0?{hooks:JM(f.sessionId,f.targetClientId,W,f.requestCapability)}:{},...J.length>0?{extraTools:$M(f.sessionId,f.targetClientId,J,f.requestCapability)}:{},...H?{compaction:{...f.sessionConfig?.compaction??{},...H.config,compact:async(P)=>{return(await f.requestCapability(f.sessionId,H.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:eD(f.sessionId,f.targetClientId,j,f.requestCapability)}:{}}}}var qX="hubCapabilityOwnerClientId";function bX(f,$){f[qX]=$}function WM(f){let $=f?.[qX];return typeof $==="string"&&$.trim()?$.trim():void 0}async function wX(f,$,J){let W=performance.now(),H={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:$.sessionId};x("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,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",{...H,reason:"missing_workspace_root"}),m($,"invalid_session_create","session.create requires workspaceRoot or cwd");let Y=$.clientId?.trim()||"hub-client",B=K9(P.clientContributions);if(x("info","session.create.contributions_parsed",{...H,clientId:Y,workspaceRoot:V,cwd:typeof Q.cwd==="string"?Q.cwd:void 0,contributionCount:B.length}),B.length>0)bX(Z,Y);let R=(typeof j?.sessionId==="string"?j.sessionId.trim():"")||OX(),U=NX(P.configExtensions);x("info","session.create.runtime_build.begin",{...H,sessionId:R,configExtensionCount:U?.length??0});let y=U9({sessionId:R,targetClientId:Y,contributions:B,sessionConfig:j,requestCapability:f.requestCapability});x("info","session.create.start_session.begin",{...H,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",{...H,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-W),hasImmediateResult:!!F.result}),gJ(f,F.sessionId,Y,"creator",{interactive:Z.interactive!==!1}),x("info","session.create.read_records.begin",{...H,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",{...H,sessionId:F.sessionId,hasSession:!!K,hasSnapshot:!!M,elapsedMs:Math.round(performance.now()-W)}),K)f.publish(f.buildEvent("session.created",{session:K,...M?{snapshot:M}:{}},F.sessionId));return x("info","session.create.reply",{...H,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-W)}),v($,{session:K,...M?{snapshot:M}:{}})}async function CX(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 P=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0;if(j&&!P)return m($,"invalid_restore","sessionConfig is required when restore.messages is true");let X=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{},V=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.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=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},B=$.clientId?.trim()||"hub-client",A=K9(X.clientContributions);if(A.length>0)bX(V,B);let U=(typeof P?.sessionId==="string"?P.sessionId.trim():"")||OX(),y=NX(X.configExtensions),F=U9({sessionId:U,targetClientId:B,contributions:A,sessionConfig:P,requestCapability:f.requestCapability}),M=await new j$().restoreCheckpoint({sessionId:H,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 W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.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:H,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:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.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 h=M.startResult;if(!h)return m($,"restore_failed","Checkpoint restore did not start a session");gJ(f,h.sessionId,B,"creator",{interactive:V.interactive!==!1});let[G,T]=await Promise.all([If(f,h.sessionId),xf(f,h.sessionId)]);if(G)f.publish(f.buildEvent("session.created",{session:G,...T?{snapshot:T}:{}},h.sessionId));return v($,{session:G,...T?{snapshot:T}:{},messages:M.messages??[],checkpoint:M.checkpoint})}catch(P){if(P instanceof Df)return m($,P.code,P.code==="session_not_found"?`Unknown session: ${H}`:P.message);return m($,"restore_failed",P instanceof Error?P.message:String(P))}}async function EX(f,$){let J=hf($);if(!J)return m($,"invalid_session_attach","session.attach requires a session id");gJ(f,J,$.clientId?.trim()||"hub-client","participant");let W=await If(f,J);if(W)f.publish(f.buildEvent("session.attached",{session:W},J));return W?v($,{session:W}):m($,"session_not_found",`Unknown session: ${J}`)}async function SX(f,$){let J=hf($);if(!J)return m($,"invalid_session_detach","session.detach requires a session id");let W=$.clientId?.trim()||"hub-client",[H]=await Promise.all([If(f,J)]),Q=WM(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)}Z$(f,(X)=>X.sessionId===J&&X.targetClientId===W,`Capability owner client ${W} 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:W}:{clientId:W},J)),v($)}async function kX(f,$){let J=hf($),W=$.payload?.includeSnapshot===!0,[H,Q]=await Promise.all([If(f,J),W?xf(f,J):Promise.resolve(void 0)]);return H?v($,{session:H,...Q?{snapshot:Q}:{}}):m($,"session_not_found",`Unknown session: ${J}`)}async function mX(f,$){let J=hf($);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 H=await f.sessionHost.readSessionMessages(J);return v($,{sessionId:J,messages:H})}async function IX(f,$){let J=typeof $.payload?.limit==="number"?$.payload.limit:200,H=(await f.sessionHost.listSessions(J)).map((Q)=>IJ(Q,f.sessionState.get(Q.sessionId)));return v($,{sessions:H})}async function xX(f,$){let J=hf($),W=xJ($.payload?.metadata),H=await f.sessionHost.updateSession(J,{metadata:W}),[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:H.updated,payload:{updated:H.updated,session:Q,...Z?{snapshot:Z}:{}}}}async function gX(f,$){let J=hf($),W=await f.sessionHost.deleteSession(J);return f.sessionState.delete(J),v($,{deleted:W})}async function vX(f,$){let J=hf($),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 v($,{sessionId:J,prompts:H})}async function uX(f,$){let J=hf($),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 v($,j)}async function cX(f,$){let J=hf($),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 v($,Q)}function dX(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 QM=new Set(["skills","workflows","rules","tools"]);function G9(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function G4(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${$}' must be a string.`);return J}function ZM(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${$}' must be a boolean.`);return J}function rX(f){if(f===void 0)return{};if(!G9(f))throw Error("settings.list payload must be an object.");return{cwd:G4(f,"cwd"),workspaceRoot:G4(f,"workspaceRoot"),availabilityContext:G9(f.availabilityContext)?f.availabilityContext:void 0}}function jM(f){if(!G9(f))throw Error("settings.toggle payload must be an object.");let{type:$}=f;if(typeof $!=="string"||!QM.has($))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools.");return{...rX(f),type:$,id:G4(f,"id"),path:G4(f,"path"),name:G4(f,"name"),enabled:ZM(f,"enabled")}}class X2{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=HM("hub_");ctx;constructor(f){this.options=f;if(this.sessionHost=f.sessionHost??new Z0({sessionService:new Q0(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:n$,requestCapability:($,J,W,H,Q)=>VX(this.ctx,$,J,W,H,Q)},this.schedules=new H2({...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(n$(W,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new W2(this.schedules),this.settings=f.settingsService??new e0,f.cronOptions)this.cronService=new n8({runtimeHandlers:f.runtimeHandlers,...f.cronOptions});this.sessionHost.subscribe(($)=>{hX(this.ctx,$).catch((J)=>{Y9("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())X9(this.ctx,f,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(Z$(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 RX(this.ctx,f);case"client.update":return FX(this.ctx,f);case"client.unregister":return yX(this.ctx,f,($)=>{this.listeners.delete($),this.detachClientFromSessions($)});case"client.list":return KX(this.ctx,f);case"session.create":return await wX(this.ctx,f,($)=>P9(this.ctx,$));case"session.restore":return await CX(this.ctx,f,($)=>P9(this.ctx,$));case"session.attach":return await EX(this.ctx,f);case"session.detach":return await SX(this.ctx,f);case"session.get":return await kX(this.ctx,f);case"session.messages":return await mX(this.ctx,f);case"session.list":return await IX(this.ctx,f);case"session.update":return await xX(this.ctx,f);case"session.pending_prompts":return await vX(this.ctx,f);case"session.update_pending_prompt":return await uX(this.ctx,f);case"session.remove_pending_prompt":return await cX(this.ctx,f);case"session.delete":return await gX(this.ctx,f);case"session.hook":return await TX(this.ctx,f);case"run.start":case"session.send_input":return await UX(this.ctx,f);case"run.abort":return await GX(this.ctx,f);case"capability.request":return await BX(this.ctx,f);case"approval.respond":return await PX(this.ctx,f);case"capability.respond":return AX(this.ctx,f);case"capability.progress":return YX(this.ctx,f);case"ui.notify":return this.publish(n$("ui.notify",f.payload??{})),v(f);case"ui.show_window":return this.publish(n$("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=dX(f.command);if(J)this.publish(n$(J,$.payload))}return $}}}async handleSettingsList(f){try{let $=await this.settings.list(rX(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(jM(f.payload));return this.publish(n$("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($);Z$(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){Y9(`listener threw while publishing ${f.event}`,W)}}}}import{timingSafeEqual as YM}from"node:crypto";import BM from"node:http";import AM from"node:net";import{URL as iX}from"node:url";import{WebSocketServer as RM}from"ws";import{HUB_COMMAND_SLOW_LOG_MS as PM,resolveHubCommandTimeoutMs as XM,safeJsonParse as VM}from"@cline/shared";function lX(f){return{command:f.envelope.command,requestId:f.envelope.requestId,clientId:f.envelope.clientId,sessionId:f.envelope.sessionId}}function pX(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,W=!1,H=(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)=>{H({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=lX(X);x("info","command.start",B);let A=setTimeout(()=>{if(Y)return;x("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-V)})},PM),R=this.transport.command(X.envelope);R.then((h)=>{if(!Y)return;x(h.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-V),ok:h.ok,errorCode:h.error?.code,errorMessage:h.error?.message})},(h)=>{if(!Y)return;x("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-V),error:h})});let U=!1,y,F,K=XM(X.envelope.command,X.envelope.timeoutMs);try{F=K===null?await R:await Promise.race([R,new Promise((h)=>{y=setTimeout(()=>{U=!0,h(pX(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(h){if(clearTimeout(A),y)clearTimeout(y);throw h}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 h=X.envelope.clientId?.trim();if(h)J.delete(h)}H({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"?VM(P.data):void 0;if(!V||V.kind!=="command"){x("error","rejected malformed websocket frame",{error:X});return}x("error","command.error",{...lX(V),error:X}),H({kind:"reply",envelope:pX(V,"command_failed",X instanceof Error?X.message:"Unknown hub error")})}},j=()=>{if(W)return;W=!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 h4{transport;constructor(f){this.transport=f}command(f){return this.transport.handleCommand(f)}subscribe(f,$,J){return this.transport.subscribe(f,$,J)}}function FM(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 yM(f){return{send($){f.send($)},addEventListener($,J){if($==="message"){f.on("message",(W)=>{J({data:FM(W)})});return}f.on("close",J)},removeEventListener(){}}}function KM(f){try{f.write(`HTTP/1.1 400 Bad Request\r
|
|
567
|
+
${P}`:X.instructions}})}})}}function CM(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:nA(j)},$))?.result}]);return H.length>0?Object.fromEntries(H):void 0}function EM(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:nA(Z)},$,Z.emitUpdate?(X)=>{Z.emitUpdate?.(zM(X))}:void 0))?.result}}))}function SM(f,$,J,W){let H=new Map(J.map((Z)=>[Z.name,Z])),Q={};for(let Z of hM){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 LH(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:CM(f.sessionId,f.targetClientId,$,f.requestCapability),localRuntime:{...W.length>0?{hooks:SM(f.sessionId,f.targetClientId,W,f.requestCapability)}:{},...J.length>0?{extraTools:EM(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:bM(f.sessionId,f.targetClientId,j,f.requestCapability)}:{}}}}var sA="hubCapabilityOwnerClientId";function oA(f,$){f[sA]=$}function kM(f){let $=f?.[sA];return typeof $==="string"&&$.trim()?$.trim():void 0}async function eA(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=MH(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)oA(Z,B);let R=(typeof j?.sessionId==="string"?j.sessionId.trim():"")||aA(),U=tA(X.configExtensions);g("info","session.create.runtime_build.begin",{...H,sessionId:R,configExtensionCount:U?.length??0});let K=LH({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}),mJ(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 fP(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=MH(A.clientContributions);if(V.length>0)oA(P,Y);let U=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||aA(),K=tA(A.configExtensions),F=LH({sessionId:U,targetClientId:Y,contributions:V,sessionConfig:X,requestCapability:f.requestCapability}),D=await new Y$().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");mJ(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 $P(f,$){let J=Of($);if(!J)return m($,"invalid_session_attach","session.attach requires a session id");mJ(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 JP(f,$){let J=Of($);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=kM(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)}B$(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 WP(f,$){let J=Of($),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 HP(f,$){let J=Of($);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 QP(f,$){let J=typeof $.payload?.limit==="number"?$.payload.limit:200,H=(await f.sessionHost.listSessions(J)).map((Q)=>kJ(Q,f.sessionState.get(Q.sessionId)));return u($,{sessions:H})}async function ZP(f,$){let J=Of($),W=IJ($.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 jP(f,$){let J=Of($),W=await f.sessionHost.deleteSession(J);return f.sessionState.delete(J),u($,{deleted:W})}async function XP(f,$){let J=Of($),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 AP(f,$){let J=Of($),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 PP(f,$){let J=Of($),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 BP(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 mM=new Set(["skills","workflows","rules","tools"]);function hH(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 xM(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${$}' must be a boolean.`);return J}function YP(f){if(f===void 0)return{};if(!hH(f))throw Error("settings.list payload must be an object.");return{cwd:L4(f,"cwd"),workspaceRoot:L4(f,"workspaceRoot"),availabilityContext:hH(f.availabilityContext)?f.availabilityContext:void 0}}function gM(f){if(!hH(f))throw Error("settings.toggle payload must be an object.");let{type:$}=f;if(typeof $!=="string"||!mM.has($))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools.");return{...YP(f),type:$,id:L4(f,"id"),path:L4(f,"path"),name:L4(f,"name"),enabled:xM(f,"enabled")}}class Y2{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=IM("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:t$,requestCapability:($,J,W,H,Q)=>CA(this.ctx,$,J,W,H,Q)},this.schedules=new j2({...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(t$(W,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new Z2(this.schedules),this.settings=f.settingsService??new J$,f.cronOptions)this.cronService=new e8({runtimeHandlers:f.runtimeHandlers,...f.cronOptions});this.sessionHost.subscribe(($)=>{dA(this.ctx,$).catch((J)=>{yH("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())FH(this.ctx,f,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(B$(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 IA(this.ctx,f);case"client.update":return mA(this.ctx,f);case"client.unregister":return xA(this.ctx,f,($)=>{this.listeners.delete($),this.detachClientFromSessions($)});case"client.list":return gA(this.ctx,f);case"session.create":return await eA(this.ctx,f,($)=>RH(this.ctx,$));case"session.restore":return await fP(this.ctx,f,($)=>RH(this.ctx,$));case"session.attach":return await $P(this.ctx,f);case"session.detach":return await JP(this.ctx,f);case"session.get":return await WP(this.ctx,f);case"session.messages":return await HP(this.ctx,f);case"session.list":return await QP(this.ctx,f);case"session.update":return await ZP(this.ctx,f);case"session.pending_prompts":return await XP(this.ctx,f);case"session.update_pending_prompt":return await AP(this.ctx,f);case"session.remove_pending_prompt":return await PP(this.ctx,f);case"session.delete":return await jP(this.ctx,f);case"session.hook":return await cA(this.ctx,f);case"run.start":case"session.send_input":return await vA(this.ctx,f);case"run.abort":return await uA(this.ctx,f);case"capability.request":return await SA(this.ctx,f);case"approval.respond":return await wA(this.ctx,f);case"capability.respond":return kA(this.ctx,f);case"capability.progress":return EA(this.ctx,f);case"ui.notify":return this.publish(t$("ui.notify",f.payload??{})),u(f);case"ui.show_window":return this.publish(t$("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=BP(f.command);if(J)this.publish(t$(J,$.payload))}return $}}}async handleSettingsList(f){try{let $=await this.settings.list(YP(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(gM(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 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($);B$(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){yH(`listener threw while publishing ${f.event}`,W)}}}}import{timingSafeEqual as dM}from"node:crypto";import rM from"node:http";import lM from"node:net";import{URL as FP}from"node:url";import{WebSocketServer as pM}from"ws";import{HUB_COMMAND_SLOW_LOG_MS as vM,resolveHubCommandTimeoutMs as uM,safeJsonParse as cM}from"@cline/shared";function VP(f){return{command:f.envelope.command,requestId:f.envelope.requestId,clientId:f.envelope.clientId,sessionId:f.envelope.sessionId}}function RP(f,$,J){return{version:f.envelope.version,requestId:f.envelope.requestId,ok:!1,error:{code:$,message:J}}}class h4{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=VP(A);g("info","command.start",Y);let V=setTimeout(()=>{if(B)return;g("warn","command.slow",{...Y,elapsedMs:Math.round(performance.now()-P)})},vM),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=uM(A.envelope.command,A.envelope.timeoutMs);try{F=y===null?await R:await Promise.race([R,new Promise((M)=>{K=setTimeout(()=>{U=!0,M(RP(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"?cM(X.data):void 0;if(!P||P.kind!=="command"){g("error","rejected malformed websocket frame",{error:A});return}g("error","command.error",{...VP(P),error:A}),H({kind:"reply",envelope:RP(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 O4{transport;constructor(f){this.transport=f}command(f){return this.transport.handleCommand(f)}subscribe(f,$,J){return this.transport.subscribe(f,$,J)}}function iM(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 nM(f){return{send($){f.send($)},addEventListener($,J){if($==="message"){f.on("message",(W)=>{J({data:iM(W)})});return}f.on("close",J)},removeEventListener(){}}}function aM(f){try{f.write(`HTTP/1.1 400 Bad Request\r
|
|
568
568
|
Connection: close\r
|
|
569
569
|
Content-Length: 0\r
|
|
570
570
|
\r
|
|
571
|
-
`),f.end()}catch{f.destroy()}}function
|
|
571
|
+
`),f.end()}catch{f.destroy()}}function tM(f){try{f.write(`HTTP/1.1 401 Unauthorized\r
|
|
572
572
|
Connection: close\r
|
|
573
573
|
Content-Length: 0\r
|
|
574
574
|
\r
|
|
575
|
-
`),f.end()}catch{f.destroy()}}function
|
|
576
|
-
Caused by: ${f.stack}`;return Q}async function
|
|
577
|
-
`).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?
|
|
578
|
-
`,"utf8")}persistRuntime(f,$,J){this.ensureTeamSubdir(f);let W={version:1,updatedAt:
|
|
579
|
-
`,"utf8"),
|
|
575
|
+
`),f.end()}catch{f.destroy()}}function KP(f,$){if(!f||!$)return!1;let J=Buffer.from(f,"utf8"),W=Buffer.from($,"utf8");return J.length===W.length&&dM(J,W)}function yP(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}
|
|
576
|
+
Caused by: ${f.stack}`;return Q}async function sM(f){return await new Promise(($,J)=>{let W=lM.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 oM(f){return f instanceof Error&&"code"in f&&f.code==="EADDRINUSE"}var OH=new Map,UP="cline-hub-auth.",eM=30000;function GP(f){return Array.isArray(f)?f.join(","):f??""}function fL(f){let $=GP(f).trim();return/^Bearer\s+(.+)$/i.exec($)?.[1]?.trim()||null}function $L(f){for(let $ of GP(f).split(",")){let J=$.trim();if(J.startsWith(UP))return J.slice(UP.length).trim()||null}return null}async function o$(f){let $=f.owner??z0(),J=f.host??"127.0.0.1",W=f.pathname??"/hub",H=f.port??d1(),Q=H===0?await sM(J):H,Z=Q,j=af(J,Q,W),X=Z$(),A=RJ(),P=new Y2(f);await P.start();let B=new h4(new O4(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 Bf($.discoveryPath))?.url===j)await xf($.discoveryPath)})(),F},D=rM.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 FP(T.url??"/",`http://${J}:${Z}`).pathname==="/shutdown"&&T.method==="POST"){if(!KP(fL(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 pM({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)}}},eM),D.on("upgrade",(T,_,L)=>{if(new FP(T.url??"/",`http://${J}:${Z}`).pathname!==W){_.destroy();return}if(!KP($L(T.headers["sec-websocket-protocol"]),A)){tM(_);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(nM(Wf));Y.add(o),Wf.once("close",()=>{U.delete(Hf),o(),Y.delete(o)})})}catch{aM(_)}});try{await new Promise((T,_)=>{D.once("error",(L)=>{_(yP(L,{host:J,port:Q,pathname:W}))}),D.listen(Q,J,()=>{let L=D.address();if(!L||typeof L==="string"){_(yP(Error("Failed to resolve hub port"),{host:J,port:Q,pathname:W}));return}Z=L.port,j=af(J,Z,W),T()})})}catch(T){if(K)clearInterval(K),K=void 0;throw await P.stop().catch(()=>{return}),T}return await FJ($.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 xJ(f){let $=f.owner??z0(),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??d1(),Q=f.pathname??"/hub",Z=af(W,H,Q),j=$.discoveryPath,X=(P)=>{if(!J)j$(P.url,P.authToken);return P},A=OH.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 KJ($.discoveryPath,async()=>{let P=await Bf($.discoveryPath);if(P?.url&&(P.url===Z||f.allowPortFallback===!0)){let R=await Uf(P.url);if(R?.url&&await J0(R.url,{authToken:P.authToken}))return X({url:R.url,authToken:P.authToken,action:"reuse"})}if((await Uf(Z))?.url||P?.url)await xf($.discoveryPath);let V=async(R)=>{let U=o$({...R,owner:$});OH.set(j,U);try{let K=await U;return X({server:K,url:K.url,authToken:K.authToken,action:"started"})}catch(K){throw OH.delete(j),K}};try{return await V(f)}catch(R){if(!f.allowPortFallback||!oM(R))throw R;return await V({...f,port:0})}})}async function TP(f){let $=gf({host:f.host,port:f.port,pathname:f.pathname});return await o$({...f,...$,owner:Af()})}async function DP(f){let $=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=gf({host:f.host,port:f.port,pathname:f.pathname});return await xJ({...f,...J,allowPortFallback:f.allowPortFallback??!$,owner:Af()})}zH();var LP={};N(LP,{registerRemoteConfigSessionBlobUpload:()=>cJ,readRemoteConfigSessionBlobUploadMetadata:()=>NH,prepareRemoteConfigCoreIntegration:()=>wH,createRemoteConfigSessionMessagesArtifactUploader:()=>qH,buildRemoteConfigSessionBlobUploadMetadata:()=>vJ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>uJ});import{buildRemoteConfigSessionBlobUploadMetadata as vJ,clearRemoteConfigSessionBlobUpload as JL,createClineTelemetryServiceConfig as WL,createSessionId as HL,createRemoteConfigSessionMessagesArtifactUploader as QL,prepareRemoteConfigRuntime as ZL,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as uJ,readRemoteConfigSessionBlobUploadMetadata as NH,registerRemoteConfigSessionBlobUpload as cJ}from"@cline/shared";function jL(f,$){let J=f.telemetry||$.telemetryService?{...$.telemetryService??{},...f.telemetry??{}}:void 0;if(!J)return;return C0(WL(J)).telemetry}function qH(){let f=QL();return{async uploadMessagesFile($){await f.uploadMessagesFile($)}}}async function wH(f){let $=await ZL(f),J=jL($,f),W=[$.pluginDefinition],H=$.claims?.subject,Q=vJ($.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()||HL():j.config.sessionId;if(P&&Q)Z=P;let B=P&&Q?cJ(P,$.bundle?.remoteConfig,H):void 0,Y=B?{...j.sessionMetadata??{},[uJ]:B}:j.sessionMetadata;return{...j,...Y?{sessionMetadata:Y}:{},config:{...j.config,...P?{sessionId:P}:{},extensions:[...X,...W],telemetry:J??A}}},async dispose(){if(Z)JL(Z)}}}var CP={};N(CP,{createTeamName:()=>dJ,DefaultRuntimeBuilder:()=>F2});import{hasRuntimeConfigExtension as DL}from"@cline/shared";import{nanoid as _L}from"nanoid";M0();var wP={};N(wP,{createLocalTeamStore:()=>SH,SqliteTeamStore:()=>e$,FileTeamStore:()=>z4});import{appendFileSync as XL,existsSync as V2,mkdirSync as hP,readdirSync as AL,readFileSync as OP,renameSync as PL,writeFileSync as BL}from"node:fs";import{join as bH}from"node:path";import{resolveTeamDataDir as YL}from"@cline/shared/storage";function zP(){return new Date().toISOString()}function CH(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function NP(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 z4{teamDirPath;constructor(f={}){this.teamDirPath=f.teamDir??YL()}init(){this.ensureTeamDir()}listTeamNames(){if(!V2(this.teamDirPath))return[];return AL(this.teamDirPath,{withFileTypes:!0}).filter((f)=>f.isDirectory()).filter((f)=>V2(this.statePath(f.name))).map((f)=>f.name).sort()}readState(f){let $=this.readEnvelope(f);return $?.teamState?NP($.teamState):void 0}readHistory(f,$=200){let J=this.historyPath(f);if(!V2(J))return[];return OP(J,"utf8").split(`
|
|
577
|
+
`).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?NP($.teamState):void 0,teammates:$?.teammates??[],interruptedRunIds:[]}}handleTeamEvent(f,$){this.ensureTeamSubdir(f),XL(this.historyPath(f),`${JSON.stringify({ts:zP(),eventType:$.type,payload:$})}
|
|
578
|
+
`,"utf8")}persistRuntime(f,$,J){this.ensureTeamSubdir(f);let W={version:1,updatedAt:zP(),teamState:$,teammates:J},H=this.statePath(f),Q=`${H}.tmp`;BL(Q,`${JSON.stringify(W,null,2)}
|
|
579
|
+
`,"utf8"),PL(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(!V2(this.teamDirPath))hP(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir(f){let $=bH(this.ensureTeamDir(),CH(f));if(!V2($))hP($,{recursive:!0});return $}statePath(f){return bH(this.ensureTeamDir(),CH(f),"state.json")}historyPath(f){return bH(this.ensureTeamDir(),CH(f),"task-history.jsonl")}readEnvelope(f){let $=this.statePath(f);if(!V2($))return;try{let J=JSON.parse(OP($,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as VL,mkdirSync as RL}from"node:fs";import{join as FL}from"node:path";import{safeJsonParse as qP}from"@cline/shared";import{loadSqliteDb as KL,nowIso as EH}from"@cline/shared/db";import{resolveDbDataDir as yL}from"@cline/shared/storage";function UL(){return yL()}function R2(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function GL(f){let $=qP(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 TL(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 e${teamDirPath;db;constructor(f={}){this.teamDirPath=f.teamDir??UL()}init(){this.getRawDb()}ensureTeamDir(){if(!VL(this.teamDirPath))RL(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return FL(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let f=KL(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(`
|
|
580
580
|
CREATE TABLE IF NOT EXISTS team_store_schema_version (
|
|
581
581
|
lock INTEGER PRIMARY KEY CHECK (lock = 1),
|
|
582
582
|
version INTEGER NOT NULL
|
|
@@ -660,8 +660,8 @@ Caused by: ${f.stack}`;return Q}async function GM(f){return await new Promise(($
|
|
|
660
660
|
version INTEGER NOT NULL DEFAULT 1,
|
|
661
661
|
PRIMARY KEY(team_name, fragment_id)
|
|
662
662
|
);
|
|
663
|
-
`)}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 = ?",[
|
|
664
|
-
VALUES (?, ?, ?, ?, NULL, ?)`,[
|
|
663
|
+
`)}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 = ?",[R2(f)]);if(!$)return;let J=qP($.state_json);if(!J)return;try{return TL(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 ?",[R2(f),$]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime(f){let $=R2(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?GL(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)
|
|
664
|
+
VALUES (?, ?, ?, ?, NULL, ?)`,[R2(f),EH(),$,JSON.stringify(J),W??null])}persistRuntime(f,$,J){let W=R2(f),H=EH();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
|
|
665
665
|
VALUES (?, ?, ?, ?)
|
|
666
666
|
ON CONFLICT(team_name) DO UPDATE SET
|
|
667
667
|
state_json = excluded.state_json,
|
|
@@ -706,15 +706,15 @@ Caused by: ${f.stack}`;return Q}async function GM(f){return await new Promise(($
|
|
|
706
706
|
status = excluded.status,
|
|
707
707
|
reviewed_by = excluded.reviewed_by,
|
|
708
708
|
reviewed_at = excluded.reviewed_at,
|
|
709
|
-
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=
|
|
710
|
-
WHERE team_name = ? AND status IN ('queued', 'running')`,[$,H,J]),W.map((Q)=>Q.run_id)}handleTeamEvent(f,$){this.appendTeamEvent(f,$.type,$)}}function
|
|
711
|
-
`,"utf8");let
|
|
712
|
-
`,"utf8")}async function
|
|
713
|
-
`,"utf8")}function yV(f,$){return{id:f,name:$.name??f,supportsAttachments:$.capabilities?.includes("files"),supportsVision:$.capabilities?.includes("images"),supportsReasoning:$.capabilities?.includes("reasoning")||$.thinkingConfig!=null}}function KV(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 UV(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 R_(f){return f!=null&&typeof f.name==="string"&&typeof f.baseUrl==="string"}function GV(f,$){return f??$??"openai-chat"}function TV(f,$,J){return f??J??($==="openai-responses"?"openai":"openai-compatible")}function F_(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 y_(f,$){for(let[J,W]of Object.entries($??{})){let H=W.id?.trim()||J.trim();if(!H)continue;Mf.registerModel(f,H,F_(H,W))}}function K_(f,$,J){return{...$??{},id:f,name:$?.name??f,capabilities:$?.capabilities??J}}function U_(f){return Object.assign({},...Mf.resolveProviderModelCatalogKeys(f).map((J)=>Mf.getGeneratedModelsForProvider(J)))}function G_(f){let $=f.provider.trim();if(!$||Mf.isBuiltInProviderId($))return;let J=f.baseUrl?.trim();if(!J)return;let W=Mf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],H=U_($),Q=UV(f.capabilities),Z=Q.length>0?Q:void 0,j=f.model?.trim(),P={...H,...W?.models??{}};if(j)P[j]=K_(j,P[j],Z);let X=Object.keys(P).filter(Boolean),V=j||X[0];if(!V)return;let Y=GV(f.protocol,W?.provider.protocol),B=TV(f.client,Y,W?.provider.client);Mf.registerProvider({provider:{id:$,name:W?.provider.name??AV($),description:W?.provider.description,protocol:Y,client:B,baseUrl:J,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:V,capabilities:KV(f.capabilities)??W?.provider.capabilities,source:"file"},models:P})}function pJ(f){for(let $ of Object.values(f.providers))G_($.settings)}function M4(f,$){let J=$.models??{};if(!R_($.provider)){y_(f,J);return}let W=UV($.provider.capabilities),H=Object.entries(J).map(([X,V])=>({id:V.id?.trim()||X.trim(),model:V})).filter(({id:X})=>X.length>0),Q=$.provider.defaultModelId?.trim()||H[0]?.id||"default",Z=GV($.provider.protocol,void 0),j=TV($.provider.client,Z,void 0),P=Object.fromEntries(H.map(({id:X,model:V})=>[X,{id:X,name:V.name??X,capabilities:W.length>0?W:void 0,status:"active"}]));Mf.registerProvider({provider:{id:f,name:$.provider.name.trim()||AV(f),protocol:Z,client:j,baseUrl:$.provider.baseUrl,modelsSourceUrl:$.provider.modelsSourceUrl,defaultModelId:Q,capabilities:KV($.provider.capabilities),source:"file"},models:P})}function hV(f){let $=o$(f);if(dJ.has($))return;let J=b9($);for(let[W,H]of Object.entries(J.providers))M4(W,H);dJ.add($)}async function iJ(f){let $=o$(f);if(dJ.has($))return;let J=await A2($);for(let[W,H]of Object.entries(J.providers))M4(W,H);dJ.add($)}function h_(f){return f.apiKey??f.auth?.apiKey}function D_(f){return(f.auth?.accessToken?.trim()??"").length>0}function DV(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function M_(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 __(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 MV(f){return Object.entries(f).sort(([$],[J])=>$.localeCompare(J)).map(([$,J])=>yV($,J))}async function L_(f,$){let J=await jf.getModelsForProvider(f);if(!$)return J;let W=await Y8(f,{loadPrivateOnAuth:!0,failOnError:!1},$);return W?.knownModels?{...J,...W.knownModels}:J}function w9(f){return[...new Set((f??[]).map(($)=>$.trim()).filter(Boolean))]}function _V(f){let $=Object.entries(f??{}).filter(([J])=>J.trim().length>0);return $.length>0?Object.fromEntries($):void 0}function C9(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 LV(f){if(!f.shouldRecompute)return f.fallbackModelIds??[];let $=f.modelsSourceUrl?await O6(f.modelsSourceUrl,f.providerId):[];return[...new Set([...f.explicitModels??[],...$])]}function zV(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);jf.unregisterProvider($)}async function E9(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=o$(f);if((await A2(R)).providers[J]){let y=await aJ(f,{providerId:J});return{providerId:J,settingsPath:y.settingsPath,modelsPath:y.modelsPath,modelsCount:0}}return zV(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:R,modelsCount:0}}if(jf.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=w9($.models),j=$.modelsSourceUrl?.trim(),P=await LV({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=_V($.headers);f.saveProviderSettings({provider:J,apiKey:H||void 0,baseUrl:W,headers:Y,timeout:$.timeoutMs,model:X,protocol:$.protocol,client:$.client},{setLastUsed:!1});let B=o$(f),A=await A2(B);return A.providers[J]={provider:{name:Q,baseUrl:W,defaultModelId:X,protocol:$.protocol,client:$.client,capabilities:V,modelsSourceUrl:j},models:C9(P,V)},await lJ(B,A),M4(J,A.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:B,modelsCount:P.length}}async function nJ(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=o$(f),H=await A2(W),Q=H.providers[J];if(!Q){let h=f.getProviderSettings(J);if(!h)throw Error(`provider "${J}" does not exist`);let G=$.modelsSourceUrl?.trim(),T=w9($.models)[0]??h.model?.trim();if(!T&&!G)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:$.name?.trim()||DV(J),baseUrl:$.baseUrl?.trim()??h.baseUrl?.trim()??"",defaultModelId:T,protocol:h.protocol,client:h.client,capabilities:h.capabilities},models:T?C9([T],h.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=w9($.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((h)=>h.trim()).filter(Boolean),U=await LV({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 h=$.apiKey?.trim()??"";if(h)M.apiKey=h;else delete M.apiKey}if($.headers!==void 0){let h=_V($.headers);if(h)M.headers=h;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}),H.providers[J]={provider:{name:Z,baseUrl:j,defaultModelId:F,protocol:X,client:V,capabilities:P,modelsSourceUrl:B},models:C9(U,P)},await lJ(W,H),M4(J,H.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:W,modelsCount:U.length}}async function aJ(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=o$(f),H=await A2(W);if(!H.providers[J])throw Error(`provider "${J}" does not exist`);return delete H.providers[J],await lJ(W,H),jf.unregisterProvider(J),zV(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:W}}async function S9(f){let $=f.read(),J=jf.getProviderIds().sort((H,Q)=>H.localeCompare(Q));return{providers:await Promise.all(J.map(async(H)=>{let[Q,Z]=await Promise.all([jf.getProvider(H),jf.getModelsForProvider(H)]),j=MV(Z),P=$.providers[H]?.settings,X=Q?.name??DV(H);return{id:H,name:X,models:j.length,color:__(H),letter:M_(X),enabled:Boolean(P),apiKey:P?h_(P):void 0,oauthAccessTokenPresent:P?D_(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 k9(f,$){let J=f.trim(),W=await L_(J,$),H=MV(W);return{providerId:J,models:H}}function m9(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 I9(f,$){let J=$.trim(),W=f.getProviderSettings(J),Q=jf.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,Z=W?.baseUrl?.trim()||Q?.baseUrl?.trim(),j=N6(Z,Q?.baseUrl,Q?.modelsSourceUrl);if(!W||!Q||!Z||!j)return{providerId:J,refreshed:!1};let P=await nJ(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:P.modelsCount}}function x9(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 z_(f,$){if(f==="cline")return $.access.startsWith("workos:")?$.access:`workos:${$.access}`;return $.access}async function g9(f,$,J){let W=T8({onPrompt:async(H)=>H.defaultValue??"",openUrl:J,onOpenUrlError:({error:H})=>{throw H instanceof Error?H:Error(String(H))}});if(f==="cline")return k1({apiBaseUrl:$?.baseUrl?.trim()||"https://api.cline.bot",useWorkOSDeviceAuth:!0,callbacks:W});if(f==="oca")return N1({mode:$?.oca?.mode,callbacks:W});return m1(W)}function v9(f,$,J,W){let H={...J?.auth??{},accessToken:z_($,W),refreshToken:W.refresh,accountId:W.accountId,expiresAt:W.expires},Q={...J??{provider:$},provider:$,auth:H};return f.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function u9(f){let $=f?.auth?.accessToken?.trim()||f?.apiKey?.trim();return $&&$.length>0?$:void 0}var O_=new Set(["ollama","lmstudio","litellm"]);function N_(f,$){if(!$?.provider.baseUrl)return!1;if($.provider.source!=="system")return!0;return O_.has(f)}function c9(f){let $=jf.normalizeProviderId(f);if(T_($))return{providerId:$,authMethod:"oauth",fields:{}};let J=jf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=J?.provider.baseUrl,H={apiKey:{}};if(N_($,J))H.baseUrl={defaultValue:W};return{providerId:$,authMethod:"api-key",fields:H}}var CV={};N(CV,{resolveLegacyClineAuth:()=>wV,migrateLegacyProviderSettings:()=>_4});import{existsSync as q_,readFileSync as b_}from"node:fs";import{dirname as w_,join as d9}from"node:path";import*as qV from"@cline/llms";import{resolveClineDataDir as C_}from"@cline/shared/storage";var bV="openai";function wV(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 NV(f){if(!q_(f))return;try{let $=b_(f,"utf8"),J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function E_(f){let $=f.dataDir??C_(),J=f.globalStatePath??d9($,"globalState.json"),W=f.secretsPath??d9($,"secrets.json"),H=NV(J),Q=NV(W);if(!H&&!Q)return;return{globalState:H??{},secrets:Q??{}}}function S_(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 k_(f){let $=E(f.openAiBaseUrl);if(!$)return!1;if(f.azureApiVersion||f.azureIdentity)return!1;return!S_($)}function r9(f,$){if(f==="openai"&&k_($))return bV;return f}function m_(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 I_(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,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 x_(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 g_(f){let $=qV.getGeneratedModelsForProvider(f);return Object.keys($)[0]??void 0}function v_(f,$,J,W){let H=r9(f,$),Q=E(W==="plan"?$.planModeApiProvider:$.actModeApiProvider),Z=m_($,f,W,Q)??g_(H),j=I_($,H,W),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,x_(J));if(f==="cline")try{let F=E(J["cline:clineAccountId"]);if(F)V.auth={...V.auth??{},...wV(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(W==="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(W==="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:H,...B?{apiKey:B}:{},...Z?{model:Z}:{},...A?{baseUrl:A}:{},...j?{reasoning:j}:{},...P?{timeout:P}:{},...V},U=R8.safeParse(R);if(!U.success)return;return Object.keys(R).filter((F)=>F!=="provider").length>0?U.data:void 0}function u_(f,$){if(f!==bV)return;if(!$.baseUrl||!$.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:$.baseUrl,defaultModelId:$.model},models:{[$.model]:{id:$.model,name:$.model}}}}function c_(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=E_(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=c_(W,H),j=t0();j.providers={...$.providers},j.lastUsedProvider=$.lastUsedProvider;let P=new Date().toISOString(),X=0,V=d9(w_(f.providerSettingsManager.getFilePath()),"models.json"),Y=b9(V),B=0;for(let U of Z){let y=r9(U,W);if(j.providers[y])continue;let F=v_(U,W,H,Q);if(!F)continue;j.providers[y]={settings:F,updatedAt:P,tokenSource:"migration"},X+=1;let K=u_(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"?W.planModeApiProvider:W.actModeApiProvider),R=A?r9(A,W):void 0;if(j.lastUsedProvider=$.lastUsedProvider??(R&&j.providers[R]?R:Object.keys(j.providers)[0]),f.providerSettingsManager.write(j),B>0)FV(V,Y);return{migrated:X>0||B>0,providerCount:Object.keys(j.providers).length,lastUsedProvider:j.lastUsedProvider}}Gf();SJ();var EV={};N(EV,{FileTeamPersistenceStore:()=>tJ});import{appendFileSync as d_,existsSync as l9,mkdirSync as r_,readFileSync as l_,renameSync as p_,unlinkSync as i_,writeFileSync as n_}from"node:fs";import{join as p9}from"node:path";import{resolveTeamDataDir as a_}from"@cline/shared/storage";function t_(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class tJ{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor(f){let $=t_(f.teamName),J=f.baseDir?.trim()||a_();this.dirPath=p9(J,$),this.statePath=p9(this.dirPath,"state.json"),this.taskHistoryPath=p9(this.dirPath,"task-history.jsonl")}loadState(){if(!l9(this.statePath))return;try{let f=l_(this.statePath,"utf8"),$=JSON.parse(f);if($.version!==1||!$.teamState)return;for(let J of $.teammates??[])this.teammateSpecs.set(J.agentId,J);return CP($.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`;n_(J,`${JSON.stringify($,null,2)}
|
|
714
|
-
`,"utf8"),
|
|
715
|
-
`,"utf8")}ensureDir(){if(!l9(this.dirPath))r_(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(l9(this.statePath))i_(this.statePath)}}var SV={};N(SV,{ChatViewStateSchema:()=>i9,ChatSummarySchema:()=>$W,ChatSessionStatusSchema:()=>oJ,ChatSessionConfigSchema:()=>sJ,ChatMessageSchema:()=>fW,ChatMessageRoleSchema:()=>eJ});import{z as q}from"zod";var sJ=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()}),oJ=q.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),eJ=q.enum(["user","assistant","tool","system","status","error"]),fW=q.object({id:q.string().min(1),sessionId:q.string().nullable(),role:eJ,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()}),$W=q.object({toolCalls:q.number().int().nonnegative(),tokensIn:q.number().int().nonnegative(),tokensOut:q.number().int().nonnegative()}),i9=q.object({sessionId:q.string().nullable(),status:oJ,config:sJ,messages:q.array(fW),rawTranscript:q.string(),error:q.string().nullable(),summary:$W});var kV={};N(kV,{CORE_BUILD_VERSION:()=>n9});var n9=xj;import{Agent as OL,createAgentRuntime as NL}from"@cline/agents";var xV={};N(xV,{fetchClineRecommendedModels:()=>a9,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>JW});var mV="https://api.cline.bot",s_=5000,JW={recommended:[{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",description:"Most intelligent model for agents and coding",tags:["BEST"]},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",description:"Strong coding and agent performance",tags:["NEW"]},{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"1M context window, strong coding performance",tags:["NEW"]},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",description:"OpenAI's latest with strong coding abilities",tags:["NEW"]}],free:[{id:"kwaipilot/kat-coder-pro",name:"KwaiKAT Kat Coder Pro",description:"Advanced agentic coding model",tags:["FREE"]},{id:"arcee-ai/trinity-large-preview:free",name:"Arcee AI Trinity Large Preview",description:"Advanced large preview model",tags:["FREE"]}]};function o_(f){return{recommended:f.recommended.map(($)=>({...$,tags:[...$.tags]})),free:f.free.map(($)=>({...$,tags:[...$.tags]}))}}function IV(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 e_(f){if(!f||typeof f!=="object")return null;let $=f,J=Array.isArray($.recommended)?$.recommended:[],W=Array.isArray($.free)?$.free:[],H=J.map(IV).filter((Z)=>Z!==null),Q=W.map(IV).filter((Z)=>Z!==null);if(H.length===0&&Q.length===0)return null;return{recommended:H,free:Q}}function fL(f){let $=f.baseUrl?.trim();if($)return $;try{return(f.providerSettingsManager??new P0).getProviderSettings("cline")?.baseUrl?.trim()||mV}catch{return mV}}async function $L(f,$,J){let W=new AbortController,H=setTimeout(()=>W.abort(),J);try{return await f($,{signal:W.signal})}finally{clearTimeout(H)}}async function a9(f={}){try{let $=fL(f),J=f.fetchImpl??fetch,W=await $L(J,`${$}/api/v1/ai/cline/recommended-models`,f.timeoutMs??s_);if(!W.ok)throw Error(`HTTP ${W.status}`);let H=await W.json(),Q=e_(H);if(Q)return Q}catch{}return o_(JW)}var gV={};N(gV,{loadLlmsConfigFromFile:()=>s9,defineLlmsConfig:()=>t9});import{readFile as JL}from"node:fs/promises";import WL from"node:path";function t9(f){return f}async function s9(f){let $=WL.resolve(f),J=await JL($,"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 HL(W,$)}function HL(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 lV={};N(lV,{createLlmsSdk:()=>e9,DefaultLlmsSdk:()=>L4});import{BUILT_IN_PROVIDER_IDS as cV,createHandler as jL,createHandlerAsync as PL,getProviderCollection as XL,hasProvider as dV,registerAsyncHandler as VL,registerHandler as YL,registerModel as BL,registerProvider as rV}from"@cline/llms";function vV(f){return f?{...f}:{}}function QL(f,$){if(f)return f;if(!$)return;let J=globalThis.process;if(!J?.env)return;return J.env[$]}function ZL(f,$){if(!$.length)throw Error(`Provider "${f}" must include at least one model.`)}function uV(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 o9{providers=new Map;register(f){ZL(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??{},...vV(f.defaults)}})}registerSelectionConfig(f){this.register({id:f.id,models:f.models,defaultModel:f.defaultModel,defaults:{apiKey:QL(f.apiKey,f.apiKeyEnv),routingProviderId:f.builtinProviderId,baseUrl:f.baseUrl,headers:f.headers,timeoutMs:f.timeoutMs,capabilities:f.capabilities,...vV(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 o9;constructor(f){this.applyConfig(f)}createHandler(f){return jL(this.configuredProviders.createHandlerConfig(f))}async createHandlerAsync(f){return PL(this.configuredProviders.createHandlerConfig(f))}registerProvider(f){if(rV(f.collection),f.handlerFactory&&f.asyncHandlerFactory)throw Error(`Provider "${f.collection.provider.id}" cannot register both sync and async handlers.`);if(f.handlerFactory)YL(f.collection.provider.id,f.handlerFactory);if(f.asyncHandlerFactory)VL(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.`);rV({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){BL(f.providerId,f.modelId,f.info),this.configuredProviders.registerModel(f.providerId,f.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...cV]}async getBuiltInProviders(){return(await Promise.all(cV.map(($)=>XL($)))).filter(($)=>$!==void 0).map(($)=>uV({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=dV($.id),W=this.configuredProviders.createHandlerConfig({providerId:$.id,modelId:$.defaultModel}).routingProviderId,H=typeof W==="string"&&dV(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 e9(f){return new L4(f)}$9();async function AL(){return Promise.resolve().then(() => (iV(),pV))}function EL(){return new Date().toISOString()}function SL(f){if(sV(f)!=="providers.json")return;let $=$3(f);if(sV($)!=="settings")return;return $3($)}class P0{filePath;dataDir;constructor(f={}){if(this.filePath=f.filePath??CL(),this.dataDir=f.dataDir??SL(this.filePath),this.dataDir||!f.filePath)_4({providerSettingsManager:this,dataDir:this.dataDir});if(hV(this),pJ(this.read()),f3(this.filePath))try{tV(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!f3(this.filePath))return t0();try{let f=bL(this.filePath,"utf8"),$=JSON.parse(f),J=w1.safeParse($);if(J.success)return pJ(J.data),J.data}catch{}return t0()}write(f){let $=w1.parse(f),J=$3(this.filePath);if(!f3(J))qL(J,{recursive:!0,mode:448});wL(this.filePath,`${JSON.stringify($,null,2)}
|
|
716
|
-
`,"utf8");try{tV(this.filePath,384)}catch{}pJ($)}saveProviderSettings(f,$={}){let J=R8.parse(f),W=this.read(),H=J.provider,Q=$.setLastUsed!==!1,Z=W.providers[H],j=$.tokenSource??Z?.tokenSource??"manual",P={...W,providers:{...W.providers,[H]:{settings:J,updatedAt:EL(),tokenSource:j}},lastUsedProvider:Q?H:W.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 bf(J,$)}getLastUsedProviderConfig(f){let $=this.getLastUsedProviderSettings();if(!$)return;return bf($,f)}async refreshCatalog(){try{await q1({})}catch{}}}Gf();_J();import{isOAuthProviderId as kL}from"@cline/shared";var mL="https://api.cline.bot",J3="workos:";function IL(f,$){if(f==="cline")return`${J3}${$}`;return $}function xL(f,$){if(f==="cline"&&$.toLowerCase().startsWith(J3))return $.slice(J3.length);return $}function gL(f){let J=Rf(f)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function vL(f,$){let J=f.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let W=gL($);if(W)return W;return Date.now()-1}function uL(f,$){let J=$.auth?.accessToken?.trim(),W=$.auth?.refreshToken?.trim();if(!J||!W)return null;let H=xL(f,J);if(!H)return null;return{access:H,refresh:W,expires:vL($,H),accountId:$.auth?.accountId}}function cL(f,$){let J=f?.expiresAt,W=$?.expiresAt;return f?.accessToken===$?.accessToken&&f?.refreshToken===$?.refreshToken&&f?.accountId===$?.accountId&&J===W}class WW 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 W3{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor(f){this.providerSettingsManager=f?.providerSettingsManager??new P0,this.telemetry=f?.telemetry}async resolveProviderApiKey(f){if(!kL(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=uL(f,J);if(!W)return null;let H=await this.resolveCredentials(f,J,W,$);if(!H)throw new WW(f);let Q=IL(f,H.access),Z={...J.auth??{},accessToken:Q,refreshToken:H.refresh,accountId:H.accountId};Z.expiresAt=H.expires;let j={...J,auth:Z},P=!cL(J.auth,j.auth);if(P)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:f,apiKey:Q,accountId:H.accountId,refreshed:P}}async resolveCredentials(f,$,J,W){if(f==="cline")return D8(J,{apiBaseUrl:$.baseUrl?.trim()||mL,telemetry:this.telemetry},{forceRefresh:W});if(f==="oca")return P8(J,{forceRefresh:W,telemetry:this.telemetry},{mode:$.oca?.mode,telemetry:this.telemetry});return _8(J,{forceRefresh:W,telemetry:this.telemetry})}}import{normalizeUserInput as dL}from"@cline/shared";import{nanoid as rL}from"nanoid";class oV{list(f){return f?gf(f):[]}update(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=$.promptId.trim(),W=f.pendingPrompts.findIndex((P)=>P.id===J);if(W<0)return{sessionId:$.sessionId,prompts:gf(f),updated:!1};let H=f.pendingPrompts[W];if(!H)return{sessionId:$.sessionId,prompts:gf(f),updated:!1};let Q=$.prompt===void 0?H.prompt:dL($.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),lL(f,j,W,H.delivery),{sessionId:$.sessionId,prompts:gf(f),prompt:HW(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:gf(f),removed:!1};let[H]=f.pendingPrompts.splice(W,1);return{sessionId:$.sessionId,prompts:gf(f),prompt:H?HW(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),P={...j,prompt:J,userImages:H??j.userImages,userFiles:Q??j.userFiles};if(W==="steer"||j.delivery==="steer")f.pendingPrompts.unshift({...P,delivery:"steer"});else f.pendingPrompts.push(P)}else{let j={id:`pending_${Date.now()}_${rL(5)}`,prompt:J,delivery:W,userImages:H,userFiles:Q};if(W==="steer")f.pendingPrompts.unshift(j);else f.pendingPrompts.push(j)}return gf(f)}consumeSteer(f){let $=f.pendingPrompts.findIndex((W)=>W.delivery==="steer");if($<0)return{prompts:gf(f)};let[J]=f.pendingPrompts.splice($,1);return{entry:J,prompts:gf(f)}}shiftNext(f){return{entry:f.pendingPrompts.shift(),prompts:gf(f)}}requeueFront(f,$){return f.pendingPrompts.unshift($),gf(f)}clear(f){return f.pendingPrompts.length=0,[]}}class H3{deps;service=new oV;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:gf(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=HW($);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:f.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function HW(f){return{id:f.id,prompt:f.prompt,delivery:f.delivery,attachmentCount:(f.userImages?.length??0)+(f.userFiles?.length??0)}}function gf(f){return f.pendingPrompts.map(HW)}function lL(f,$,J,W){if($.delivery==="steer")f.pendingPrompts.unshift($);else if(W==="steer")f.pendingPrompts.push($);else f.pendingPrompts.splice(J,0,$)}Gf();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,persistMessages:this.deps.persistMessages,emit:this.deps.emit},Q=nW(J),Z=W&&Q.agentId===eV(W.agent);aW(H,J,Z?{isPrimaryAgentEvent:!0,...W?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent(f,$){let J=this.deps.getSession(f);if(J){if(xH(J,$),$.type==="agent_event"){let W={sessionId:f,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};aW(W,$.event,{teamRole:"teammate",teamAgentId:$.agentId,isPrimaryAgentEvent:!1})}if($.type==="teammate_spawned"){let W=U0({agentId:$.teammate.runtimeAgentId??$.agentId,conversationId:$.teammate.conversationId,parentAgentId:$.teammate.parentAgentId,createdByAgentId:eV(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:$.agentId});if(W)v0(J.config.telemetry,{ulid:f,modelId:$.teammate.modelId??J.config.modelId,provider:J.config.providerId,...W})}}if(await gH(f,$,this.deps.invokeBackendOptional),J)vH(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 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 eV(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:d0(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 fY(f,$,...J){let W=j3(f,$);if(!W)throw Error(`session service method not available: ${$}`);return Promise.resolve(W.apply(f,J))}async function $Y(f,$,...J){let W=j3(f,$);if(!W)return;await Promise.resolve(W.apply(f,J))}async function JY(f,$,...J){let W=j3(f,$);if(!W)return;return await Promise.resolve(W.apply(f,J))}G0();Gf();function P3(f,$,J,W){return I0({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?T$({cwd:$.cwd,...Nf[B0({mode:$.mode})],executors:W}):[];if($.enableSpawnAgent)Q.push(P3(f,$,J,W));return z$(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=U0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)v0($.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),P=j?Date.now()-j.startedAt:0,X=Q.result?.text?Q.result.text.split(`
|
|
717
|
-
`).length:0;n2($.telemetry,{event:"ended",ulid:J,durationMs:P,outputLines:X,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...U0({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 pL,stat as iL}from"node:fs/promises";var nL=20480000;async function WY(f){let $=await iL(f);if(!$.isFile())throw Error("Path is not a file");if($.size>nL)throw Error("File is too large to read into context.");let J=await pL(f,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var HY=5000;class Z0{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new a8;sessions=new Map;usageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new j$;constructor(f){let $=aL();if($)$z($);let J=c$(f.distinctId);this.sessionService=f.sessionService,this.runtimeBuilder=f.runtimeBuilder??new B2,this.createAgentInstance=f.createAgent??((W)=>new m0(W)),this.defaultCapabilities=Vf(f.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=f.toolPolicies,this.providerSettingsManager=f.providerSettingsManager??new P0,this.oauthTokenManager=f.oauthTokenManager??new W3({providerSettingsManager:this.providerSettingsManager,telemetry:f.telemetry}),this.defaultTelemetry=f.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=f.fetch,this.pendingPromptsController=new H3({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,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??Pf.CLI,J=s(),W=f.config.sessionId?.trim()??"",H=W||oL(),Q=f,Z=Q.initialMessages??[];this.usageBySession.set(H,Z.length>0?a2(Z):u0());let j=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!j)throw Error("session service method not available: ensureSessionsDir");let P=X3(j,H),X=X3(P,`${H}.messages.json`),V=X3(P,`${H}.json`),Y=d0(f.config),B=Uf.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:X}),A;if(W.length>0&&Z.length>0&&!Q.prompt?.trim()){let C=await this.invokeOptionalValue("readSessionManifest",H);if(C)B=C,A={manifestPath:V,messagesPath:C.messages_path||X,manifest:C}}let U=Vf(this.defaultCapabilities,f.capabilities),y=U?.toolExecutors??this.toolExecutors,F=f.localRuntime,K=F?.extensionContext?.logger??F?.logger,M=F?.extensionContext?.automation,h;h=await FZ({input:Q,localRuntime:f.localRuntime,sessionId:H,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(C)=>{if(C.name==="plugin_log"){this.eventBridge.handlePluginLog(H,C.payload,K);return}this.eventBridge.handlePluginEvent(H,C,M)},onTeamEvent:(C)=>{this.eventBridge.handleTeamEvent(H,C),h.config.onTeamEvent?.(C)},createSpawnTool:()=>P3({getSession:(C)=>this.sessions.get(C),subAgentStarts:this.subAgentStarts,onAgentEvent:(C,af,uf)=>this.eventBridge.dispatchAgentEvent(C,af,uf),invokeBackendOptional:(C,...af)=>this.invokeOptional(C,...af)},h.config,H,y),readSessionMetadata:async()=>(await this.getSession(H))?.metadata,writeSessionMetadata:async(C)=>{await this.persistSessionMetadata(H,()=>C)}});let G=await this.runtimeBuilder.build(h.runtimeBuilderInput),T=h.config,z=h.providerConfig;if(G.teamRuntime&&!T.teamName?.trim())T.teamName=G.teamRuntime.getTeamName();let u=[...G.tools,...T.extraTools??[]],vf=G.extensions??h.extensions,a={sessionId:H,providerId:z.providerId,modelId:z.modelId,apiKey:z.apiKey,baseUrl:z.baseUrl,headers:z.headers,knownModels:z.knownModels,providerConfig:z,thinking:T.thinking,reasoningEffort:T.reasoningEffort??z.reasoningEffort,systemPrompt:T.systemPrompt,maxIterations:T.maxIterations,execution:T.execution,prepareTurn:h2(T),tools:u,hooks:h.hooks,extensions:vf,hookErrorMode:T.hookErrorMode,initialMessages:h.effectiveInput.initialMessages,userFileContentLoader:WY,toolPolicies:h.toolPolicies,requestToolApproval:h.requestToolApproval,onConsecutiveMistakeLimitReached:T.onConsecutiveMistakeLimitReached,completionPolicy:G.completionPolicy,consumePendingUserMessage:()=>{let C=this.pendingPromptsController.consumeSteer(H);return C?Q4(C,T.mode):C},logger:G.logger??T.logger,extensionContext:T.extensionContext,onEvent:(C)=>this.eventBridge.dispatchAgentEvent(H,T,C)};a.hooks={...a.hooks,onEvent:async(C)=>{if(await h.hooks?.onEvent?.(C),C.type!=="assistant-message")return;let af=this.sessions.get(H);if(!af)return;let uf=af.agent.getMessages();try{await this.invoke("persistSessionMessages",H,uf,T.systemPrompt)}catch($f){T.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:H,error:$f})}}};let c=this.createAgentInstance(a);if(a.onEvent)c.subscribeEvents(a.onEvent);G.registerLeadAgent?.(c);let d=U0({agentId:c.getAgentId(),conversationId:c.getConversationId(),teamId:G.teamRuntime?.getTeamId(),teamName:G.teamRuntime?.getTeamName(),teamRole:G.teamRuntime?"lead":void 0});if(KZ(T,H,W.length>0,Y,d),d)v0(T.telemetry,{ulid:H,modelId:T.modelId,provider:T.providerId,...d});if(G.teamRuntime)J6(T.telemetry,{ulid:H,teamId:G.teamRuntime.getTeamId(),teamName:G.teamRuntime.getTeamName(),leadAgentId:c.getAgentId(),restoredFromPersistence:G.teamRestoredFromPersistence===!0});let t={sessionId:H,config:T,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:h.pluginSandboxShutdown,submitAndExitObserved:!1};if(this.sessions.set(H,t),this.emitStatus(H,"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 nf;try{if(Q.prompt?.trim())if(nf=await this.executeTurn(t,{prompt:Q.prompt,userImages:Q.userImages,userFiles:Q.userFiles}),!t.interactive)await this.finalizeSingleRun(t,nf.finishReason);else await this.completeInteractiveTurn(t,nf.finishReason)}catch(C){if(t.interactive&&t.aborting)nf=await this.completeAbortedInteractiveTurn(t);else throw await this.failSession(t),C}return{sessionId:H,manifest:B,manifestPath:V,messagesPath:X,result:nf}}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){return qj(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 Z3($);let J=f.trim();if(!J)return;let W=await this.getRow(J);if(W)return r2(W);let H=await this.readManifest(J);return H?RJ(H):void 0}async listSessions(f=200){let J=(await this.listRows(f)).map(r2),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);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 bj(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(uH(f,H.finishReason)){let Q=await cH(f);if(Q.length===0)break;let Z=dH(f,Q);H=await this.executeAgentTurn(f,Z)}return H}async completeInteractiveTurn(f,$){if(H4(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:u0(),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)??u0();f.turnUsageBaseline=Z,a4(f.config.telemetry,f.sessionId,f.config.mode),F1(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=H?()=>f.agent.continue($,J,W):()=>f.agent.run($,J,W),P=await this.runWithAuthRetry(f,j,Q);f.started=!0;let X=c4(P.messages,P,Q);f.persistedMessages=X;let V=c0(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((W)=>W.name===ff.SUBMIT_AND_EXIT&&W.error===void 0))return;f.submitAndExitObserved=!0,p2(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=d0(f.config),W=fz($.prompt).trim();if(!W)return{prompt:"",userImages:$.userImages,userFiles:this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles)};let H=await H1(W,J);UZ(f.config.telemetry,H);let Q=Q4(H.prompt,f.config.mode),Z=this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles),j=this.resolveAbsoluteFilePaths(J,H.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 $=d0(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(H4(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)p2(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)});zJ(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(!eL(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 WW)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)=>tL(W)?W:sL(f,W));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity(f){return U0({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:$0({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)),HY))}async getRow(f){let $=f.trim();if(!$)return;return(await this.listRows(HY)).find((W)=>W.sessionId===$)}async readManifest(f){let $=f.trim();if(!$)return;return await this.invokeOptionalValue("readSessionManifest",$)}invoke(f,...$){return fY(this.sessionService,f,...$)}invokeOptional(f,...$){return $Y(this.sessionService,f,...$)}invokeOptionalValue(f,...$){return JY(this.sessionService,f,...$)}}function Wz(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 Hz(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}function uJ(f={}){let $=new Z0({sessionService:new Q0(new W0),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()||Pf.CLI,interactive:!1,config:{providerId:Jz(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:Hz(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:Wz(H)}},async abortSession(J){return await $.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}Qz(process.env.CLINE_VCR);function Zz(f){let $=process.cwd(),J,W,H;for(let Q=0;Q<f.length;Q+=1){let Z=f[Q],j=f[Q+1];if(Z==="--cwd"&&j){$=j,Q+=1;continue}if(Z==="--host"&&j){J=j,Q+=1;continue}if(Z==="--port"&&j){let P=Number(j);if(Number.isFinite(P))W=P;Q+=1;continue}if(Z==="--pathname"&&j)H=j,Q+=1}return{cwd:$,host:J,port:W,pathname:H}}async function jz(){let f=Zz(process.argv.slice(2));process.chdir(f.cwd);let $=Sf({host:f.host,port:f.port,pathname:f.pathname}),J=await t$({host:$.host,port:$.port,pathname:$.pathname,owner:Qf(),runtimeHandlers:uJ(),cronOptions:{workspaceRoot:f.cwd}}),W=async()=>{await J.close(),process.exit(0)},H=!1,Q=(Z,j)=>{if(H)return;H=!0;let P=j instanceof Error?j.stack||j.message:String(j);process.stderr.write(`[hub-daemon] ${Z}: ${P}
|
|
718
|
-
`),J.close().catch((
|
|
719
|
-
`)}).finally(()=>{process.exit(1)})};process.on("SIGINT",()=>{W()}),process.on("SIGTERM",()=>{W()}),process.on("uncaughtException",(Z)=>{Q("uncaughtException",Z)}),process.on("unhandledRejection",(Z)=>{Q("unhandledRejection",Z)}),await new Promise(()=>{})}
|
|
709
|
+
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=R2(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=EH();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
|
|
710
|
+
WHERE team_name = ? AND status IN ('queued', 'running')`,[$,H,J]),W.map((Q)=>Q.run_id)}handleTeamEvent(f,$){this.appendTeamEvent(f,$.type,$)}}function SH(f={}){try{let $=new e$(f);return $.init(),$}catch{let $=new z4({teamDir:f.teamDir});return $.init(),$}}function kH(f,$){return DL(f,$)}function ML(f,$){let J=$?.["*"]??{},W=$?.[f]??{};return{...J,...W}.enabled!==!1}function LL(f,$){return f.filter((J)=>ML(J.name,$))}function bP(f,$){return w$(LL(f,$))}function dJ(){return`team-${_L(5)}`}function IH(f,$,J,W,H,Q,Z,j){let X=Ef[K0({mode:J})],A=A1($,W,J,H??X1);return bP(L$({cwd:f,...X,enableSkills:!!Z,...A,executors:{...Z?{skills:Z}:{},...j??{}}}),Q)}function hL(f){return IH(f.cwd,f.providerId,f.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,OL,f.toolExecutors).some(($)=>$.name==="skills")}var OL=async()=>"";async function zL(f){let $=P$();if(!f2({filePath:$}))return{tools:[]};let J=new i$({clientFactory:e1()}),W;try{W=await $2(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)=>J2({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 NL(f,$){if(!f)return;for(let J of f.getTeammateIds())try{f.shutdownTeammate(J,$)}catch{}}function qL(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 wL(f){let $=Ef[K0({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 F2{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=wL($),V=nf(),R=[],U=$.teamName?.trim()||dJ(),K=$.sessionId?.trim()||U,F=kH(A,"rules"),y=kH(A,"skills"),D=kH(A,"workflows"),M=F||y||D,T=!1,_=Boolean(X),L=X,q;if(!L&&M)L=$$({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)&&hL({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(...IH($.cwd,$.providerId,Y.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,P)),!Y.disableMcpSettingsTools){let r=await zL($.logger);R.push(...r.tools),q=r.shutdown}}let c,Gf=Y.enableAgentTeams?SH():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,$1=B1({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:$1});let y2=()=>{if(!Y.enableAgentTeams)return;let r=this.teamRuntimeEntries.get(n)??{delegatedAgentConfigProvider:$1};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"&&!qL($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=R1({runtime:c,leadAgentId:$.sessionId||"lead",restoredFromPersistence:Boolean(i),restoredTeammates:P0,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(V0)=>{Y0=V0,B0?.addTools(V0)},createBaseTools:Y.enableTools?()=>IH($.cwd,$.providerId,Y.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,P):void 0,teammateConfigProvider:$1});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 y2(),r.execute($f,V0)}})}if(Y.enableAgentTeams)y2();let C4=bP(R,$.toolPolicies),Z5=C4.some((r)=>r.name===Jf.SUBMIT_AND_EXIT&&r.lifecycle?.completesRun===!0),J1=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"),_3=r.listRuns({}),hB=_3.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(", "),M3=_3.filter((qf)=>qf.status==="running"||qf.status==="queued").map((qf)=>`${qf.id} (${qf.status})`).join(", "),j5=[];if(S0)j5.push(`Unfinished tasks: ${S0}`);if(M3)j5.push(`Active runs: ${M3}`);return`[SYSTEM] You still have team obligations. ${j5.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,U2=Z5?{requireCompletionTool:!0,...J1?{completionGuard:J1}:{}}:J1?{completionGuard:J1}:void 0;return{tools:C4,logger:H??$.logger,telemetry:Q??$.telemetry,teamRuntime:c,teamRestoredFromPersistence:Boolean(i),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(n)?.delegatedAgentConfigProvider??$1,extensions:o,completionPolicy:U2,registerLeadAgent:(r)=>{if(B0=r,Y0.length>0)r.addTools(w$(Y0,[...V]))},shutdown:async(r)=>{if(NL(c,r),this.teamRuntimeEntries.delete(n),await q?.(),!_)L?.stop()}}}}var SP={};N(SP,{requestDesktopToolApproval:()=>xH});import{mkdir as bL,readFile as CL,unlink as EL,writeFile as SL}from"node:fs/promises";import{join as EP}from"node:path";function kL(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function IL(f){return new Promise(($)=>setTimeout($,f))}async function mH(f){try{await EL(f)}catch{}}async function xH(f,$={}){let J=$.approvalDir?.trim(),W=$.sessionId?.trim();if(!J||!W)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await bL(J,{recursive:!0});let H=kL(`${f.toolCallId}`),Q=EP(J,`${W}.request.${H}.json`),Z=EP(J,`${W}.decision.${H}.json`),j=$.nowIso??(()=>new Date().toISOString());await SL(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)}
|
|
711
|
+
`,"utf8");let X=$.timeoutMs??300000,A=$.pollIntervalMs??200,P=Date.now();while(Date.now()-P<X){try{let B=await CL(Z,"utf8"),Y=JSON.parse(B),V={approved:Y.approved===!0,reason:typeof Y.reason==="string"?Y.reason:void 0};return await Promise.all([mH(Z),mH(Q)]),V}catch{}await IL(A)}return await mH(Q),{approved:!1,reason:"Tool approval request timed out"}}M0();var sP={};N(sP,{updateLocalProvider:()=>aJ,saveLocalProviderSettings:()=>pH,saveLocalProviderOAuthCredentials:()=>tH,resolveLocalClineAuthToken:()=>sH,refreshProviderModelsFromSource:()=>iH,normalizeOAuthProvider:()=>nH,loginLocalProvider:()=>aH,listLocalProviders:()=>rH,getProviderConfigFields:()=>oH,getLocalProviderModels:()=>lH,ensureCustomProvidersLoaded:()=>nJ,deleteLocalProvider:()=>tJ,addLocalProvider:()=>dH});import*as Yf from"@cline/llms";import{getClineEnvironmentConfig as Hh,isOAuthProviderId as Qh}from"@cline/shared";import{existsSync as mL,mkdirSync as xL,readFileSync as gL,writeFileSync as vL}from"node:fs";import{mkdir as uL,readFile as cL,writeFile as dL}from"node:fs/promises";import{dirname as gH,join as rL}from"node:path";import*as Nf from"@cline/llms";import{ModelCapabilitySchema as lL,ProviderCapabilitySchema as pL,ProviderClientSchema as iL,ProviderProtocolSchema as nL}from"@cline/shared";import{z as p}from"zod";var aL=p.object({id:p.string().optional(),name:p.string().optional(),capabilities:p.array(lL).optional(),supportsVision:p.boolean().optional(),supportsAttachments:p.boolean().optional(),supportsReasoning:p.boolean().optional()}).passthrough(),tL=p.object({name:p.string(),baseUrl:p.string(),defaultModelId:p.string().optional(),protocol:nL.optional(),client:iL.optional(),capabilities:p.array(pL).optional(),modelsSourceUrl:p.string().optional()}).passthrough(),kP=p.object({provider:tL.optional(),models:p.record(p.string(),aL).optional()}).passthrough(),IP=p.object({version:p.literal(1),providers:p.record(p.string(),kP)}),sL=p.object({version:p.literal(1),providers:p.record(p.string(),p.unknown())}),rJ=new Set;function mP(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function f1(f){return rL(gH(f.getFilePath()),"models.json")}function lJ(){return{version:1,providers:{}}}function xP(f){let $=sL.safeParse(f);if(!$.success)return lJ();let J={};for(let[W,H]of Object.entries($.data.providers)){let Q=kP.safeParse(H);if(Q.success)J[W]=Q.data}return{version:1,providers:J}}function vH(f){if(!mL(f))return lJ();try{let $=gL(f,"utf8");return xP(JSON.parse($))}catch{}return lJ()}async function K2(f){try{let $=await cL(f,"utf8");return xP(JSON.parse($))}catch{}return lJ()}function gP(f,$){xL(gH(f),{recursive:!0});let J=IP.parse($);vL(f,`${JSON.stringify(J,null,2)}
|
|
712
|
+
`,"utf8")}async function pJ(f,$){await uL(gH(f),{recursive:!0});let J=IP.parse($);await dL(f,`${JSON.stringify(J,null,2)}
|
|
713
|
+
`,"utf8")}function vP(f,$){return{id:f,name:$.name??f,supportsAttachments:$.capabilities?.includes("files"),supportsVision:$.capabilities?.includes("images"),supportsReasoning:$.capabilities?.includes("reasoning")||$.thinkingConfig!=null}}function uP(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 cP(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 oL(f){return f!=null&&typeof f.name==="string"&&typeof f.baseUrl==="string"}function dP(f,$){return f??$??"openai-chat"}function rP(f,$,J){return f??J??($==="openai-responses"?"openai":"openai-compatible")}function eL(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 fh(f,$){for(let[J,W]of Object.entries($??{})){let H=W.id?.trim()||J.trim();if(!H)continue;Nf.registerModel(f,H,eL(H,W))}}function $h(f,$,J){return{...$??{},id:f,name:$?.name??f,capabilities:$?.capabilities??J}}function Jh(f){return Object.assign({},...Nf.resolveProviderModelCatalogKeys(f).map((J)=>Nf.getGeneratedModelsForProvider(J)))}function Wh(f){let $=f.provider.trim();if(!$||Nf.isBuiltInProviderId($))return;let J=f.baseUrl?.trim();if(!J)return;let W=Nf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],H=Jh($),Q=cP(f.capabilities),Z=Q.length>0?Q:void 0,j=f.model?.trim(),X={...H,...W?.models??{}};if(j)X[j]=$h(j,X[j],Z);let A=Object.keys(X).filter(Boolean),P=j||A[0];if(!P)return;let B=dP(f.protocol,W?.provider.protocol),Y=rP(f.client,B,W?.provider.client);Nf.registerProvider({provider:{id:$,name:W?.provider.name??mP($),description:W?.provider.description,protocol:B,client:Y,baseUrl:J,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:P,capabilities:uP(f.capabilities)??W?.provider.capabilities,source:"file"},models:X})}function iJ(f){for(let $ of Object.values(f.providers))Wh($.settings)}function N4(f,$){let J=$.models??{};if(!oL($.provider)){fh(f,J);return}let W=cP($.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=dP($.provider.protocol,void 0),j=rP($.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"}]));Nf.registerProvider({provider:{id:f,name:$.provider.name.trim()||mP(f),protocol:Z,client:j,baseUrl:$.provider.baseUrl,modelsSourceUrl:$.provider.modelsSourceUrl,defaultModelId:Q,capabilities:uP($.provider.capabilities),source:"file"},models:X})}function lP(f){let $=f1(f);if(rJ.has($))return;let J=vH($);for(let[W,H]of Object.entries(J.providers))N4(W,H);rJ.add($)}async function nJ(f){let $=f1(f);if(rJ.has($))return;let J=await K2($);for(let[W,H]of Object.entries(J.providers))N4(W,H);rJ.add($)}function Zh(f){return f.apiKey??f.auth?.apiKey}function jh(f){return(f.auth?.accessToken?.trim()??"").length>0}function pP(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function Xh(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 Ah(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 iP(f){return Object.entries(f).sort(([$],[J])=>$.localeCompare(J)).map(([$,J])=>vP($,J))}async function Ph(f,$){let J=await Yf.getModelsForProvider(f);if(!$)return J;let W=await K8(f,{loadPrivateOnAuth:!0,failOnError:!1},$);return W?.knownModels?{...J,...W.knownModels}:J}function uH(f){return[...new Set((f??[]).map(($)=>$.trim()).filter(Boolean))]}function nP(f){let $=Object.entries(f??{}).filter(([J])=>J.trim().length>0);return $.length>0?Object.fromEntries($):void 0}function cH(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 aP(f){if(!f.shouldRecompute)return f.fallbackModelIds??[];let $=f.modelsSourceUrl?await O6(f.modelsSourceUrl,f.providerId):[];return[...new Set([...f.explicitModels??[],...$])]}function tP(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);Yf.unregisterProvider($)}async function dH(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=f1(f);if((await K2(R)).providers[J]){let K=await tJ(f,{providerId:J});return{providerId:J,settingsPath:K.settingsPath,modelsPath:K.modelsPath,modelsCount:0}}return tP(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:R,modelsCount:0}}if(Yf.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=uH($.models),j=$.modelsSourceUrl?.trim(),X=await aP({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=nP($.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=f1(f),V=await K2(Y);return V.providers[J]={provider:{name:Q,baseUrl:W,defaultModelId:A,protocol:$.protocol,client:$.client,capabilities:P,modelsSourceUrl:j},models:cH(X,P)},await pJ(Y,V),N4(J,V.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:Y,modelsCount:X.length}}async function aJ(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=f1(f),H=await K2(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(),_=uH($.models)[0]??M.model?.trim();if(!_&&!T)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:$.name?.trim()||pP(J),baseUrl:$.baseUrl?.trim()??M.baseUrl?.trim()??"",defaultModelId:_,protocol:M.protocol,client:M.client,capabilities:M.capabilities},models:_?cH([_],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=uH($.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 aP({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=nP($.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:cH(U,X)},await pJ(W,H),N4(J,H.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:W,modelsCount:U.length}}async function tJ(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=f1(f),H=await K2(W);if(!H.providers[J])throw Error(`provider "${J}" does not exist`);return delete H.providers[J],await pJ(W,H),Yf.unregisterProvider(J),tP(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:W}}async function rH(f){let $=f.read(),J=Yf.getProviderIds().sort((H,Q)=>H.localeCompare(Q));return{providers:await Promise.all(J.map(async(H)=>{let[Q,Z]=await Promise.all([Yf.getProvider(H),Yf.getModelsForProvider(H)]),j=iP(Z),X=$.providers[H]?.settings,A=Q?.name??pP(H);return{id:H,name:A,models:j.length,color:Ah(H),letter:Xh(A),enabled:Boolean(X),apiKey:X?Zh(X):void 0,oauthAccessTokenPresent:X?jh(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 lH(f,$){let J=f.trim(),W=await Ph(J,$),H=iP(W);return{providerId:J,models:H}}function pH(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 iH(f,$){let J=$.trim(),W=f.getProviderSettings(J),Q=Yf.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,Z=W?.baseUrl?.trim()||Q?.baseUrl?.trim(),j=z6(Z,Q?.baseUrl,Q?.modelsSourceUrl);if(!W||!Q||!Z||!j)return{providerId:J,refreshed:!1};let X=await aJ(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 nH(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 Bh(f,$){if(f==="cline")return $.access.startsWith("workos:")?$.access:`workos:${$.access}`;return $.access}async function aH(f,$,J){let W=h8({onPrompt:async(H)=>H.defaultValue??"",openUrl:J,onOpenUrlError:({error:H})=>{throw H instanceof Error?H:Error(String(H))}});if(f==="cline")return x1({apiBaseUrl:$?.baseUrl?.trim()||Hh().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:W});if(f==="oca")return b1({mode:$?.oca?.mode,callbacks:W});return g1(W)}function tH(f,$,J,W){let H={...J?.auth??{},accessToken:Bh($,W),refreshToken:W.refresh,accountId:W.accountId,expiresAt:W.expires},Q={...J??{provider:$},provider:$,auth:H};return f.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function sH(f){let $=f?.auth?.accessToken?.trim()||f?.apiKey?.trim();return $&&$.length>0?$:void 0}var Yh=new Set(["ollama","lmstudio","litellm"]);function Vh(f,$){if(!$?.provider.baseUrl)return!1;if($.provider.source!=="system")return!0;return Yh.has(f)}function oH(f){let $=Yf.normalizeProviderId(f);if(Qh($))return{providerId:$,authMethod:"oauth",fields:{}};let J=Yf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=J?.provider.baseUrl,H={apiKey:{}};if(Vh($,J))H.baseUrl={defaultValue:W};return{providerId:$,authMethod:"api-key",fields:H}}var JB={};N(JB,{resolveLegacyClineAuth:()=>$B,migrateLegacyProviderSettings:()=>q4});import{existsSync as Rh,readFileSync as Fh}from"node:fs";import{dirname as Kh,join as eH}from"node:path";import*as eP from"@cline/llms";import{resolveClineDataDir as yh}from"@cline/shared/storage";var fB="openai";function $B(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 oP(f){if(!Rh(f))return;try{let $=Fh(f,"utf8"),J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function Uh(f){let $=f.dataDir??yh(),J=f.globalStatePath??eH($,"globalState.json"),W=f.secretsPath??eH($,"secrets.json"),H=oP(J),Q=oP(W);if(!H&&!Q)return;return{globalState:H??{},secrets:Q??{}}}function Gh(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 Th(f){let $=E(f.openAiBaseUrl);if(!$)return!1;if(f.azureApiVersion||f.azureIdentity)return!1;return!Gh($)}function f3(f,$){if(f==="openai"&&Th($))return fB;return f}function Dh(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 _h(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 Mh(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 Lh(f){let $=eP.getGeneratedModelsForProvider(f);return Object.keys($)[0]??void 0}function hh(f,$,J,W){let H=f3(f,$),Q=E(W==="plan"?$.planModeApiProvider:$.actModeApiProvider),Z=Dh($,f,W,Q)??Lh(H),j=_h($,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,Mh(J));if(f==="cline")try{let F=E(J["cline:clineAccountId"]);if(F)P.auth={...P.auth??{},...$B(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=G8.safeParse(R);if(!U.success)return;return Object.keys(R).filter((F)=>F!=="provider").length>0?U.data:void 0}function Oh(f,$){if(f!==fB)return;if(!$.baseUrl||!$.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:$.baseUrl,defaultModelId:$.model},models:{[$.model]:{id:$.model,name:$.model}}}}function zh(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 q4(f){let $=f.providerSettingsManager.read(),J=Uh(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=zh(W,H),j=e0();j.providers={...$.providers},j.lastUsedProvider=$.lastUsedProvider;let X=new Date().toISOString(),A=0,P=eH(Kh(f.providerSettingsManager.getFilePath()),"models.json"),B=vH(P),Y=0;for(let U of Z){let K=f3(U,W);if(j.providers[K])continue;let F=hh(U,W,H,Q);if(!F)continue;j.providers[K]={settings:F,updatedAt:X,tokenSource:"migration"},A+=1;let y=Oh(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?f3(V,W):void 0;if(j.lastUsedProvider=$.lastUsedProvider??(R&&j.providers[R]?R:Object.keys(j.providers)[0]),f.providerSettingsManager.write(j),Y>0)gP(P,B);return{migrated:A>0||Y>0,providerCount:Object.keys(j.providers).length,lastUsedProvider:j.lastUsedProvider}}Lf();CJ();var WB={};N(WB,{FileTeamPersistenceStore:()=>sJ});import{appendFileSync as Nh,existsSync as $3,mkdirSync as qh,readFileSync as wh,renameSync as bh,unlinkSync as Ch,writeFileSync as Eh}from"node:fs";import{join as J3}from"node:path";import{resolveTeamDataDir as Sh}from"@cline/shared/storage";function kh(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class sJ{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor(f){let $=kh(f.teamName),J=f.baseDir?.trim()||Sh();this.dirPath=J3(J,$),this.statePath=J3(this.dirPath,"state.json"),this.taskHistoryPath=J3(this.dirPath,"task-history.jsonl")}loadState(){if(!$3(this.statePath))return;try{let f=wh(this.statePath,"utf8"),$=JSON.parse(f);if($.version!==1||!$.teamState)return;for(let J of $.teammates??[])this.teammateSpecs.set(J.agentId,J);return fA($.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`;Eh(J,`${JSON.stringify($,null,2)}
|
|
714
|
+
`,"utf8"),bh(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(),Nh(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:f.type,task:$})}
|
|
715
|
+
`,"utf8")}ensureDir(){if(!$3(this.dirPath))qh(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($3(this.statePath))Ch(this.statePath)}}var HB={};N(HB,{ChatViewStateSchema:()=>W3,ChatSummarySchema:()=>J5,ChatSessionStatusSchema:()=>eJ,ChatSessionConfigSchema:()=>oJ,ChatMessageSchema:()=>$5,ChatMessageRoleSchema:()=>f5});import{z as w}from"zod";var oJ=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()}),eJ=w.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),f5=w.enum(["user","assistant","tool","system","status","error"]),$5=w.object({id:w.string().min(1),sessionId:w.string().nullable(),role:f5,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()}),J5=w.object({toolCalls:w.number().int().nonnegative(),tokensIn:w.number().int().nonnegative(),tokensOut:w.number().int().nonnegative()}),W3=w.object({sessionId:w.string().nullable(),status:eJ,config:oJ,messages:w.array($5),rawTranscript:w.string(),error:w.string().nullable(),summary:J5});var QB={};N(QB,{CORE_BUILD_VERSION:()=>H3});var H3=QX;import{Agent as VO,createAgentRuntime as RO}from"@cline/agents";var jB={};N(jB,{fetchClineRecommendedModels:()=>Q3,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>W5});import{getClineEnvironmentConfig as Ih}from"@cline/shared";var mh=5000,W5={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 xh(f){return{recommended:f.recommended.map(($)=>({...$,tags:[...$.tags]})),free:f.free.map(($)=>({...$,tags:[...$.tags]}))}}function ZB(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 gh(f){if(!f||typeof f!=="object")return null;let $=f,J=Array.isArray($.recommended)?$.recommended:[],W=Array.isArray($.free)?$.free:[],H=J.map(ZB).filter((Z)=>Z!==null),Q=W.map(ZB).filter((Z)=>Z!==null);if(H.length===0&&Q.length===0)return null;return{recommended:H,free:Q}}function vh(f){let $=f.baseUrl?.trim();if($)return $;let J=Ih().apiBaseUrl;try{return(f.providerSettingsManager??new A0).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function uh(f,$,J){let W=new AbortController,H=setTimeout(()=>W.abort(),J);try{return await f($,{signal:W.signal})}finally{clearTimeout(H)}}async function Q3(f={}){try{let $=vh(f),J=f.fetchImpl??fetch,W=await uh(J,`${$}/api/v1/ai/cline/recommended-models`,f.timeoutMs??mh);if(!W.ok)throw Error(`HTTP ${W.status}`);let H=await W.json(),Q=gh(H);if(Q)return Q}catch{}return xh(W5)}var XB={};N(XB,{loadLlmsConfigFromFile:()=>j3,defineLlmsConfig:()=>Z3});import{readFile as ch}from"node:fs/promises";import dh from"node:path";function Z3(f){return f}async function j3(f){let $=dh.resolve(f),J=await ch($,"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 rh(W,$)}function rh(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 RB={};N(RB,{createLlmsSdk:()=>A3,DefaultLlmsSdk:()=>w4});import{BUILT_IN_PROVIDER_IDS as BB,createHandler as ih,createHandlerAsync as nh,getProviderCollection as ah,hasProvider as YB,registerAsyncHandler as th,registerHandler as sh,registerModel as oh,registerProvider as VB}from"@cline/llms";function AB(f){return f?{...f}:{}}function lh(f,$){if(f)return f;if(!$)return;let J=globalThis.process;if(!J?.env)return;return J.env[$]}function ph(f,$){if(!$.length)throw Error(`Provider "${f}" must include at least one model.`)}function PB(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 X3{providers=new Map;register(f){ph(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??{},...AB(f.defaults)}})}registerSelectionConfig(f){this.register({id:f.id,models:f.models,defaultModel:f.defaultModel,defaults:{apiKey:lh(f.apiKey,f.apiKeyEnv),routingProviderId:f.builtinProviderId,baseUrl:f.baseUrl,headers:f.headers,timeoutMs:f.timeoutMs,capabilities:f.capabilities,...AB(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 w4{configuredProviders=new X3;constructor(f){this.applyConfig(f)}createHandler(f){return ih(this.configuredProviders.createHandlerConfig(f))}async createHandlerAsync(f){return nh(this.configuredProviders.createHandlerConfig(f))}registerProvider(f){if(VB(f.collection),f.handlerFactory&&f.asyncHandlerFactory)throw Error(`Provider "${f.collection.provider.id}" cannot register both sync and async handlers.`);if(f.handlerFactory)sh(f.collection.provider.id,f.handlerFactory);if(f.asyncHandlerFactory)th(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.`);VB({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){oh(f.providerId,f.modelId,f.info),this.configuredProviders.registerModel(f.providerId,f.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...BB]}async getBuiltInProviders(){return(await Promise.all(BB.map(($)=>ah($)))).filter(($)=>$!==void 0).map(($)=>PB({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=YB($.id),W=this.configuredProviders.createHandlerConfig({providerId:$.id,modelId:$.defaultModel}).routingProviderId,H=typeof W==="string"&&YB(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 A3(f){return new w4(f)}jH();async function eh(){return Promise.resolve().then(() => (zH(),MP))}function GO(){return new Date().toISOString()}function TO(f){if(UB(f)!=="providers.json")return;let $=B3(f);if(UB($)!=="settings")return;return B3($)}class A0{filePath;dataDir;constructor(f={}){if(this.filePath=f.filePath??UO(),this.dataDir=f.dataDir??TO(this.filePath),this.dataDir||!f.filePath)q4({providerSettingsManager:this,dataDir:this.dataDir});if(lP(this),iJ(this.read()),P3(this.filePath))try{yB(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!P3(this.filePath))return e0();try{let f=KO(this.filePath,"utf8"),$=JSON.parse(f),J=S1.safeParse($);if(J.success)return iJ(J.data),J.data}catch{}return e0()}write(f){let $=S1.parse(f),J=B3(this.filePath);if(!P3(J))FO(J,{recursive:!0,mode:448});yO(this.filePath,`${JSON.stringify($,null,2)}
|
|
716
|
+
`,"utf8");try{yB(this.filePath,384)}catch{}iJ($)}saveProviderSettings(f,$={}){let J=G8.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:GO(),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 kf(J,$)}getLastUsedProviderConfig(f){let $=this.getLastUsedProviderSettings();if(!$)return;return kf($,f)}async refreshCatalog(){try{await C1({})}catch{}}}Lf();_J();import{getClineEnvironmentConfig as DO,isOAuthProviderId as _O}from"@cline/shared";var Y3="workos:";function MO(f,$){if(f==="cline")return`${Y3}${$}`;return $}function LO(f,$){if(f==="cline"&&$.toLowerCase().startsWith(Y3))return $.slice(Y3.length);return $}function hO(f){let J=Rf(f)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function OO(f,$){let J=f.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let W=hO($);if(W)return W;return Date.now()-1}function zO(f,$){let J=$.auth?.accessToken?.trim(),W=$.auth?.refreshToken?.trim();if(!J||!W)return null;let H=LO(f,J);if(!H)return null;return{access:H,refresh:W,expires:OO($,H),accountId:$.auth?.accountId}}function NO(f,$){let J=f?.expiresAt,W=$?.expiresAt;return f?.accessToken===$?.accessToken&&f?.refreshToken===$?.refreshToken&&f?.accountId===$?.accountId&&J===W}class H5 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 V3{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor(f){this.providerSettingsManager=f?.providerSettingsManager??new A0,this.telemetry=f?.telemetry}async resolveProviderApiKey(f){if(!_O(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=zO(f,J);if(!W)return null;let H=await this.resolveCredentials(f,J,W,$);if(!H)throw new H5(f);let Q=MO(f,H.access),Z={...J.auth??{},accessToken:Q,refreshToken:H.refresh,accountId:H.accountId};Z.expiresAt=H.expires;let j={...J,auth:Z},X=!NO(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 z8(J,{apiBaseUrl:$.baseUrl?.trim()||DO().apiBaseUrl,telemetry:this.telemetry},{forceRefresh:W});if(f==="oca")return Y8(J,{forceRefresh:W,telemetry:this.telemetry},{mode:$.oca?.mode,telemetry:this.telemetry});return q8(J,{forceRefresh:W,telemetry:this.telemetry})}}import{normalizeUserInput as qO}from"@cline/shared";import{nanoid as wO}from"nanoid";class GB{list(f){return f?rf(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:rf(f),updated:!1};let H=f.pendingPrompts[W];if(!H)return{sessionId:$.sessionId,prompts:rf(f),updated:!1};let Q=$.prompt===void 0?H.prompt:qO($.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),bO(f,j,W,H.delivery),{sessionId:$.sessionId,prompts:rf(f),prompt:Q5(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:rf(f),removed:!1};let[H]=f.pendingPrompts.splice(W,1);return{sessionId:$.sessionId,prompts:rf(f),prompt:H?Q5(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()}_${wO(5)}`,prompt:J,delivery:W,userImages:H,userFiles:Q};if(W==="steer")f.pendingPrompts.unshift(j);else f.pendingPrompts.push(j)}return rf(f)}consumeSteer(f){let $=f.pendingPrompts.findIndex((W)=>W.delivery==="steer");if($<0)return{prompts:rf(f)};let[J]=f.pendingPrompts.splice($,1);return{entry:J,prompts:rf(f)}}shiftNext(f){return{entry:f.pendingPrompts.shift(),prompts:rf(f)}}requeueFront(f,$){return f.pendingPrompts.unshift($),rf(f)}clear(f){return f.pendingPrompts.length=0,[]}}class R3{deps;service=new GB;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:rf(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=Q5($);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:f.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function Q5(f){return{id:f.id,prompt:f.prompt,delivery:f.delivery,attachmentCount:(f.userImages?.length??0)+(f.userFiles?.length??0)}}function rf(f){return f.pendingPrompts.map(Q5)}function bO(f,$,J,W){if($.delivery==="steer")f.pendingPrompts.unshift($);else if(W==="steer")f.pendingPrompts.push($);else f.pendingPrompts.splice(J,0,$)}Lf();class K3{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=a5(J),Z=!!W&&(!Q.agentId||Q.agentId===F3(W.agent));t5(H,J,Z?{isPrimaryAgentEvent:!0,agentId:F3(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(r9(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};t5(W,$.event,{agentId:$.agentId,teamRole:"teammate",teamAgentId:$.agentId,isPrimaryAgentEvent:!1})}if($.type==="teammate_spawned"){let W=_0({agentId:$.teammate.runtimeAgentId??$.agentId,conversationId:$.teammate.conversationId,parentAgentId:$.teammate.parentAgentId,createdByAgentId:F3(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:$.agentId});if(W)p0(J.config.telemetry,{ulid:f,modelId:$.teammate.modelId??J.config.modelId,provider:J.config.providerId,...W})}}if(await l9(f,$,this.deps.invokeBackendOptional),J)p9(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 F3(f){return f.getAgentId()}function y3(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:i0(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 U3(f,$){let J=f[$];return typeof J==="function"?J:null}async function TB(f,$,...J){let W=U3(f,$);if(!W)throw Error(`session service method not available: ${$}`);return Promise.resolve(W.apply(f,J))}async function DB(f,$,...J){let W=U3(f,$);if(!W)return;await Promise.resolve(W.apply(f,J))}async function _B(f,$,...J){let W=U3(f,$);if(!W)return;return await Promise.resolve(W.apply(f,J))}M0();Lf();function G3(f,$,J,W){return d0({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?L$({cwd:$.cwd,...Ef[K0({mode:$.mode})],executors:W}):[];if($.enableSpawnAgent)Q.push(G3(f,$,J,W));return w$(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=_0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)p0($.telemetry,{ulid:J,modelId:$.modelId,provider:$.providerId,...j});t2($.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(`
|
|
717
|
+
`).length:0;t2($.telemetry,{event:"ended",ulid:J,durationMs:X,outputLines:A,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,..._0({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 CO,stat as EO}from"node:fs/promises";var SO=20480000;async function MB(f){let $=await EO(f);if(!$.isFile())throw Error("Path is not a file");if($.size>SO)throw Error("File is too large to read into context.");let J=await CO(f,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var LB=5000;function b4(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function cO(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=b4($.inputTokens),W=b4($.outputTokens),H=b4($.cacheReadTokens),Q=b4($.cacheWriteTokens),Z=b4($.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 dO(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 f4;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new Y$;constructor(f){let $=IO();if($)uO($);let J=l$(f.distinctId);this.sessionService=f.sessionService,this.runtimeBuilder=f.runtimeBuilder??new F2,this.createAgentInstance=f.createAgent??((W)=>new c0(W)),this.defaultCapabilities=Kf(f.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=f.toolPolicies,this.providerSettingsManager=f.providerSettingsManager??new A0,this.oauthTokenManager=f.oauthTokenManager??new V3({providerSettingsManager:this.providerSettingsManager,telemetry:f.telemetry}),this.defaultTelemetry=f.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=f.fetch,this.pendingPromptsController=new R3({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 K3({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??Vf.CLI,J=s(),W=f.config.sessionId?.trim()??"",H=W||xO(),Q=f,Z=Q.initialMessages??[],j=Z.length>0?G1(Z):Pf(),X=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!X)throw Error("session service method not available: ensureSessionsDir");let A=T3(X,H),P=T3(A,`${H}.messages.json`),B=T3(A,`${H}.json`),Y=i0(f.config),V=Mf.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=Kf(this.defaultCapabilities,f.capabilities),y=F?.toolExecutors??this.toolExecutors,D=f.localRuntime,M=D?.extensionContext?.logger??D?.logger,T=D?.extensionContext?.automation,_;_=await mZ({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:()=>G3({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:M2(q),tools:Hf,hooks:_.hooks,extensions:o,hookErrorMode:q.hookErrorMode,initialMessages:_.effectiveInput.initialMessages,userFileContentLoader:MB,toolPolicies:_.toolPolicies,requestToolApproval:_.requestToolApproval,onConsecutiveMistakeLimitReached:q.onConsecutiveMistakeLimitReached,completionPolicy:L.completionPolicy,consumePendingUserMessage:()=>{let S=this.pendingPromptsController.consumeSteer(H);return S?P4(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=_0({agentId:Gf.getAgentId(),conversationId:Gf.getConversationId(),teamId:L.teamRuntime?.getTeamId(),teamName:L.teamRuntime?.getTeamName(),teamRole:L.teamRuntime?"lead":void 0});if(gZ(q,H,W.length>0,Y,E0),E0)p0(q.telemetry,{ulid:H,modelId:q.modelId,provider:q.providerId,...E0});if(L.teamRuntime)j6(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 $=U9(this.usageBySession.get(f)),J=U9(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 y3($);let J=f.trim();if(!J)return;let W=await this.getRow(J);if(W)return p2(W);let H=await this.readManifest(J);return H?YJ(H):void 0}async listSessions(f=200){let J=(await this.listRows(f)).map(p2),W=new Set(J.map((H)=>H.sessionId));for(let H of this.sessions.values()){if(W.has(H.sessionId))continue;J.unshift(y3(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 Q$(J.messagesPath);let W=await this.readManifest($);return Q$(W?.messages_path)}async dispatchHookEvent(f){await sj(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(i9(f,H.finishReason)){let Q=await n9(f);if(Q.length===0)break;let Z=a9(f,Q);H=await this.executeAgentTurn(f,Z)}return H}async completeInteractiveTurn(f,$){if(A4(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,f6(f.config.telemetry,f.sessionId,f.config.mode),y1(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=i4(A.messages,A,Q);f.persistedMessages=P;let B=s2(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,n2(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=i0(f.config),W=vO($.prompt).trim();if(!W)return{prompt:"",userImages:$.userImages,userFiles:this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles)};let H=await Z1(W,J);vZ(f.config.telemetry,H);let Q=P4(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 $=i0(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(A4(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)n2(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)});LJ(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(!gO(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 H5)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)=>mO(W)?W:D3(f,W));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity(f){return _0({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=D3($),H=`${J}.messages.json`,Q;try{Q=kO(f)}catch{return Pf()}let Z=Pf();for(let j of Q){if(!j.endsWith(".messages.json"))continue;if(j===H)continue;let X=D3(f,j);if(X===W)continue;let A=await Q$(X);if(A.length===0)continue;Z=Xf(Z,G1(A))}return Z}withPersistedAggregateUsageFloor(f,$){let J=cO($.metadata?.aggregateUsage);if(J)return dO(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)),LB))}async getRow(f){let $=f.trim();if(!$)return;return(await this.listRows(LB)).find((W)=>W.sessionId===$)}async readManifest(f){let $=f.trim();if(!$)return;return await this.invokeOptionalValue("readSessionManifest",$)}invoke(f,...$){return TB(this.sessionService,f,...$)}invokeOptional(f,...$){return DB(this.sessionService,f,...$)}invokeOptionalValue(f,...$){return _B(this.sessionService,f,...$)}}function lO(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 pO(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}function gJ(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()||Vf.CLI,interactive:!1,config:{providerId:rO(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:pO(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:lO(H)}},async abortSession(J){return await $.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}iO(process.env.CLINE_VCR);function nO(f){let $=process.cwd(),J,W,H;for(let Q=0;Q<f.length;Q+=1){let Z=f[Q],j=f[Q+1];if(Z==="--cwd"&&j){$=j,Q+=1;continue}if(Z==="--host"&&j){J=j,Q+=1;continue}if(Z==="--port"&&j){let X=Number(j);if(Number.isFinite(X))W=X;Q+=1;continue}if(Z==="--pathname"&&j)H=j,Q+=1}return{cwd:$,host:J,port:W,pathname:H}}async function aO(){let f=nO(process.argv.slice(2));process.chdir(f.cwd);let $=gf({host:f.host,port:f.port,pathname:f.pathname}),J=await o$({host:$.host,port:$.port,pathname:$.pathname,owner:Af(),runtimeHandlers:gJ(),cronOptions:{workspaceRoot:f.cwd}}),W=async()=>{await J.close(),process.exit(0)},H=!1,Q=(Z,j)=>{if(H)return;H=!0;let X=j instanceof Error?j.stack||j.message:String(j);process.stderr.write(`[hub-daemon] ${Z}: ${X}
|
|
718
|
+
`),J.close().catch((A)=>{let P=A instanceof Error?A.stack||A.message:String(A);process.stderr.write(`[hub-daemon] shutdown after ${Z} failed: ${P}
|
|
719
|
+
`)}).finally(()=>{process.exit(1)})};process.on("SIGINT",()=>{W()}),process.on("SIGTERM",()=>{W()}),process.on("uncaughtException",(Z)=>{Q("uncaughtException",Z)}),process.on("unhandledRejection",(Z)=>{Q("unhandledRejection",Z)}),await new Promise(()=>{})}aO().catch((f)=>{let $=f instanceof Error?f.stack||f.message:String(f);process.stderr.write(`[hub-daemon] fatal: ${$}
|
|
720
720
|
`),process.exit(1)});
|