@cline/core 0.0.42 → 0.0.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cron/service/schedule-service.d.ts +1 -0
- package/dist/extensions/config/user-instruction-config-loader.d.ts +4 -0
- package/dist/extensions/index.d.ts +1 -1
- package/dist/extensions/plugin/plugin-config-loader.d.ts +3 -0
- package/dist/extensions/plugin/plugin-loader.d.ts +1 -0
- package/dist/extensions/plugin/plugin-sandbox.d.ts +7 -0
- package/dist/extensions/plugin-sandbox-bootstrap.js +1 -1
- package/dist/extensions/tools/helpers.d.ts +4 -1
- package/dist/extensions/tools/schemas.d.ts +8 -0
- package/dist/hub/daemon/entry.js +164 -163
- package/dist/hub/discovery/index.d.ts +1 -0
- package/dist/hub/index.js +163 -163
- package/dist/index.d.ts +4 -2
- package/dist/index.js +163 -163
- package/dist/runtime/host/runtime-host.d.ts +7 -0
- package/dist/runtime/orchestration/session-runtime.d.ts +1 -0
- package/dist/services/llms/apihandler-agent-model-adapter.d.ts +26 -0
- package/dist/services/plugin-uninstall.d.ts +13 -0
- package/dist/services/providers/provider-config-fields.d.ts +1 -1
- package/dist/services/telemetry/core-events.d.ts +18 -0
- package/dist/services/telemetry/index.js +1 -1
- package/dist/services/telemetry/tool-context.d.ts +3 -0
- package/dist/types.d.ts +1 -1
- package/package.json +4 -4
package/dist/hub/index.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`,"utf8"),_G()}function Ff(){return e0().telemetryOptOut}function C3($,f={}){D2({...e0(),telemetryOptOut:$},f)}function $$($){return new Set($??e0().disabledTools??[])}function c8($){return new Set($??e0().disabledPlugins??[])}function E3($){return $$().has($)}function Pf($){let f=e0(),J=new Set(f.disabledTools??[]),Q=J.has($);if(Q)J.delete($);else J.add($);return D2({...f,disabledTools:[...J]}),!Q}function o5($,f){let J=[...new Set($.map((W)=>W.trim()).filter(Boolean))];if(J.length===0)return;let Q=e0(),Z=$$(Q.disabledTools);for(let W of J)if(f)Z.add(W);else Z.delete(W);D2({...Q,disabledTools:[...Z]})}function b3($,f){return o5([$],f),f}function k3($){return c8().has($)}function I3($,f){let J=$.trim();if(!J)return;let Q=e0(),Z=c8(Q.disabledPlugins);if(f)Z.add(J);else Z.delete(J);D2({...Q,disabledPlugins:[...Z]})}function Uf($,f){let J=c8(f);if(J.size===0)return[...$];return $.filter((Q)=>!J.has(Q))}function O1($,f){let J=$$(f);if(J.size===0)return[...$];return $.filter((Q)=>!J.has(Q.name))}function Df($,f){if(!$||$.length===0)return $;let J=$$(f);if(J.size===0)return $;return $.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(Z,W)=>Q.setup?.({...Z,registerTool:(j)=>{if(!J.has(j.name))Z.registerTool(j)}},W)}})}var S3,u8,Kf;var O$=U1(()=>{L0();S3=v8.preprocess(($)=>Array.isArray($)?$.filter((f)=>typeof f==="string").map((f)=>f.trim()).filter(Boolean):void 0,v8.array(v8.string()).optional()).transform(($)=>{if(!$)return;let f=[...new Set($)].sort((J,Q)=>J.localeCompare(Q));return f.length>0?f:void 0}),u8=v8.object({telemetryOptOut:v8.boolean().default(!1).catch(!1),disabledTools:S3.optional(),disabledPlugins:S3.optional()}).strip().transform(($)=>{let f={telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)f.disabledTools=$.disabledTools;if($.disabledPlugins?.length)f.disabledPlugins=$.disabledPlugins;return f})});import{existsSync as qG,mkdirSync as yG,readFileSync as wG,writeFileSync as SG}from"node:fs";import{resolve as hG}from"node:path";import{resolveSessionDataDir as CG}from"@cline/shared/storage";import{nanoid as EG}from"nanoid";import*as bG from"node-machine-id";function z1($){let f=$?.trim();if(f)return f;let J=xG();if(J)return J;return mG()}function IG(){let $=bG;return $.machineIdSync??$.default?.machineIdSync}function xG(){try{let $=IG();if(!$)return;return $().trim()||void 0}catch{return}}function mG(){let $=CG(),f=hG($,kG);try{if(qG(f)){let Q=wG(f,"utf8").trim();if(Q.length>0)return Q}}catch{}let J=`cl-${EG()}`;try{yG($,{recursive:!0}),SG(f,J,"utf8")}catch{}return J}var kG="machine-id";var Rf=()=>{};class l8{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,f){if(!this.isEnabled())return;this.emitLog($,f,!1)}emitRequired($,f){this.emitLog($,f,!0)}recordCounter($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.counters.get($);if(!W)W=this.meter.createCounter($,Q?{description:Q}:void 0),this.counters.set($,W);W.add(f,this.flattenProperties(this.buildAttributes(J)))}recordHistogram($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.histograms.get($);if(!W)W=this.meter.createHistogram($,Q?{description:Q}:void 0),this.histograms.set($,W);W.record(f,this.flattenProperties(this.buildAttributes(J)))}recordGauge($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.buildAttributes(J),j=JSON.stringify(W),X=this.gaugeValues.get($);if(f===null){if(X){if(X.delete(j),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let H=X;if(!H)H=new Map,this.gaugeValues.set($,H);if(!this.gauges.has($)){let Y=this.meter.createObservableGauge($,Q?{description:Q}:void 0);Y.addCallback((V)=>{for(let A of this.snapshotGaugeSeries($))V.observe(A.value,this.flattenProperties(A.attributes))}),this.gauges.set($,Y)}H.set(j,{value:f,attributes:W})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,f,J){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes(f,J));this.logger.emit({severityText:"INFO",body:$,attributes:Q})}buildAttributes($,f=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...f?{_required:!0}:{}}}snapshotGaugeSeries($){let f=this.gaugeValues.get($);if(!f)return[];return Array.from(f.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties($,f="",J=new WeakSet,Q=0){if(!$)return{};let Z={},W=100,j=10;for(let[X,H]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let Y=f?`${f}.${X}`:X;if(H===null||H===void 0){Z[Y]=String(H);continue}if(Array.isArray(H)){let V=H.length>W?H.slice(0,W):H;try{Z[Y]=JSON.stringify(V)}catch{Z[Y]="[UnserializableArray]"}if(H.length>W)Z[`${Y}_truncated`]=!0,Z[`${Y}_original_length`]=H.length;continue}if(typeof H==="object"){if(H instanceof Date){Z[Y]=H.toISOString();continue}if(H instanceof Error){Z[Y]=H.message;continue}if(J.has(H)){Z[Y]="[Circular]";continue}if(Q>=j){Z[Y]="[MaxDepthExceeded]";continue}J.add(H),Object.assign(Z,this.flattenProperties(H,Y,J,Q+1));continue}if(gG(H)){Z[Y]=H;continue}try{Z[Y]=JSON.stringify(H)}catch{Z[Y]=String(H)}}return Z}}function gG($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class p8{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,f){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:f})}emitRequired($,f){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:f})}recordCounter($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:f,attributes:J,description:Q,required:Z===!0})}recordHistogram($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:f,attributes:J,description:Q,required:Z===!0})}recordGauge($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:f,attributes:J,description:Q,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class R2{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new p8({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let f=this.buildAttributes($.properties);for(let J of this.adapters)J.emit($.event,f)}captureRequired($,f){let J=this.buildAttributes(f);for(let Q of this.adapters)Q.emitRequired($,J)}recordCounter($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter($,f,W,Q,Z)}recordHistogram($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram($,f,W,Q,Z)}recordGauge($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge($,f,W,Q,Z)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var e5=()=>{};import{metrics as vG,trace as uG}from"@opentelemetry/api";import{logs as cG}from"@opentelemetry/api-logs";import{OTLPLogExporter as dG}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as lG}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as pG}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as rG}from"@opentelemetry/resources";import{BatchLogRecordProcessor as iG,ConsoleLogRecordExporter as nG,LoggerProvider as aG}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as tG,MeterProvider as sG,PeriodicExportingMetricReader as x3}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as oG,ConsoleSpanExporter as eG,SimpleSpanProcessor as $K}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as fK}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as JK,ATTR_SERVICE_VERSION as QK}from"@opentelemetry/semantic-conventions";class m3{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,f){this.resolveProperties(f)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class L2{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let f=rG({[JK]:$.serviceName??"cline",...$.serviceVersion?{[QK]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(f),this.loggerProvider=this.createLoggerProvider(f),this.tracerProvider=this.createTracerProvider(f),this.meterProvider)vG.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)cG.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",f){return uG.getTracer($,f??this.options.serviceVersion)}createAdapter($){return new l8({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let f=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new R2({...$,adapters:[f],distinctId:z1($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let f=$9(this.options.metricsExporter);if(f.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(J*0.8)),Z=f.map((W)=>jK(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:Q})).filter((W)=>W!==null);if(Z.length===0)return null;return new sG({resource:$,readers:Z})}createTracerProvider($){let f=$9(this.options.tracesExporter);if(f.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let W of f){let j=WK(W,{endpoint:J,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(j)Z.push(j)}if(Z.length===0)return null;return new fK({resource:$,spanProcessors:Z})}createLoggerProvider($){let f=$9(this.options.logsExporter);if(f.length===0)return null;let J=f.map((Q)=>{let Z=ZK(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new iG(Z,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(J.length===0)return null;return new aG({resource:$,processors:J})}}function r8($){let f=new L2($),J=f.createTelemetryService($);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:f,telemetry:J}}function z$($){if(Ff())return{telemetry:new m3($)};if($.enabled!==!0)return{telemetry:new R2({...$,distinctId:z1($.distinctId)})};return r8($)}function O2($){let{telemetry:f,provider:J}=z$($);return{telemetry:f,provider:J,flush:async()=>{let W=J;if(W&&typeof W.forceFlush==="function")try{await W.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([f.dispose(),J?.dispose()])}}}function $9($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function ZK($,f){if($==="console")return new nG;if(!f.endpoint)return null;let J=f9(f.endpoint,"/v1/logs");return new dG({url:J,headers:f.headers})}function WK($,f){if($==="console")return new $K(new eG);if(!f.endpoint)return null;let J=f9(f.endpoint,"/v1/traces");return new oG(new pG({url:J,headers:f.headers}))}function jK($,f){if($==="console")return new x3({exporter:new tG,exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout});if(!f.endpoint)return null;let J=f9(f.endpoint,"/v1/metrics");return new x3({exporter:new lG({url:J,headers:f.headers}),exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout})}function f9($,f){let J=new URL($),Q=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=Q.endsWith(f)?Q:`${Q}${f}`,J.toString()}var Lf=U1(()=>{O$();Rf();e5()});var Lj={};y(Lj,{normalizeUserMessage:()=>OU,buildInitialUserContent:()=>LU});async function LU($,f,J,Q){let Z=zU(f),W=await NU(J,Q);if(Z.length===0&&!W)return $;let j=[{type:"text",text:$},...Z];if(W)j.push(...W);return j}function OU($){if($==null)return"";if(typeof $==="string")return $;let f=$.content;if(typeof f==="string")return f;if(!Array.isArray(f))return"";let J=[];for(let Q of f)if(Q&&typeof Q==="object"&&Q.type==="text"){let Z=Q.text;if(typeof Z==="string")J.push(Z)}return J.join(`
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function
|
|
5
|
-
`,"utf8"),
|
|
1
|
+
import{createRequire as yK}from"node:module";var{defineProperty:BW,getOwnPropertyNames:TK}=Object;var v7=Object.prototype.hasOwnProperty;function u7($){return this[$]}var M=($,f,J)=>{var W=TK(f);for(let Z of W)if(!v7.call($,Z)&&Z!=="default")BW($,Z,{get:u7.bind(f,Z),enumerable:!0});if(J){for(let Z of W)if(!v7.call(J,Z)&&Z!=="default")BW(J,Z,{get:u7.bind(f,Z),enumerable:!0});return J}};var NK=($)=>$;function MK($,f){this[$]=NK.bind(null,f)}var w=($,f)=>{for(var J in f)BW($,J,{get:f[J],enumerable:!0,configurable:!0,set:MK.bind(f,J)})};var M1=($,f)=>()=>($&&(f=$($=0)),f);var c7=yK(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as AG}from"@cline/shared";function d($,f,J){$?.capture({event:f,properties:J})}function G4($){if(!$)return;return $.substring(0,VG)}function BG($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function KG($){return typeof $==="string"?$:$.message}function H3($,f){return $.some((J)=>f.has(J.trim().toLowerCase()))}function X3($){d($,x.CLIENT.EXTENSION_ACTIVATED)}function P4($,f){let J=[...f.vcs_types],W={root_count:f.root_count,vcs_types:J,is_multi_root:f.root_count>1,has_git:H3(J,new Set(["git"])),has_mercurial:H3(J,new Set(["mercurial","hg"]))};if(f.init_duration_ms!==void 0)W.init_duration_ms=f.init_duration_ms;if(f.feature_flag_enabled!==void 0)W.feature_flag_enabled=f.feature_flag_enabled;if(f.is_remote_workspace!==void 0)W.is_remote_workspace=f.is_remote_workspace;d($,x.WORKSPACE.INITIALIZED,W)}function F4($,f,J){d($,x.WORKSPACE.INIT_ERROR,{error_type:BG(f),error_message:G4(KG(f)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function Y3($,f){d($,x.WORKSPACE.PATH_RESOLVED,{...f})}function O$($,f){d($,x.USER.AUTH_STARTED,{provider:f})}function _$($,f){d($,x.USER.AUTH_SUCCEEDED,{provider:f})}function z$($,f,J){d($,x.USER.AUTH_FAILED,{provider:f,errorMessage:G4(J)})}function i$($,f,J){d($,x.USER.AUTH_LOGGED_OUT,{provider:f,reason:J})}function A3($,f){d($,x.USER.PROVIDER_CONFIGURED,{provider:f})}function V3($,f){$?.captureRequired(x.USER.TELEMETRY_OPT_OUT,f)}function T$($,f){let J=f.id?.trim();if(J)$?.setDistinctId(J);$?.updateCommonProperties({account_id:f.id,account_email:f.email,provider:f.provider,organization_id:f.organizationId,organization_name:f.organizationName,member_id:f.memberId})}function U4($,f){d($,x.TASK.CREATED,f)}function R4($,f){d($,x.TASK.RESTARTED,f)}function o2($,f){d($,x.TASK.COMPLETED,f)}function wf($,f){d($,x.TASK.CONVERSATION_TURN,{...f,timestamp:new Date().toISOString()})}function D4($,f){d($,x.TASK.TOKEN_USAGE,f)}function L4($,f,J){d($,x.TASK.MODE_SWITCH,{ulid:f,mode:J})}function O4($,f){d($,x.TASK.TOOL_USED,f)}function _4($,f){d($,x.TASK.SKILL_USED,f)}function z4($,f){d($,x.TASK.DIFF_EDIT_FAILED,f)}function e2($,f){d($,x.TASK.PROVIDER_API_ERROR,{...f,errorMessage:G4(f.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function B3($,f){d($,x.SDK.TOOL_TIMEOUT,GG(f))}function GG($){let f={};for(let[J,W]of Object.entries($))if(W!==void 0)f[J]=W;return f}function T4($,f,J){d($,x.TASK.MENTION_USED,{mentionType:f,contentLength:J,timestamp:new Date().toISOString()})}function N4($,f,J,W){d($,x.TASK.MENTION_FAILED,{mentionType:f,errorType:J,errorMessage:G4(W),timestamp:new Date().toISOString()})}function M4($,f,J,W,Z){d($,x.TASK.MENTION_SEARCH_RESULTS,{queryLength:f.length,resultCount:J,searchType:W,isEmpty:Z,timestamp:new Date().toISOString()})}function n$($,f){d($,x.TASK.AGENT_CREATED,{...f,timestamp:new Date().toISOString()})}function y4($,f){d($,x.TASK.AGENT_TEAM_CREATED,{...f,timestamp:new Date().toISOString()})}function $8($,f){d($,f.event==="ended"?x.TASK.SUBAGENT_COMPLETED:x.TASK.SUBAGENT_STARTED,{...f,timestamp:new Date().toISOString()})}function q4($,f,J,W){d($,x.HOOKS.DISCOVERY_COMPLETED,{hookName:f,globalCount:J,workspaceCount:W,totalCount:J+W,timestamp:new Date().toISOString()})}function w4($,f){d($,x.TASK.COMPACTION_EXECUTED,{...f,timestamp:new Date().toISOString()})}function S4($,f){d($,x.TASK.COMPACTION_SKIPPED,{...f,timestamp:new Date().toISOString()})}var VG=500,x;var L0=M1(()=>{x={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",PROVIDER_CONFIGURED:"user.provider_configured",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed",COMPACTION_EXECUTED:"task.compaction_executed",COMPACTION_SKIPPED:"task.compaction_skipped"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:AG,TOOL_TIMEOUT:"sdk.tool_timeout"}}});import{mkdirSync as PG,readFileSync as FG,statSync as UG,writeFileSync as RG}from"node:fs";import{dirname as DG}from"node:path";import{resolveGlobalSettingsPath as G3}from"@cline/shared/storage";import{z as f8}from"zod";function h4(){return J8.parse({})}function LG(){C4=void 0}function OG($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function _G($){let f;try{f=FG($,"utf8")}catch{return h4()}try{let J=J8.safeParse(JSON.parse(f));return J.success?J.data:h4()}catch{return h4()}}function zG(){let $=G3(),f=UG($,{throwIfNoEntry:!1}),J=f?.mtimeMs??0,W=f?.size??0,Z=C4;if(Z&&Z.path===$&&Z.mtimeMs===J&&Z.size===W)return Z;let Q=OG(f?_G($):h4());return C4={path:$,mtimeMs:J,size:W,value:Q},C4}function E0(){return zG().value}function a$($,f={}){let J=G3(),W=E0();PG(DG(J),{recursive:!0});let Z=J8.parse($);if(!W.telemetryOptOut&&Z.telemetryOptOut)V3(f.telemetry);RG(J,`${JSON.stringify(Z,null,2)}
|
|
2
|
+
`,"utf8"),LG()}function E4(){return E0().telemetryOptOut}function P3($,f={}){a$({...E0(),telemetryOptOut:$},f)}function W$($){return new Set($??E0().disabledTools??[])}function W8($){return new Set($??E0().disabledPlugins??[])}function F3($){return W$().has($)}function b4($){let f=E0(),J=new Set(f.disabledTools??[]),W=J.has($);if(W)J.delete($);else J.add($);return a$({...f,disabledTools:[...J]}),!W}function NW($,f){let J=[...new Set($.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let W=E0(),Z=W$(W.disabledTools);for(let Q of J)if(f)Z.add(Q);else Z.delete(Q);a$({...W,disabledTools:[...Z]})}function U3($,f){return NW([$],f),f}function R3($){return W8().has($)}function D3($,f){let J=$.trim();if(!J)return;let W=E0(),Z=W8(W.disabledPlugins);if(f)Z.add(J);else Z.delete(J);a$({...W,disabledPlugins:[...Z]})}function k4($,f){let J=W8(f);if(J.size===0)return[...$];return $.filter((W)=>!J.has(W))}function S1($,f){let J=W$(f);if(J.size===0)return[...$];return $.filter((W)=>!J.has(W.name))}function I4($,f){if(!$||$.length===0)return $;let J=W$(f);if(J.size===0)return $;return $.map((W)=>{if(!W.setup)return W;return{...W,setup:(Z,Q)=>W.setup?.({...Z,registerTool:(j)=>{if(!J.has(j.name))Z.registerTool(j)}},Q)}})}var K3,J8,C4;var Z$=M1(()=>{L0();K3=f8.preprocess(($)=>Array.isArray($)?$.filter((f)=>typeof f==="string").map((f)=>f.trim()).filter(Boolean):void 0,f8.array(f8.string()).optional()).transform(($)=>{if(!$)return;let f=[...new Set($)].sort((J,W)=>J.localeCompare(W));return f.length>0?f:void 0}),J8=f8.object({telemetryOptOut:f8.boolean().default(!1).catch(!1),disabledTools:K3.optional(),disabledPlugins:K3.optional()}).strip().transform(($)=>{let f={telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)f.disabledTools=$.disabledTools;if($.disabledPlugins?.length)f.disabledPlugins=$.disabledPlugins;return f})});import{existsSync as TG,mkdirSync as NG,readFileSync as MG,writeFileSync as yG}from"node:fs";import{resolve as qG}from"node:path";import{resolveSessionDataDir as wG}from"@cline/shared/storage";import{nanoid as SG}from"nanoid";import*as hG from"node-machine-id";function h1($){let f=$?.trim();if(f)return f;let J=bG();if(J)return J;return kG()}function EG(){let $=hG;return $.machineIdSync??$.default?.machineIdSync}function bG(){try{let $=EG();if(!$)return;return $().trim()||void 0}catch{return}}function kG(){let $=wG(),f=qG($,CG);try{if(TG(f)){let W=MG(f,"utf8").trim();if(W.length>0)return W}}catch{}let J=`cl-${SG()}`;try{NG($,{recursive:!0}),yG(f,J,"utf8")}catch{}return J}var CG="machine-id";var x4=()=>{};class Q8{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,f){if(!this.isEnabled())return;this.emitLog($,f,!1)}emitRequired($,f){this.emitLog($,f,!0)}recordCounter($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.counters.get($);if(!Q)Q=this.meter.createCounter($,W?{description:W}:void 0),this.counters.set($,Q);Q.add(f,this.flattenProperties(this.buildAttributes(J)))}recordHistogram($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.histograms.get($);if(!Q)Q=this.meter.createHistogram($,W?{description:W}:void 0),this.histograms.set($,Q);Q.record(f,this.flattenProperties(this.buildAttributes(J)))}recordGauge($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.buildAttributes(J),j=JSON.stringify(Q),H=this.gaugeValues.get($);if(f===null){if(H){if(H.delete(j),H.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let X=H;if(!X)X=new Map,this.gaugeValues.set($,X);if(!this.gauges.has($)){let Y=this.meter.createObservableGauge($,W?{description:W}:void 0);Y.addCallback((A)=>{for(let V of this.snapshotGaugeSeries($))A.observe(V.value,this.flattenProperties(V.attributes))}),this.gauges.set($,Y)}X.set(j,{value:f,attributes:Q})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,f,J){if(!this.logger)return;let W=this.flattenProperties(this.buildAttributes(f,J));this.logger.emit({severityText:"INFO",body:$,attributes:W})}buildAttributes($,f=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...f?{_required:!0}:{}}}snapshotGaugeSeries($){let f=this.gaugeValues.get($);if(!f)return[];return Array.from(f.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties($,f="",J=new WeakSet,W=0){if(!$)return{};let Z={},Q=100,j=10;for(let[H,X]of Object.entries($)){if(H==="__proto__"||H==="constructor"||H==="prototype")continue;let Y=f?`${f}.${H}`:H;if(X===null||X===void 0){Z[Y]=String(X);continue}if(Array.isArray(X)){let A=X.length>Q?X.slice(0,Q):X;try{Z[Y]=JSON.stringify(A)}catch{Z[Y]="[UnserializableArray]"}if(X.length>Q)Z[`${Y}_truncated`]=!0,Z[`${Y}_original_length`]=X.length;continue}if(typeof X==="object"){if(X instanceof Date){Z[Y]=X.toISOString();continue}if(X instanceof Error){Z[Y]=X.message;continue}if(J.has(X)){Z[Y]="[Circular]";continue}if(W>=j){Z[Y]="[MaxDepthExceeded]";continue}J.add(X),Object.assign(Z,this.flattenProperties(X,Y,J,W+1));continue}if(IG(X)){Z[Y]=X;continue}try{Z[Y]=JSON.stringify(X)}catch{Z[Y]=String(X)}}return Z}}function IG($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class j8{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,f){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:f})}emitRequired($,f){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:f})}recordCounter($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:f,attributes:J,description:W,required:Z===!0})}recordHistogram($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:f,attributes:J,description:W,required:Z===!0})}recordGauge($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:f,attributes:J,description:W,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class Sf{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new j8({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let f=this.buildAttributes($.properties);for(let J of this.adapters)J.emit($.event,f)}captureRequired($,f){let J=this.buildAttributes(f);for(let W of this.adapters)W.emitRequired($,J)}recordCounter($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter($,f,Q,W,Z)}recordHistogram($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram($,f,Q,W,Z)}recordGauge($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge($,f,Q,W,Z)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var MW=()=>{};import{metrics as xG,trace as mG}from"@opentelemetry/api";import{logs as gG}from"@opentelemetry/api-logs";import{OTLPLogExporter as vG}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as uG}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as cG}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as dG}from"@opentelemetry/resources";import{BatchLogRecordProcessor as lG,ConsoleLogRecordExporter as pG,LoggerProvider as rG}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as iG,MeterProvider as nG,PeriodicExportingMetricReader as L3}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as aG,ConsoleSpanExporter as tG,SimpleSpanProcessor as sG}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as oG}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as eG,ATTR_SERVICE_VERSION as $P}from"@opentelemetry/semantic-conventions";class O3{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,f){this.resolveProperties(f)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class hf{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let f=dG({[eG]:$.serviceName??"cline",...$.serviceVersion?{[$P]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(f),this.loggerProvider=this.createLoggerProvider(f),this.tracerProvider=this.createTracerProvider(f),this.meterProvider)xG.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)gG.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",f){return mG.getTracer($,f??this.options.serviceVersion)}createAdapter($){return new Q8({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let f=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new Sf({...$,adapters:[f],distinctId:h1($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let f=yW(this.options.metricsExporter);if(f.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),W=Math.min(30000,Math.floor(J*0.8)),Z=f.map((Q)=>WP(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:W})).filter((Q)=>Q!==null);if(Z.length===0)return null;return new nG({resource:$,readers:Z})}createTracerProvider($){let f=yW(this.options.tracesExporter);if(f.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,W=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let Q of f){let j=JP(Q,{endpoint:J,headers:W,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(j)Z.push(j)}if(Z.length===0)return null;return new oG({resource:$,spanProcessors:Z})}createLoggerProvider($){let f=yW(this.options.logsExporter);if(f.length===0)return null;let J=f.map((W)=>{let Z=fP(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new lG(Z,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((W)=>W!==null);if(J.length===0)return null;return new rG({resource:$,processors:J})}}function H8($){let f=new hf($),J=f.createTelemetryService($);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:f,telemetry:J}}function N$($){if(E4())return{telemetry:new O3($)};if($.enabled!==!0)return{telemetry:new Sf({...$,distinctId:h1($.distinctId)})};return H8($)}function Cf($){let{telemetry:f,provider:J}=N$($);return{telemetry:f,provider:J,flush:async()=>{let Q=J;if(Q&&typeof Q.forceFlush==="function")try{await Q.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([f.dispose(),J?.dispose()])}}}function yW($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function fP($,f){if($==="console")return new pG;if(!f.endpoint)return null;let J=qW(f.endpoint,"/v1/logs");return new vG({url:J,headers:f.headers})}function JP($,f){if($==="console")return new sG(new tG);if(!f.endpoint)return null;let J=qW(f.endpoint,"/v1/traces");return new aG(new cG({url:J,headers:f.headers}))}function WP($,f){if($==="console")return new L3({exporter:new iG,exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout});if(!f.endpoint)return null;let J=qW(f.endpoint,"/v1/metrics");return new L3({exporter:new uG({url:J,headers:f.headers}),exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout})}function qW($,f){let J=new URL($),W=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=W.endsWith(f)?W:`${W}${f}`,J.toString()}var m4=M1(()=>{Z$();x4();MW()});var QH={};w(QH,{normalizeUserMessage:()=>NR,buildInitialUserContent:()=>TR});async function TR($,f,J,W){let Z=MR(f),Q=await qR(J,W);if(Z.length===0&&!Q)return $;let j=[{type:"text",text:$},...Z];if(Q)j.push(...Q);return j}function NR($){if($==null)return"";if(typeof $==="string")return $;let f=$.content;if(typeof f==="string")return f;if(!Array.isArray(f))return"";let J=[];for(let W of f)if(W&&typeof W==="object"&&W.type==="text"){let Z=W.text;if(typeof Z==="string")J.push(Z)}return J.join(`
|
|
3
|
+
`)}function MR($){if(!$||$.length===0)return[];let f=[];for(let J of $){let W=yR(J);if(W)f.push(W)}return f}function yR($){let f=$.trim();if(!f)return;let J=f.match(/^data:([^;,]+);base64,(.+)$/);if(J){let W=J[1],Z=J[2];if(!W||!Z)return;return{type:"image",mediaType:W,data:Z}}return{type:"image",mediaType:"image/png",data:f}}async function qR($,f){if(!$||$.length===0)return;let J=f??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),W=await Promise.all($.map(async(Z)=>{let Q=Z.replace(/\\/g,"/");try{let j=await J(Z);return{type:"file",path:Q,content:j}}catch(j){let H=j instanceof Error?j.message:String(j);return{type:"file",path:Q,content:`Error fetching content: ${H}`}}}));if(W.length===0)return;return W}var nY={};w(nY,{updateMcpServerOAuthState:()=>Yf,setMcpServerDisabled:()=>Hf,resolveMcpServerRegistrations:()=>A$,resolveDefaultMcpSettingsPath:()=>z0,registerMcpServersFromSettingsFile:()=>Af,normalizeMcpServerOAuthState:()=>L2,loadMcpSettingsFile:()=>jf,listMcpServerOAuthStatuses:()=>bJ,hasMcpSettingsFile:()=>x$,getMcpServerOAuthState:()=>Xf});import{existsSync as t_,mkdirSync as cY,readFileSync as x9,writeFileSync as dY}from"node:fs";import{dirname as lY}from"node:path";import{resolveMcpSettingsPath as s_}from"@cline/shared/storage";import{z as S}from"zod";function I9($){if(!$)return;if($==="http")return"streamableHttp";return $}function z0(){return s_()}function Xz($){let f=x9($,"utf8"),J;try{J=JSON.parse(f)}catch(W){let Z=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object.`);return J}function iY($,f){if(!Object.hasOwn($,f))return;let J=$[f];if(!J||typeof J!=="object"||Array.isArray(J))return;return J}function Yz($,f,J){Object.defineProperty($,f,{value:J,enumerable:!0,configurable:!0,writable:!0})}function jf($={}){let f=$.filePath??z0(),J=x9(f,"utf8"),W;try{W=JSON.parse(J)}catch(Q){let j=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${f}": ${j}`)}let Z=Hz.safeParse(W);if(!Z.success){let Q=Z.error.issues.map((j)=>{let H=j.path.join(".");return H?`${H}: ${j.message}`:j.message}).join("; ");throw Error(`Invalid MCP settings at "${f}": ${Q}`)}return Z.data}function Az($){let f=x9($,"utf8"),J;try{J=JSON.parse(f)}catch(Q){let j=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${j}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object`);let W=J,Z=W.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return W}function L2($){if(!$)return;let f={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(f).length>0?f:void 0}function Vz($){if($===void 0)return;let f=m9.safeParse($);if(!f.success)return;return L2(f.data)}function x$($={}){let f=$.filePath??z0();return t_(f)}function A$($={}){let f=jf($);return Object.entries(f.mcpServers).map(([J,W])=>({name:J,transport:W.transport,disabled:W.disabled,metadata:W.metadata,oauth:W.oauth}))}function Hf($){let f=$.filePath??z0(),J=$.name.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let W=Xz(f),Z=W.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${f}": mcpServers must be an object.`);let Q={...Z},j=iY(Q,J);if(!j)throw Error(`Unknown MCP server: ${J}`);let H={...j};if($.disabled)H.disabled=!0;else delete H.disabled;Yz(Q,J,H),cY(lY(f),{recursive:!0}),dY(f,`${JSON.stringify({...W,mcpServers:Q},null,2)}
|
|
4
|
+
`)}function Xf($,f={}){let J=jf(f);if(!Object.hasOwn(J.mcpServers,$))return;return L2(J.mcpServers[$]?.oauth)}function Yf($,f,J={}){let W=J.filePath??z0(),Z=Az(W),Q=Z.mcpServers,j=iY(Q,$);if(!j)throw Error(`Unknown MCP server: ${$}`);let H=Vz(j.oauth)??{},X=L2(f(H));if(X)j.oauth=X;else delete j.oauth;return cY(lY(W),{recursive:!0}),dY(W,`${JSON.stringify(Z,null,2)}
|
|
5
|
+
`,"utf8"),X??{}}function bJ($={}){return A$($).map((J)=>{let W=J.transport.type!=="stdio",Z=J.oauth?.tokens?.access_token;return{serverName:J.name,oauthSupported:W,oauthConfigured:W&&typeof Z==="string"&&Z.trim().length>0,lastError:J.oauth?.lastError,lastAuthenticatedAt:J.oauth?.lastAuthenticatedAt}}).sort((J,W)=>J.serverName.localeCompare(W.serverName))}async function Af($,f={}){let J=A$(f);for(let W of J)await $.registerServer(W);return J}var EJ,pY,m9,o_,e_,$z,fz,Jz,Wz,rY,Zz,Qz,jz,Hz;var A5=M1(()=>{EJ=S.record(S.string(),S.string()),pY=S.record(S.string(),S.unknown()),m9=S.object({clientInformation:S.record(S.string(),S.unknown()).optional(),tokens:S.record(S.string(),S.unknown()).optional(),codeVerifier:S.string().optional(),discoveryState:S.record(S.string(),S.unknown()).optional(),redirectUrl:S.string().url().optional(),lastError:S.string().optional(),lastAuthenticatedAt:S.number().int().positive().optional()}).strip(),o_=S.object({type:S.literal("stdio"),command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:EJ.optional()}),e_=S.object({type:S.literal("sse"),url:S.string().url(),headers:EJ.optional()}),$z=S.object({type:S.literal("streamableHttp"),url:S.string().url(),headers:EJ.optional()}),fz=S.discriminatedUnion("type",[o_,e_,$z]),Jz=S.object({transport:fz,disabled:S.boolean().optional(),metadata:pY.optional(),oauth:m9.optional()}),Wz=S.enum(["stdio","sse","http","streamableHttp"]).optional(),rY=S.object({type:S.enum(["stdio","sse","streamableHttp"]).optional(),transportType:Wz,disabled:S.boolean().optional(),metadata:pY.optional(),oauth:m9.optional()});Zz=rY.extend({command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:EJ.optional()}).superRefine(($,f)=>{let J=$.type??I9($.transportType);if(J&&J!=="stdio")f.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),Qz=rY.extend({url:S.string().url(),headers:EJ.optional()}).superRefine(($,f)=>{let J=$.type??I9($.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")f.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??I9($.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth};return{transport:{type:"sse",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth}}),jz=S.union([Jz,Zz,Qz]),Hz=S.object({mcpServers:S.record(S.string(),jz)}).passthrough()});var RV={};w(RV,{createOpenTelemetryTelemetryService:()=>H8,createConfiguredTelemetryService:()=>N$,createConfiguredTelemetryHandle:()=>Cf,OpenTelemetryProvider:()=>hf,OpenTelemetryAdapter:()=>Q8});var LQ=M1(()=>{m4()});var MB={};w(MB,{writeHubDiscovery:()=>v4,withHubStartupLock:()=>u4,verifyHubConnection:()=>H$,truncateNotificationBody:()=>f4,toHubHealthUrl:()=>CW,stopLocalHubServerGracefully:()=>lW,startHubWebSocketServer:()=>Z4,startHubServer:()=>TB,spawnDetachedHubServerWithRetry:()=>bf,spawnDetachedHubServer:()=>mW,sendHubCommand:()=>r3,restartLocalHubIfIdleAfterStartupTimeout:()=>l4,resolveWorkspaceHubOwnerContext:()=>b3,resolveSharedHubOwnerContext:()=>G0,resolveHubUrl:()=>pW,resolveHubOwnerContext:()=>q$,resolveHubEndpointOptions:()=>j$,resolveHubBuildId:()=>t$,resolveDefaultHubPort:()=>Ef,resolveDefaultHubPathname:()=>xW,resolveDefaultHubHost:()=>IW,resolveCompatibleLocalHubUrl:()=>G8,resolveClineDir:()=>S3,resolveClineDataDir:()=>A8,requestHubShutdown:()=>K8,rememberRecoverableLocalHubUrl:()=>s$,readHubDiscovery:()=>V0,probeHubServer:()=>Q$,probeHubConnection:()=>p3,prewarmDetachedHubServer:()=>c4,normalizeHubWebSocketUrl:()=>o$,isHubReconnectableTransportError:()=>cW,isHubCommandTimeoutError:()=>d4,isDiscoveryFilePresent:()=>C3,ensureHubWebSocketServer:()=>WW,ensureHubServer:()=>NB,ensureDetachedHubServer:()=>I3,ensureCompatibleLocalHubUrl:()=>b1,createLocalHubScheduleRuntimeHandlers:()=>zB,createInMemoryHubOwnerContext:()=>h3,createHubServerUrl:()=>t0,createHubAuthToken:()=>g4,createConfiguredTelemetryService:()=>N$,createConfiguredTelemetryHandle:()=>Cf,connectToHub:()=>p4,clearHubDiscovery:()=>b0,NodeHubClient:()=>s0,NativeHubTransportAdapter:()=>W4,HubUIClient:()=>nW,HubTransportError:()=>O0,HubSessionClient:()=>iW,HubServerTransport:()=>u2,HubScheduleService:()=>qf,HubScheduleCommandService:()=>Tf,HubCommandError:()=>kf,DEFAULT_HUB_PORT:()=>bW,DEFAULT_HUB_PATHNAME:()=>kW,DEFAULT_HUB_HOST:()=>EW,BrowserWebSocketHubAdapter:()=>J4});import{createSessionId as qK}from"@cline/shared";function C0($,f){return{version:$.version,requestId:$.requestId,ok:!0,payload:f}}function d7($,f,J){return{version:$.version,requestId:$.requestId??qK("hubreq_"),ok:!1,error:{code:f,message:J}}}class Tf{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return C0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return C0($,{schedules:this.schedules.listSchedules({enabled:typeof $.payload?.enabled==="boolean"?$.payload.enabled:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0,tags:Array.isArray($.payload?.tags)?$.payload?.tags:void 0})});case"schedule.get":return C0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return C0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return C0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return C0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return C0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return C0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return C0($,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof $.payload?.scheduleId==="string"?$.payload.scheduleId:void 0,status:typeof $.payload?.status==="string"?$.payload.status:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0})});case"schedule.stats":return C0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return C0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return C0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return d7($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(f){return d7($,"schedule_command_failed",f instanceof Error?f.message:String(f))}}toCreateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:f}}toUpdateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:f}}}class l2{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},f=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let W of f)if(this.materializeOneOff(W))$.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of J)try{if(this.materializeSchedule(W))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as mK}from"node:path";import{buildClineSystemPrompt as gK}from"@cline/shared";import{nowIso as a7}from"@cline/shared/db";var J0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},l$=[J0.READ_FILES,J0.SEARCH_CODEBASE,J0.RUN_COMMANDS,J0.FETCH_WEB_CONTENT,J0.APPLY_PATCH,J0.EDITOR,J0.SKILLS,J0.ASK,J0.SUBMIT_AND_EXIT];var p7={};w(p7,{mergeRulesForSystemPrompt:()=>Mf,loadRulesForSystemPromptFromWatcher:()=>KW,listEnabledRulesFromWatcher:()=>l7,isRuleEnabled:()=>Y4,formatRulesForSystemPrompt:()=>Nf});function Y4($){return $.disabled!==!0}function Nf($){if($.length===0)return"";return`
|
|
6
6
|
|
|
7
7
|
# Rules
|
|
8
8
|
${$.map((J)=>`## ${J.name}
|
|
9
9
|
${J.instructions}`).join(`
|
|
10
10
|
|
|
11
|
-
`)}`}function
|
|
11
|
+
`)}`}function Mf($,f){let J=$?.trim(),W=f?.trim();if(J&&W)return`${J}
|
|
12
12
|
|
|
13
|
-
${
|
|
14
|
-
${
|
|
13
|
+
${W}`;return J||W||void 0}function l7($){return[...$.getSnapshot("rule").values()].map((J)=>J.item).filter(Y4).sort((J,W)=>J.name.localeCompare(W.name))}function KW($){return Nf(l7($))}var n7={};w(n7,{normalizeWorkspacePath:()=>L$,generateWorkspaceInfoWithDiagnostics:()=>p2,generateWorkspaceInfo:()=>yf,buildWorkspaceMetadataWithInfo:()=>GW,buildWorkspaceMetadata:()=>r2});import{basename as wK,resolve as SK}from"node:path";import{performance as r7}from"node:perf_hooks";import{processWorkspaceInfo as i7}from"@cline/shared";import hK from"simple-git";function L$($){return SK($)}async function yf($){return(await p2($)).info}function A4($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function p2($){let f=L$($),J={rootPath:f,hint:wK(f)},W;try{let Z=hK({baseDir:f});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let H=j.map((X)=>{let Y=X.refs.fetch||X.refs.push;return`${X.name}: ${Y}`});J.associatedRemoteUrls=H}}catch(j){W??=A4(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){W??=A4(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){W??=A4(j)}return{info:J,vcsType:"git",error:W}}catch(Z){return{info:J,vcsType:"none",error:A4(Z)}}}async function r2($){let f=await yf($);return i7(f)}async function GW($){let f=r7.now(),J=await p2($),W=r7.now()-f,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:i7(Z),durationMs:W,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as CK,writeFileSync as EK}from"node:fs";import{join as bK}from"node:path";import{resolveCronReportsDir as kK}from"@cline/shared/storage";function p$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function y1($,f){if(f===void 0||f===null)return;return`${$}: ${p$(f)}`}function IK($,f,J){let W=[`runId: ${p$($.runId)}`,`specId: ${p$(f.specId)}`,`externalId: ${p$(f.externalId)}`,`title: ${p$(f.title)}`,`triggerKind: ${p$($.triggerKind)}`,`status: ${p$($.status)}`,`sourcePath: ${p$(f.sourcePath)}`],Z=[y1("sessionId",$.sessionId),y1("startedAt",$.startedAt),y1("completedAt",$.completedAt),y1("triggerEventId",$.triggerEventId),y1("triggerEventType",J?.eventType),y1("triggerEventSource",J?.source),y1("triggerEventSubject",J?.subject)];for(let Q of Z)if(Q)W.push(Q);return`---
|
|
14
|
+
${W.join(`
|
|
15
15
|
`)}
|
|
16
16
|
---
|
|
17
|
-
`}function
|
|
17
|
+
`}function xK($){let f=[];if($.triggerEvent){let J=$.triggerEvent,W=[`- eventId: ${J.eventId}`,`- eventType: ${J.eventType}`,`- source: ${J.source}`,J.subject?`- subject: ${J.subject}`:"",`- occurredAt: ${J.occurredAt}`,J.dedupeKey?`- dedupeKey: ${J.dedupeKey}`:"",J.attributes?`- attributes: ${JSON.stringify(J.attributes)}`:""].filter((Z)=>Z.length>0);f.push(`## Trigger Event
|
|
18
18
|
|
|
19
|
-
${
|
|
19
|
+
${W.join(`
|
|
20
20
|
`)}
|
|
21
21
|
`)}if($.error)f.push(`## Error
|
|
22
22
|
|
|
@@ -24,21 +24,21 @@ ${$.error}
|
|
|
24
24
|
`);if($.finalText&&$.finalText.trim().length>0)f.push(`## Summary
|
|
25
25
|
|
|
26
26
|
${$.finalText.trim()}
|
|
27
|
-
`);if($.usage){let J=$.usage,
|
|
27
|
+
`);if($.usage){let J=$.usage,W=[J.inputTokens!==void 0?`- inputTokens: ${J.inputTokens}`:"",J.outputTokens!==void 0?`- outputTokens: ${J.outputTokens}`:"",J.cacheReadTokens!==void 0?`- cacheReadTokens: ${J.cacheReadTokens}`:"",J.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${J.cacheWriteTokens}`:"",J.totalCost!==void 0?`- totalCostUsd: ${J.totalCost}`:"",$.durationMs!==void 0?`- durationMs: ${$.durationMs}`:""].filter((Z)=>Z.length>0);if(W.length>0)f.push(`## Usage
|
|
28
28
|
|
|
29
|
-
${
|
|
29
|
+
${W.join(`
|
|
30
30
|
`)}
|
|
31
|
-
`)}if($.toolCalls&&$.toolCalls.length>0){let J=$.toolCalls.map((
|
|
31
|
+
`)}if($.toolCalls&&$.toolCalls.length>0){let J=$.toolCalls.map((W)=>{let Z=[`- ${W.name}`];if(W.durationMs!==void 0)Z.push(`(${W.durationMs}ms)`);if(W.error)Z.push(`error: ${W.error}`);return Z.join(" ")});f.push(`## Tool Calls
|
|
32
32
|
|
|
33
33
|
${J.join(`
|
|
34
34
|
`)}
|
|
35
35
|
`)}return f.join(`
|
|
36
|
-
`)}function
|
|
37
|
-
${
|
|
38
|
-
`)}class
|
|
36
|
+
`)}function PW($){let f=kK($.specs);CK(f,{recursive:!0});let J=bK(f,`${$.run.runId}.md`),W=`${IK($.run,$.spec,$.data.triggerEvent)}
|
|
37
|
+
${xK($.data)}`;return EK(J,W,"utf8"),J}class FW{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,f,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let W=Math.max(1,Math.floor(J)),Z=this.activeExecutions.get($)??new Set;if(Z.size>=W)return!1;return Z.add(f),this.activeExecutions.set($,Z),!0}release($,f){let J=this.activeExecutions.get($);if(!J)return;if(J.delete(f),J.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let f of this.activeExecutions.values())$+=f.size;return $}}var vK=15000,uK=90,t7=["rules","skills","plugins"];function cK($,f){return new Set($.extensions??t7).has(f)}function dK($,f){if($.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let W of $.tools)J[W]={enabled:!0,autoApprove:!0};if(f==="yolo")J[J0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function lK($){let f=$?.trim();if(!f)return;return["# Notes Directory",`Use ${f} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
|
|
38
|
+
`)}class UW extends Error{constructor($){super($);this.name="TimeoutError"}}async function pK($,f){if(f<=0)return $;let J,W=new Promise((Z,Q)=>{J=setTimeout(()=>{Q(new UW("cron run timed out"))},f)});try{return await Promise.race([$,W])}finally{if(J)clearTimeout(J)}}class i2{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor($){this.store=$.store,this.materializer=$.materializer,this.options=$,this.limiter=new FW($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??uK)*1000)}async start(){if(this.disposed)throw Error("CronRunner disposed");if(this.started)return;this.stopping=!1,this.started=!0;let $=Math.max(2000,this.options.pollIntervalMs??vK);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let f=[...this.activeRuns.entries()];await Promise.all(f.map(async([J,W])=>{if(W.sessionId)try{await this.options.runtimeHandlers.abortSession(W.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:W.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:a7(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((f)=>this.executeClaim(f)))}catch($){let f=this.options.logger;if(f)if(f.error)f.error("cron.runner.tick.failed",{error:$});else f.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,f])=>{let J=this.store.getRun($);return J?[{...J,...f}]:[]})}async executeClaim($){let f=$.run,J=this.store.getSpec(f.specId);if(!J){this.store.completeRun(f.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun(f.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let W=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,f.runId,W)){this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,f.runId),this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(f.runId,{claimToken:$.claimToken});let Q=f.triggerEventId?this.store.getEventLog(f.triggerEventId):void 0,j,H,X=Date.now(),Y;if(J.timeoutSeconds&&J.timeoutSeconds>0)Y=X+J.timeoutSeconds*1000;try{H=this.startClaimLeaseHeartbeat($);let A=await this.buildStartRequest(J);if(j=(await this.options.runtimeHandlers.startSession(A)).sessionId.trim(),!j)throw Error("runtime returned empty sessionId");this.activeRuns.set(f.runId,{claimToken:$.claimToken,sessionId:j}),this.store.attachSessionIdToRun(f.runId,j);let B={config:A,prompt:this.buildPrompt(J,Q)},K=this.options.runtimeHandlers.sendSession(j,B),G=Y?Math.max(1,Y-Date.now()):0,P=(await pK(K,G)).result,F=Date.now(),U=PW({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"done"},spec:J,data:{finalText:P.text,usage:P.usage,toolCalls:P.toolCalls,durationMs:F-X,triggerEvent:Q}});this.store.completeRun(f.runId,{status:"done",sessionId:j,reportPath:U,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",J,f.runId),this.store.updateSpecLastRunAt(J.specId,a7())}catch(A){let V=A instanceof UW;if(j&&V)try{await this.options.runtimeHandlers.abortSession(j)}catch{}let B=A instanceof Error?A.message:String(A),K=Date.now(),G=PW({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"failed"},spec:J,data:{error:B,durationMs:K-X,triggerEvent:Q}});this.store.completeRun(f.runId,{status:"failed",sessionId:j,reportPath:G,error:B,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",J,f.runId)}finally{if(H?.(),j)try{await this.options.runtimeHandlers.stopSession(j)}catch{}this.activeRuns.delete(f.runId),this.limiter.release(J.specId,f.runId)}}publishScheduleExecutionEvent($,f,J){if(f.source!=="hub-schedule"||!this.options.eventPublisher)return;let W=this.store.getRun(J);if(!W)return;let Z=W.status==="done"?"success":W.status==="cancelled"?"aborted":W.status==="running"?"running":W.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:f.externalId,executionId:W.runId,sessionId:W.sessionId,triggeredAt:new Date(W.scheduledFor??W.createdAt).getTime(),startedAt:W.startedAt?new Date(W.startedAt).getTime():void 0,endedAt:W.completedAt?new Date(W.completedAt).getTime():void 0,status:Z,errorMessage:W.error})}buildPrompt($,f){let J=$.prompt??"";if(!f)return J;let W={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload};return`${J}
|
|
39
39
|
|
|
40
40
|
Trigger event:
|
|
41
|
-
${JSON.stringify(
|
|
41
|
+
${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let W=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,W))clearInterval(J)},f);return()=>clearInterval(J)}async buildSystemPrompt($,f,J,W){let Z=lK($.notesDirectory),Q=Mf(void 0,Z),j=await r2(f),H=gK({ide:"Cline Cron",workspaceRoot:f,workspaceName:mK(f),metadata:j,rules:$.systemPrompt?void 0:Q,mode:J,providerId:W,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?Mf(H,Q)??H:H}async buildStartRequest($){let f=($.workspaceRoot??"").trim(),J=($.providerId??"").trim(),W=($.modelId??"").trim(),Z=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,Q=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():f;if(!f)throw Error("cron spec requires workspaceRoot");let j=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:f,cwd:Q,provider:J,model:W,mode:j,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,f,j,J),maxIterations:$.maxIterations,enableTools:Z?.enableTools??!0,enableSpawn:Z?.enableSpawn??!0,enableTeams:Z?.enableTeams??!0,autoApproveTools:Z?.autoApproveTools??!0,toolPolicies:dK($,j),configExtensions:t7.filter((H)=>cK($,H))}}}function n2($,f,J,W){let Z=new Set;function Q(j){let H=j.toLowerCase();if(W){let Y=W.indexOf(H);if(Y!==-1)return Y+f}let X=Number(j);if(!Number.isInteger(X)||X<f||X>J)throw Error(`Invalid cron value "${j}" for range [${f}-${J}]`);return X}for(let j of $.split(",")){if(j==="*"){for(let Y=f;Y<=J;Y+=1)Z.add(Y);continue}let H=j.indexOf("/");if(H!==-1){let Y=j.slice(0,H),A=Number(j.slice(H+1));if(!Number.isInteger(A)||A<1)throw Error(`Invalid step "${j.slice(H+1)}"`);let V=f,B=J;if(Y!=="*"){let K=Y.indexOf("-");if(K!==-1)V=Q(Y.slice(0,K)),B=Q(Y.slice(K+1));else V=Q(Y)}if(V>B)throw Error(`Invalid cron range "${Y}"`);for(let K=V;K<=B;K+=A)Z.add(K);continue}let X=j.indexOf("-");if(X!==-1){let Y=Q(j.slice(0,X)),A=Q(j.slice(X+1));if(Y>A)throw Error(`Invalid cron range "${j}"`);for(let V=Y;V<=A;V+=1)Z.add(V);continue}Z.add(Q(j))}return[...Z].sort((j,H)=>j-H)}var rK=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],o7=["sun","mon","tue","wed","thu","fri","sat"];function a2($,f,J){let W=$[f];if(typeof W!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${f+1}`);return W}function RW($,f){let J=$[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${f}`);return J}function DW($){let f=$.trim().split(/\s+/);if(f.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${f.length}`);return{minutes:n2(a2(f,0,$),0,59),hours:n2(a2(f,1,$),0,23),daysOfMonth:n2(a2(f,2,$),1,31),months:n2(a2(f,3,$),1,12,rK),daysOfWeek:n2(a2(f,4,$),0,6,o7)}}function LW($){DW($)}function e7($,f,J=Date.now()){q1($,J,f)}var s7=new Map,iK=new Map(o7.map(($,f)=>[$,f]));function $3($){let f=$?.trim();return f?f:void 0}function f3($){let f=s7.get($);if(f)return f;let J=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return s7.set($,J),J}function nK($){let f=$3($);if(!f)return;f3(f).format(new Date)}function aK($,f){let J=f3(f).formatToParts(new Date($)),W=new Map(J.map((j)=>[j.type,j.value])),Z=W.get("weekday")?.toLowerCase().slice(0,3)??"",Q=iK.get(Z);if(Q===void 0)throw Error(`Unable to resolve weekday for timezone "${f}"`);return{month:Number(W.get("month")),dayOfMonth:Number(W.get("day")),dayOfWeek:Q,hour:Number(W.get("hour")),minute:Number(W.get("minute"))}}function tK($){let f=new Date($);return{month:f.getMonth()+1,dayOfMonth:f.getDate(),dayOfWeek:f.getDay(),hour:f.getHours(),minute:f.getMinutes()}}function sK($,f){return $.months.includes(f.month)&&$.daysOfMonth.includes(f.dayOfMonth)&&$.daysOfWeek.includes(f.dayOfWeek)&&$.hours.includes(f.hour)&&$.minutes.includes(f.minute)}function oK($,f,J){let W=DW($),Z=new Date(f);Z.setSeconds(0,0);let Q=Z.getTime()+60000,j=new Date(f);j.setFullYear(j.getFullYear()+4);let H=j.getTime();while(Q<=H){if(sK(W,aK(Q,J)))return Q;Q+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${J}"`)}function q1($,f,J){let W=$3(J);if(W)return nK(W),oK($,f,W);let Z=DW($),Q=new Date(f);Q.setSeconds(0,0),Q=new Date(Q.getTime()+60000);let j=new Date(f);j.setFullYear(j.getFullYear()+4);while(Q<=j){let{month:H,dayOfMonth:X,dayOfWeek:Y,hour:A,minute:V}=tK(Q.getTime());if(!Z.months.includes(H)){let B=Z.months.find((G)=>G>H)??RW(Z.months,"months"),K=B<=H?1:0;Q=new Date(Q.getFullYear()+K,B-1,1,0,0,0,0);continue}if(!Z.daysOfMonth.includes(X)||!Z.daysOfWeek.includes(Y)){Q=new Date(Q.getFullYear(),Q.getMonth(),X+1,0,0,0,0);continue}if(!Z.hours.includes(A)){let B=Z.hours.find((G)=>G>A)??RW(Z.hours,"hours"),K=B<=A?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()+K,B,0,0,0);continue}if(!Z.minutes.includes(V)){let B=Z.minutes.find((G)=>G>V)??RW(Z.minutes,"minutes"),K=B<=V?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate(),Q.getHours()+K,B,0,0);continue}return Q.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{randomUUID as t2}from"node:crypto";import{asOptionalString as I,asString as a,loadSqliteDb as $G,nowIso as K0}from"@cline/shared/db";import{resolveCronDbPath as fG}from"@cline/shared/storage";var eK=[`CREATE TABLE IF NOT EXISTS cron_specs (
|
|
42
42
|
spec_id TEXT PRIMARY KEY,
|
|
43
43
|
external_id TEXT NOT NULL,
|
|
44
44
|
source_path TEXT NOT NULL UNIQUE,
|
|
@@ -129,17 +129,17 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
|
|
|
129
129
|
ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
|
|
130
130
|
ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
|
|
131
131
|
ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
|
|
132
|
-
ON cron_specs(source_path);`];function
|
|
132
|
+
ON cron_specs(source_path);`];function J3($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let f of eK)$.exec(f)}function V4($){if(!$)return;try{let f=JSON.parse($);if(f&&typeof f==="object"&&!Array.isArray(f))return f}catch{}return}function OW($,f={}){if(!$)return;try{let J=JSON.parse($);if(!Array.isArray(J))return;let W=J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);if(f.preserveEmpty)return W;return W.length>0?W:void 0}catch{return}}function w1($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function r$($){return{specId:a($.spec_id),externalId:a($.external_id),sourcePath:a($.source_path),triggerKind:a($.trigger_kind),sourceMtimeMs:w1($.source_mtime_ms),sourceHash:I($.source_hash),parseStatus:a($.parse_status)==="invalid"?"invalid":"valid",parseError:I($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:a($.title),prompt:I($.prompt),workspaceRoot:I($.workspace_root),scheduleExpr:I($.schedule_expr),timezone:I($.timezone),eventType:I($.event_type),filters:V4(I($.filters_json)),debounceSeconds:w1($.debounce_seconds),dedupeWindowSeconds:w1($.dedupe_window_seconds),cooldownSeconds:w1($.cooldown_seconds),mode:I($.mode),systemPrompt:I($.system_prompt),providerId:I($.provider_id),modelId:I($.model_id),maxIterations:w1($.max_iterations),timeoutSeconds:w1($.timeout_seconds),maxParallel:w1($.max_parallel),tools:OW(I($.tools_json),{preserveEmpty:!0}),notesDirectory:I($.notes_directory),extensions:OW(I($.extensions_json),{preserveEmpty:!0}),source:I($.source),tags:OW(I($.tags_json)),metadata:V4(I($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:I($.last_materialized_run_id),lastRunAt:I($.last_run_at),nextRunAt:I($.next_run_at),createdAt:a($.created_at),updatedAt:a($.updated_at)}}function _W($){return{runId:a($.run_id),specId:a($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:a($.trigger_kind),status:a($.status),claimToken:I($.claim_token),claimStartedAt:I($.claim_started_at),claimUntilAt:I($.claim_until_at),scheduledFor:I($.scheduled_for),triggerEventId:I($.trigger_event_id),startedAt:I($.started_at),completedAt:I($.completed_at),sessionId:I($.session_id),reportPath:I($.report_path),error:I($.error),attemptCount:Number($.attempt_count??0),createdAt:a($.created_at),updatedAt:a($.updated_at)}}function W3($){return{eventId:a($.event_id),eventType:a($.event_type),source:a($.source),subject:I($.subject),occurredAt:a($.occurred_at),receivedAt:a($.received_at),workspaceRoot:I($.workspace_root),dedupeKey:I($.dedupe_key),payload:V4(I($.payload_json)),attributes:V4(I($.attributes_json)),processingStatus:a($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:I($.error),createdAt:a($.created_at),updatedAt:a($.updated_at)}}function Z3($){return $?JSON.stringify($):null}var JG=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function Q3($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function WG($,f,J,W){for(let Z of JG){let Q=$[Z],j=f[Z];if(Q3(Q)!==Q3(j))return!0}if(J===!1&&W===!0)return!0;return!1}function ZG($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function QG($){return`hub/schedules/${$}.cron.md`}function jG($){let f={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(f).length>0?f:void 0}function zW($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((f)=>f.trim().length>0),enabled:$.enabled!==!1,metadata:jG($)}}function j3($){return JSON.stringify(zW($))}function HG($,f){let J=$.metadata?{...$.metadata}:{},W=f.createdBy===null?void 0:f.createdBy!==void 0?f.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,Z=f.cwd!==void 0?f.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,Q=f.runtimeOptions!==void 0?f.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:f.name??$.title,cronPattern:f.cronPattern??$.scheduleExpr??"",prompt:f.prompt??$.prompt??"",workspaceRoot:f.workspaceRoot??$.workspaceRoot??"",cwd:Z,modelSelection:f.modelSelection!==void 0?f.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:f.enabled??$.enabled,mode:f.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:f.systemPrompt===null?void 0:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,maxIterations:f.maxIterations===null?void 0:f.maxIterations!==void 0?f.maxIterations:$.maxIterations,timeoutSeconds:f.timeoutSeconds===null?void 0:f.timeoutSeconds!==void 0?f.timeoutSeconds:$.timeoutSeconds,maxParallel:f.maxParallel??$.maxParallel??1,createdBy:W,tags:f.tags??$.tags,runtimeOptions:Q,metadata:f.metadata!==void 0?f.metadata:Object.keys(J).length>0?J:void 0}}class s2{db;constructor($={}){let f=$.dbPath??fG();this.db=$G(f),J3(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return f?r$(f):void 0}getSpec($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return f?r$(f):void 0}getSpecByExternalId($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return f?r$(f):void 0}listSpecs($={}){let f=[],J=[];if($.triggerKind)f.push("trigger_kind = ?"),J.push($.triggerKind);if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.parseStatus)f.push("parse_status = ?"),J.push($.parseStatus);if(!$.includeRemoved)f.push("removed = 0");let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>r$(j))}createHubSchedule($){let f=`sched_${t2()}`,J=this.upsertSpec({externalId:f,sourcePath:QG(f),triggerKind:"schedule",sourceHash:j3($),parseStatus:"valid",spec:zW($)});this.initializeScheduleNextRun(J.record.specId);let W=this.getSpec(J.record.specId);if(!W)throw Error("failed to create hub schedule");return W}getHubSchedule($){let f=this.db.prepare(`SELECT * FROM cron_specs
|
|
133
133
|
WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
|
|
134
|
-
ORDER BY created_at ASC LIMIT 1`).get($);return f?
|
|
134
|
+
ORDER BY created_at ASC LIMIT 1`).get($);return f?r$(f):void 0}listHubSchedules($={}){let f=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let Q of $.tags)f.push("tags_json LIKE ?"),J.push(`%"${Q.trim()}"%`);let W=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
|
|
135
135
|
WHERE ${f.join(" AND ")}
|
|
136
|
-
ORDER BY created_at DESC LIMIT ?`).all(...J,
|
|
136
|
+
ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Q)=>r$(Q))}updateHubSchedule($,f){let J=this.getHubSchedule($);if(!J)return;let W=HG(J,f),Z=this.upsertSpec({externalId:$,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:j3(W),parseStatus:"valid",spec:zW(W)});if(f.cronPattern!==void 0||f.enabled!==void 0)this.initializeScheduleNextRun(Z.record.specId);return this.getSpec(Z.record.specId)}deleteHubSchedule($){let f=this.getHubSchedule($);if(!f)return!1;return this.markSpecRemoved(f.specId),this.cancelQueuedRunsForSpec(f.specId),!0}enqueueHubScheduleRun($,f="manual"){let J=this.getHubSchedule($);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:f,scheduledFor:K0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
|
|
137
137
|
WHERE trigger_kind = 'event'
|
|
138
138
|
AND event_type = ?
|
|
139
139
|
AND enabled = 1
|
|
140
140
|
AND removed = 0
|
|
141
141
|
AND parse_status = 'valid'
|
|
142
|
-
ORDER BY created_at ASC`).all($).map((J)=>
|
|
142
|
+
ORDER BY created_at ASC`).all($).map((J)=>r$(J))}upsertSpec($){let f=K0(),J=this.getSpecBySourcePath($.sourcePath),W=$.spec,Z={title:W?.title??J?.title??ZG($.sourcePath),prompt:W?.prompt,workspaceRoot:W?.workspaceRoot,scheduleExpr:W?.triggerKind==="schedule"?W.schedule:void 0,timezone:W?.triggerKind==="schedule"?W.timezone:void 0,eventType:W?.triggerKind==="event"?W.event:void 0,filters:W?.triggerKind==="event"?W.filters:void 0,debounceSeconds:W?.triggerKind==="event"?W.debounceSeconds:void 0,dedupeWindowSeconds:W?.triggerKind==="event"?W.dedupeWindowSeconds:void 0,cooldownSeconds:W?.triggerKind==="event"?W.cooldownSeconds:void 0,mode:W?.mode,systemPrompt:W?.systemPrompt,providerId:W?.modelSelection?.providerId,modelId:W?.modelSelection?.modelId,maxIterations:W?.maxIterations,timeoutSeconds:W?.timeoutSeconds,maxParallel:W&&"maxParallel"in W?W.maxParallel:void 0,tools:W?.tools,notesDirectory:W?.notesDirectory,extensions:W?.extensions,source:W?.source},Q=$.parseStatus==="valid"&&(W?.enabled??!0);if(!J){let A=`cspec_${t2()}`;this.insertSpecRow(A,$,Z,Q,f);let V=this.getSpec(A);if(!V)throw Error("failed to insert cron_spec row");return{record:V,created:!0,revisionChanged:!0}}let H=J.sourceHash!==$.sourceHash&&WG(J,Z,J.enabled,Q),X=H?J.revision+1:J.revision;this.updateSpecRow(J.specId,$,Z,Q,X,f);let Y=this.getSpec(J.specId);if(!Y)throw Error("failed to reload cron_spec after update");return{record:Y,created:!1,revisionChanged:H}}insertSpecRow($,f,J,W,Z){let Q=f.spec;this.db.prepare(`INSERT INTO cron_specs (
|
|
143
143
|
spec_id, external_id, source_path, trigger_kind,
|
|
144
144
|
source_mtime_ms, source_hash, parse_status, parse_error,
|
|
145
145
|
enabled, removed, title, prompt, workspace_root,
|
|
@@ -150,7 +150,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
|
|
|
150
150
|
tools_json, notes_directory, extensions_json, source,
|
|
151
151
|
tags_json, metadata_json, revision,
|
|
152
152
|
created_at, updated_at
|
|
153
|
-
) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run($,f.externalId,f.sourcePath,f.triggerKind,f.sourceMtimeMs??null,f.sourceHash,f.parseStatus,f.parseError??null,
|
|
153
|
+
) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run($,f.externalId,f.sourcePath,f.triggerKind,f.sourceMtimeMs??null,f.sourceHash,f.parseStatus,f.parseError??null,W?1:0,0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,Q?.tags?JSON.stringify(Q.tags):null,Q?.metadata?JSON.stringify(Q.metadata):null,1,Z,Z)}updateSpecRow($,f,J,W,Z,Q){let j=f.spec;this.db.prepare(`UPDATE cron_specs SET
|
|
154
154
|
external_id = ?, trigger_kind = ?,
|
|
155
155
|
source_mtime_ms = ?, source_hash = ?, parse_status = ?, parse_error = ?,
|
|
156
156
|
enabled = ?, removed = 0, title = ?, prompt = ?,
|
|
@@ -162,31 +162,31 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
|
|
|
162
162
|
tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
|
|
163
163
|
tags_json = ?, metadata_json = ?,
|
|
164
164
|
revision = ?, updated_at = ?
|
|
165
|
-
WHERE spec_id = ?`).run(f.externalId,f.triggerKind,f.sourceMtimeMs??null,f.sourceHash,f.parseStatus,f.parseError??null,
|
|
165
|
+
WHERE spec_id = ?`).run(f.externalId,f.triggerKind,f.sourceMtimeMs??null,f.sourceHash,f.parseStatus,f.parseError??null,W?1:0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,j?.tags?JSON.stringify(j.tags):null,j?.metadata?JSON.stringify(j.metadata):null,Z,Q,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(K0(),$)}updateSpecNextRunAt($,f){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f??null,K0(),$)}updateSpecLastRunAt($,f){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f,K0(),$)}updateLastMaterializedRunId($,f){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(f,K0(),$)}initializeScheduleNextRun($){let f=this.getSpec($);if(!f||f.triggerKind!=="schedule"||!f.enabled||!f.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let J=new Date(q1(f.scheduleExpr,Date.now(),f.timezone)).toISOString();this.updateSpecNextRunAt($,J)}materializeDueScheduleRun($){let f=$.nowMs,J=new Date(f).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!W)return this.db.exec("COMMIT;"),{queued:!1};let Z=r$(W);if(Z.triggerKind!=="schedule"||!Z.enabled||Z.removed||Z.parseStatus!=="valid"||!Z.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let Q=Z.nextRunAt;if(!Q){let X=new Date(q1(Z.scheduleExpr,f,Z.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(X,J,Z.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:X}}if(new Date(Q).getTime()>f)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:Q};let j=`crun_${t2()}`,H;try{H=new Date(q1(Z.scheduleExpr,f,Z.timezone)).toISOString()}catch{H=void 0}return this.db.prepare(`INSERT INTO cron_runs (
|
|
166
166
|
run_id, spec_id, spec_revision, trigger_kind, status,
|
|
167
167
|
scheduled_for, trigger_event_id, attempt_count,
|
|
168
168
|
created_at, updated_at
|
|
169
|
-
) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(j,Z.specId,Z.revision,"schedule","queued",
|
|
169
|
+
) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(j,Z.specId,Z.revision,"schedule","queued",Q,null,0,J,J),this.db.prepare(`UPDATE cron_specs SET
|
|
170
170
|
last_materialized_run_id = ?,
|
|
171
171
|
last_run_at = ?,
|
|
172
172
|
next_run_at = ?,
|
|
173
173
|
updated_at = ?
|
|
174
|
-
WHERE spec_id = ?`).run(j,J,
|
|
174
|
+
WHERE spec_id = ?`).run(j,J,H??null,J,Z.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(j),nextRunAt:H}}catch(W){throw this.db.exec("ROLLBACK;"),W}}getRun($){let f=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return f?_W(f):void 0}insertEventLog($,f={}){let J=K0(),W=f.receivedAtIso??J,Z=$.eventId.trim();if(!Z)throw Error("automation event requires eventId");let Q=$.eventType.trim();if(!Q)throw Error("automation event requires eventType");let j=$.source.trim();if(!j)throw Error("automation event requires source");let H=$.occurredAt.trim()||W,X=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
|
|
175
175
|
event_id, event_type, source, subject,
|
|
176
176
|
occurred_at, received_at, workspace_root, dedupe_key,
|
|
177
177
|
payload_json, attributes_json, processing_status,
|
|
178
178
|
matched_spec_count, queued_run_count, suppressed_count,
|
|
179
179
|
error, created_at, updated_at
|
|
180
|
-
) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(Z,
|
|
180
|
+
) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(Z,Q,j,$.subject?.trim()||null,H,W,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,Z3($.payload),Z3($.attributes),"received",0,0,0,null,J,J).changes??0,Y=this.getEventLog(Z);if(!Y)throw Error("failed to insert cron_event_log row");return{record:Y,created:X===1}}getEventLog($){let f=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return f?W3(f):void 0}listEventLogs($={}){let f=[],J=[];if($.eventType)f.push("event_type = ?"),J.push($.eventType);if($.source)f.push("source = ?"),J.push($.source);if($.processingStatus)f.push("processing_status = ?"),J.push($.processingStatus);let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${W}
|
|
181
181
|
ORDER BY received_at DESC, created_at DESC
|
|
182
|
-
LIMIT ?`).all(...J,Z).map((j)=>
|
|
182
|
+
LIMIT ?`).all(...J,Z).map((j)=>W3(j))}updateEventLogProcessing($,f){return(this.db.prepare(`UPDATE cron_event_log SET
|
|
183
183
|
processing_status = ?,
|
|
184
184
|
matched_spec_count = COALESCE(?, matched_spec_count),
|
|
185
185
|
queued_run_count = COALESCE(?, queued_run_count),
|
|
186
186
|
suppressed_count = COALESCE(?, suppressed_count),
|
|
187
187
|
error = ?,
|
|
188
188
|
updated_at = ?
|
|
189
|
-
WHERE event_id = ?`).run(f.status,f.matchedSpecCount??null,f.queuedRunCount??null,f.suppressedCount??null,f.error??null,
|
|
189
|
+
WHERE event_id = ?`).run(f.status,f.matchedSpecCount??null,f.queuedRunCount??null,f.suppressedCount??null,f.error??null,K0(),$).changes??0)===1}listRuns($={}){let f=[],J=[];if($.specId)f.push("spec_id = ?"),J.push($.specId);if($.status){let j=Array.isArray($.status)?$.status:[$.status];if(j.length>0){let H=j.map(()=>"?").join(",");f.push(`status IN (${H})`);for(let X of j)J.push(X)}}let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>_W(j))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
|
|
190
190
|
INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
|
|
191
191
|
WHERE r.spec_id = ?
|
|
192
192
|
AND r.trigger_kind = 'event'
|
|
@@ -204,7 +204,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
|
|
|
204
204
|
AND r.status = 'queued'
|
|
205
205
|
AND e.dedupe_key = ?
|
|
206
206
|
ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
|
|
207
|
-
LIMIT 1`).get($.specId,$.dedupeKey);return f?
|
|
207
|
+
LIMIT 1`).get($.specId,$.dedupeKey);return f?_W(f):void 0}updateQueuedEventRunForDebounce($){let f=K0();if((this.db.prepare(`UPDATE cron_runs SET
|
|
208
208
|
trigger_event_id = ?,
|
|
209
209
|
scheduled_for = ?,
|
|
210
210
|
updated_at = ?
|
|
@@ -213,12 +213,12 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
|
|
|
213
213
|
AND status = 'queued'`).run($.triggerEventId,$.scheduledFor,f,$.runId).changes??0)!==1)return;return this.getRun($.runId)}hasOneOffRunForRevision($,f){return!!this.db.prepare(`SELECT run_id FROM cron_runs
|
|
214
214
|
WHERE spec_id = ? AND spec_revision = ?
|
|
215
215
|
AND trigger_kind = 'one_off'
|
|
216
|
-
LIMIT 1`).get($,f)}enqueueRun($){let f=`crun_${
|
|
216
|
+
LIMIT 1`).get($,f)}enqueueRun($){let f=`crun_${t2()}`,J=K0();this.db.prepare(`INSERT INTO cron_runs (
|
|
217
217
|
run_id, spec_id, spec_revision, trigger_kind, status,
|
|
218
218
|
scheduled_for, trigger_event_id, attempt_count,
|
|
219
219
|
created_at, updated_at
|
|
220
|
-
) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(f,$.specId,$.specRevision,$.triggerKind,"queued",$.scheduledFor??null,$.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId($.specId,f);let
|
|
221
|
-
WHERE spec_id = ? AND status = 'queued'`).run(
|
|
220
|
+
) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(f,$.specId,$.specRevision,$.triggerKind,"queued",$.scheduledFor??null,$.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId($.specId,f);let W=this.getRun(f);if(!W)throw Error("failed to insert cron_run row");return W}cancelQueuedRunsForSpec($){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
|
|
221
|
+
WHERE spec_id = ? AND status = 'queued'`).run(K0(),$).changes??0}claimDueRuns($){let f=$.nowIso,J=Math.max(1000,Math.floor($.leaseMs)),W=new Date(new Date(f).getTime()+J).toISOString(),Z=Math.max(1,Math.floor($.limit??25)),Q=[];this.db.exec("BEGIN IMMEDIATE;");try{let j=this.db.prepare(`SELECT * FROM cron_runs
|
|
222
222
|
WHERE (
|
|
223
223
|
status = 'queued'
|
|
224
224
|
OR (
|
|
@@ -230,7 +230,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
|
|
|
230
230
|
)
|
|
231
231
|
AND (scheduled_for IS NULL OR scheduled_for <= ?)
|
|
232
232
|
ORDER BY COALESCE(scheduled_for, created_at) ASC
|
|
233
|
-
LIMIT ?`).all(f,f,Z);for(let
|
|
233
|
+
LIMIT ?`).all(f,f,Z);for(let H of j){let X=a(H.run_id);if(!X)continue;let Y=`cclaim_${t2()}`;if((this.db.prepare(`UPDATE cron_runs SET
|
|
234
234
|
status = 'running',
|
|
235
235
|
claim_token = ?,
|
|
236
236
|
claim_started_at = ?,
|
|
@@ -251,8 +251,8 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
|
|
|
251
251
|
AND claim_until_at <= ?
|
|
252
252
|
AND completed_at IS NULL
|
|
253
253
|
)
|
|
254
|
-
)`).run(Y,f,
|
|
255
|
-
WHERE run_id = ? AND claim_token = ?`).run(J,
|
|
254
|
+
)`).run(Y,f,W,f,f,X,f).changes??0)!==1)continue;let V=this.getRun(X);if(!V)continue;Q.push({run:V,claimToken:Y,claimUntilAt:W})}this.db.exec("COMMIT;")}catch(j){throw this.db.exec("ROLLBACK;"),j}return Q}renewClaim($,f,J){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
|
|
255
|
+
WHERE run_id = ? AND claim_token = ?`).run(J,K0(),$,f).changes??0)===1}completeRun($,f){let J=f.completedAtIso??K0(),W=f.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
|
|
256
256
|
status = ?,
|
|
257
257
|
session_id = COALESCE(?, session_id),
|
|
258
258
|
report_path = COALESCE(?, report_path),
|
|
@@ -262,7 +262,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
|
|
|
262
262
|
claim_token = NULL,
|
|
263
263
|
claim_until_at = NULL,
|
|
264
264
|
updated_at = ?
|
|
265
|
-
${
|
|
265
|
+
${W}`).run(f.status,f.sessionId??null,f.reportPath??null,f.error??null,J,J,$,...f.claimToken?[f.claimToken]:[]).changes??0)>0}requeueRun($){let f=K0();return(this.db.prepare(`UPDATE cron_runs SET
|
|
266
266
|
status = 'queued',
|
|
267
267
|
claim_started_at = NULL,
|
|
268
268
|
claim_token = NULL,
|
|
@@ -274,24 +274,24 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
|
|
|
274
274
|
error = ?,
|
|
275
275
|
scheduled_for = COALESCE(?, scheduled_for),
|
|
276
276
|
updated_at = ?
|
|
277
|
-
WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,f,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,f){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(f,B0(),$)}attachReportPathToRun($,f){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(f,B0(),$)}}function a6($){return $?new Date($).getTime():void 0}function BG($){let f=$.metadata?{...$.metadata}:void 0;if(f)delete f.__hubScheduleCreatedBy,delete f.__hubScheduleCwd,delete f.__hubRuntimeOptions;return f}function n6($){let f=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof f?.__hubScheduleCwd==="string"?f.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:a6($.nextRunAt),lastRunAt:a6($.lastRunAt),createdBy:typeof f?.__hubScheduleCreatedBy==="string"?f.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:f?.__hubRuntimeOptions&&typeof f.__hubRuntimeOptions==="object"&&!Array.isArray(f.__hubRuntimeOptions)?f.__hubRuntimeOptions:void 0,metadata:BG($)}}function GG($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function N3($,f){return{executionId:$.runId,scheduleId:f,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:a6($.startedAt),endedAt:a6($.completedAt),status:GG($.status),errorMessage:$.error}}class P2{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new I8({dbPath:$.dbPath}),this.materializer=new w8({store:this.store}),this.runner=new C8({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,eventPublisher:$.eventPublisher,workspaceRoot:"",logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule($){if(n5($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return n6(this.store.createHubSchedule($))}getSchedule($){let f=this.store.getHubSchedule($);return f?n6(f):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((f)=>n6(f))}updateSchedule($,f){if(f.cronPattern!==void 0)n5(f.cronPattern);let J=this.store.getHubSchedule($);if(!J)return;let Q=f.workspaceRoot!==void 0?f.workspaceRoot.trim():J.workspaceRoot;if((f.enabled??J.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let W=this.store.updateHubSchedule($,{...f,scheduleId:$});return W?n6(W):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;await this.runner.tick();let J=this.store.getRun(f.runId)??f;return N3(J,$)}listScheduleExecutions($){let f=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,J={specId:f?.specId,limit:$.limit};return this.store.listRuns(J).map((Z)=>{let W=f??this.store.getSpec(Z.specId);if(!W||W.source!=="hub-schedule")return;return N3(Z,W.externalId)}).filter((Z)=>{if(!Z)return!1;return!$.status||Z.status===$.status})}getScheduleStats($){let f=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(f.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,Q=0,Z=0,W;for(let j of f){if(j.status==="success"||j.status==="completed")J+=1;if(!W&&j.status!=="success"&&j.status!=="completed")W=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,Q+=1}return{totalRuns:f.length,successRate:J/f.length,avgDurationSeconds:Q>0?Z/Q/1000:0,lastFailure:W}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let f=this.store.getSpec($.specId);if(!f||f.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:f.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:f.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+f.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let f={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(f).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,Q)=>String(J.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:J,nextRunAt:Q})=>({scheduleId:J.externalId,name:J.title,nextRunAt:Q}))}}Lf();import{createSessionId as tK,resolveHubCommandTimeoutMs as sK}from"@cline/shared";import{spawn as yK}from"node:child_process";import{closeSync as wK,mkdirSync as SK,openSync as hK}from"node:fs";import{basename as CK,dirname as EK,join as bK}from"node:path";import{fileURLToPath as kK}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as IK,isHubDaemonProcess as o3,withResolvedClineBuildEnv as xK}from"@cline/shared";import{createHash as XK,randomBytes as HK}from"node:crypto";import{existsSync as YK}from"node:fs";import{chmod as VK,mkdir as J9,readFile as l3,rm as Q9,writeFile as p3}from"node:fs/promises";import{dirname as r3,join as Z9}from"node:path";import{resolveClineDataDir as i8,resolveClineDir as i3}from"@cline/shared/storage";var v3="0.0.42";var u3={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:v3,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var AK="CLINE_HUB_DISCOVERY_PATH",BK="CLINE_HUB_BUILD_ID",c3=30000,GK=15000,KK=100;function FK($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function PK($){return XK("sha256").update($).digest("hex").slice(0,12)}function UK($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f?String(f.code)==="EPERM":!1}}function Of(){return HK(32).toString("hex")}function DK($){return new Promise((f)=>setTimeout(f,$))}function RK($){return`${$}.lock`}async function LK($){try{let f=JSON.parse(await l3(Z9($,"owner.json"),"utf8"));if(typeof f.pid!=="number"||typeof f.acquiredAt!=="string")return;return{pid:f.pid,acquiredAt:f.acquiredAt}}catch{return}}async function d3($){await Q9($,{recursive:!0,force:!0}).catch(()=>{return})}function u$(){return process.env[BK]?.trim()||String(u3.version)}function _$($=process.argv[1]?.trim()||process.cwd()){let f=`hub-${PK($)}`,J=process.env[AK]?.trim()||Z9(i8(),"locks","hub","owners",`${FK(f)}.json`);return{ownerId:f,discoveryPath:J}}function n3($=`hub-${Date.now().toString(36)}`){return _$($)}async function V0($){try{let f=JSON.parse(await l3($,"utf8"));if(typeof f.hubId!=="string"||typeof f.protocolVersion!=="string"||typeof f.authToken!=="string"||typeof f.host!=="string"||typeof f.port!=="number"||typeof f.url!=="string"||typeof f.startedAt!=="string"||typeof f.updatedAt!=="string")return;return{hubId:f.hubId,protocolVersion:f.protocolVersion,buildId:typeof f.buildId==="string"?f.buildId:void 0,authToken:f.authToken,host:f.host,port:f.port,url:f.url,pid:typeof f.pid==="number"?f.pid:void 0,startedAt:f.startedAt,updatedAt:f.updatedAt}}catch{return}}async function zf($,f){await J9(r3($),{recursive:!0}),await Q9($,{force:!0}).catch(()=>{return}),await p3($,`${JSON.stringify(f,null,2)}
|
|
278
|
-
`,{encoding:"utf8",mode:384}),await
|
|
279
|
-
`,"utf8");try{return await f()}finally{await d3(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await LK(J),X=j?Date.now()-Date.parse(j.acquiredAt):c3+1;if(!j||!UK(j.pid)||X>c3){await d3(J);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${J}`);await DK(KK)}}async function G0($){try{let f=await fetch(W9($));if(!f.ok)return;return await f.json()}catch{return}}function n0($,f,J="/hub"){return new URL(`ws://${$}:${f}${J}`).toString()}function W9($){let f=new URL($);return f.protocol=f.protocol==="wss:"?"https:":"http:",f.pathname="/health",f.search="",f.toString()}function a3($){return YK($)}import{CLINE_HUB_DEV_PORT as OK,CLINE_HUB_PORT as zK,resolveClineBuildEnv as _K}from"@cline/shared";var NK="CLINE_HUB_HOST",TK="CLINE_HUB_PORT",MK="CLINE_HUB_PATHNAME",j9="127.0.0.1",X9=zK,H9="/hub";function t3($){return _K($)==="development"?OK:X9}function Y9($={}){return($.env??process.env)[NK]?.trim()||j9}function z2($={}){let J=($.env??process.env)[TK]?.trim();if(!J)return t3($);let Q=Number.parseInt(J,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return t3($);return Q}function V9($={}){return($.env??process.env)[MK]?.trim()||H9}function f$($={},f={}){return{host:$.host??Y9(f),port:$.port??z2(f),pathname:$.pathname??V9(f)}}var qK="shared:cline";function s3($){let f=P$($.trim());return _$(`workspace:${f||$.trim()}`)}function K0($=qK){return _$($)}var mK=8000,gK=200,vK=3000,uK=100,cK=[100,250,500,1000,2000],dK="--cline-hub-daemon";function lK($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function pK(){try{let $=bK(i8(),"logs","hub-daemon.log");return SK(EK($),{recursive:!0}),{fd:hK($,"a"),logPath:$}}catch{return}}function n8($){let f=$.buildId?.trim();return!!f&&f===u$()}async function rK($,f){let J=Date.now()+f;while(Date.now()<J){if(!(await G0($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,uK))}return!1}async function a8($,f){if(n8($))return;if(await t8($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}await rK($.url,vK),await k0(f).catch(()=>{return})}function iK(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return kK(new URL(`./entry.${$}`,import.meta.url))}function nK($,f){let J=iK(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let Z=CK(Q).toLowerCase().includes("bun"),W=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),X=W?[dK]:[...j?["--conditions=development"]:[],J];return{launcher:Q,args:[...X,"--cwd",$,...lK(f)],cwd:$,env:{...xK(process.env),CLINE_NO_INTERACTIVE:"1",[IK]:"1"}}}function aK($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let J="message"in $?$.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function A9($,f={}){if(o3())return;let J=nK($,f),Q=pK();try{yK(J.launcher,J.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(Q)wK(Q.fd)}}async function _2($,f={}){for(let J=0;;J++)try{A9($,f);return}catch(Q){let Z=cK[J];if(!aK(Q)||Z===void 0)throw Q;await new Promise((W)=>setTimeout(W,Z))}}function Nf($,f={}){if(o3())return;let J=K0(),Q=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=f$(f),W=n0(Z.host,Z.port,Z.pathname);V0(J.discoveryPath).then(async(j)=>{if(j?.url){let V=await G0(j.url);if(V?.url&&n8(V)&&await J$(V.url,{authToken:j.authToken}))return;if(V?.url)await a8({...V,authToken:j.authToken},J.discoveryPath);else await k0(J.discoveryPath).catch(()=>{return})}let X=await G0(W);if(X?.url)await a8(X,J.discoveryPath);let Y=!Q&&Z.port!==0?{...Z,port:0}:Z;await _2($,Y)}).catch(()=>{})}async function e3($,f={}){let J=K0(),Q=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=f$(f),j=n0(W.host,W.port,W.pathname),X=(G)=>{if(!Q)c$(G.url,G.authToken);return G},H=await V0(J.discoveryPath);if(H?.url){let G=await G0(H.url);if(G?.url&&n8(G)&&await J$(G.url,{authToken:H.authToken}))return X({url:G.url,authToken:H.authToken});if(G?.url)await a8({...G,authToken:H.authToken},J.discoveryPath);else await k0(J.discoveryPath).catch(()=>{return})}let Y=await G0(j);if(Y?.url)await a8(Y,J.discoveryPath);let A=!Z&&W.port!==0?{...W,port:0}:W;await _2($,A);let B=Date.now()+mK;while(Date.now()<B){let G=await V0(J.discoveryPath);if(G?.url){let D=await G0(G.url);if(D?.url&&n8(D)&&await J$(D.url,{authToken:G.authToken}))return X({url:D.url,authToken:G.authToken})}let K=await G0(j);if(K?.url&&!n8(K))await a8(K,J.discoveryPath);await new Promise((D)=>setTimeout(D,gK))}throw Error("Timed out waiting for detached hub startup.")}function oK(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function ZW($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return ZW($.data);return String($)}function eK($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function $W($){let f=$,J=eK(f.reason);return new O0("hub_connection_closed",f.code||J?`Hub connection closed (code=${f.code??0}${J?`, reason=${J}`:""})`:B9,{closeCode:f.code,closeReason:J||void 0})}function $F($,f){if($ instanceof O0)return $;if($ instanceof Error)return new O0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new O0("hub_connect_failed",$.error.message);let J=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(J)return new O0("hub_connect_failed",J);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new O0("hub_connect_failed",Q?`Failed to connect to hub at ${f.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${f.toString()}.`)}var fF=8000,JF=200,fW="*",JW=8000,QF="cline-hub-auth.",WW=new Map,jW=new Set,ZF=3000,WF=3000,jF=100,B9="Hub connection closed",XF=250,HF=5000,QW=0.5;class O0 extends Error{code;details;constructor($,f,J){super(f);this.code=$;this.details=J;this.name="HubTransportError"}}function F9($){return $ instanceof O0}class N2 extends Error{command;code;constructor($,f,J){super(J);this.command=$;this.code=f;this.name="HubCommandError"}}function Tf($,f){return $ instanceof N2&&$.code==="hub_command_timeout"&&(f===void 0||$.command===f)}function XW($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=P9($.toString());return J?WW.get(J):void 0}function YF($){try{let J=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function P9($){if(!YF($))return;let f=new URL(d$($));return f.search="",f.hash="",f.toString()}function G9($){let f=P9($);return!!f&&jW.has(f)}function c$($,f){let J=P9($);if(J){if(jW.add(J),f?.trim())WW.set(J,f)}return $}class a0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new O0("hub_connection_closed",B9);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),f=this.options.authToken?.trim()||XW($);$.hash="";let Q=new(oK())($.toString(),f?[`${QF}${f}`]:void 0);this.socket=Q;let Z=!1;this.connectPromise=new Promise((W,j)=>{let X=!1,H=setTimeout(()=>{if(X)return;X=!0,Z=!0,this.lastCloseError=new O0("hub_connect_timeout",`Timed out connecting to hub after ${JW}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}j(this.lastCloseError)},JW);Q.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(H),W()}),Q.addEventListener("error",(Y)=>{if(X)return;X=!0,clearTimeout(H),this.lastCloseError=$F(Y,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),Q.addEventListener("close",(Y)=>{if(X)return;if(X=!0,clearTimeout(H),!Z)this.lastCloseError=$W(Y),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),Q.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(ZW(W)))}),Q.addEventListener("close",(W)=>{if(this.socket!==Q)return;if(!Z)this.lastCloseError=$W(W),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let W of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(W));this.reconnectAttempt=0}subscribe($,f){let J=f?.sessionId?.trim()||void 0,Q={listener:$,sessionId:J};return this.listeners.add(Q),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(J,-1)}}async command($,f,J,Q){let Z=0,W=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,f,J,Q)}catch(j){if(!W||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce($,f,J,Q){await this.connect();let Z=tK("hubreq_"),W=sK($,Q?.timeoutMs),j=new Promise((H,Y)=>{let V=W===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;Y(new N2($,"hub_command_timeout",`Hub command ${$} timed out after ${W}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},W);this.pendingReplies.set(Z,{resolve:(A)=>{if(V)clearTimeout(V);H(A)},reject:(A)=>{if(V)clearTimeout(V);Y(A)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:W,payload:f}})}catch(H){throw this.pendingReplies.delete(Z),H}let X=await j;if(!X.ok)throw new N2($,X.error?.code,X.error?.message??`Hub command ${$} failed`);return X}async recoverLocalHubTransport($){if(!G9(this.currentUrl)||!F9($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let f=await _1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!f)return!1;return this.currentUrl=f,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(XF*2**this.reconnectAttempt,HF),f=Math.round($*(1-QW)+Math.random()*$*QW);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},f)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!G9(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await _1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!$)return;this.lastCloseError=new O0("hub_connection_closed",B9),this.sawSocketClose=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new O0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,f){this.sendFrame({kind:$,clientId:this.clientId,...f?{sessionId:f}:{}})}adjustSubscriptionCount($,f){let J=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(J)??0)+f;if(Q<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(f<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(J,Q),f>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??fW}subscriptionSessionIdFromKey($){return $===fW?void 0:$}handleFrame($){switch($.kind){case"reply":{let f=$.envelope.requestId;if(!f)return;let J=this.pendingReplies.get(f);if(!J)return;this.pendingReplies.delete(f),J.resolve($.envelope);return}case"event":for(let f of this.listeners){if(f.sessionId&&f.sessionId!==$.envelope.sessionId?.trim())continue;f.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function d$($){let f=new URL($);if(f.protocol==="http:")f.protocol="ws:";else if(f.protocol==="https:")f.protocol="wss:";return f.toString()}async function J$($,f){let J=new a0({url:$,authToken:f?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function K9($,f){let J=d$($),Q=await G0(J);if(!Q)return{status:"unreachable",url:J};let Z=u$(),W=Q.buildId?.trim();if(!W||W!==Z)return{status:"build_mismatch",url:J};if(f?.verifyConnection===!0&&!await J$(J,{workspaceRoot:f.workspaceRoot,cwd:f.cwd,authToken:f.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function VF($){let f=Date.now()+fF;while(Date.now()<f){let J=await V0($.discoveryPath);if(J?.url){let Q=await K9(J.url,{verifyConnection:!0,authToken:J.authToken});if(Q.status==="compatible")return c$(Q.url,J.authToken)}await new Promise((Q)=>setTimeout(Q,JF))}return}async function AF($){let f=Date.now()+WF;while(Date.now()<f){if(!(await G0($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,jF))}return!1}function BF($,f){try{return d$($)===d$(f)}catch{return!1}}function GF($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let Q=J;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function KF($,f,J){let Q=new a0({url:$,authToken:f,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await Q.command("session.list",{limit:500},void 0,{timeoutMs:ZF});return!GF(Z.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function s8($={}){if($.endpoint?.trim()){let Z=await K9($.endpoint);return Z.status==="compatible"?Z.url:void 0}let f=K0(),J=await V0(f.discoveryPath);if(!J?.url)return;let Q=await K9(J.url);if(Q.status==="compatible")return c$(Q.url,J.authToken);if(Q.status==="build_mismatch")await k0(f.discoveryPath).catch(()=>{return});return}async function _1($={}){let f=await s8($);if(f&&await J$(f,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return f;if($.endpoint?.trim())return;let J=K0();return await _2($.workspaceRoot??process.cwd()),await VF(J)}async function t8($,f){let J=new URL($),Q=f?.trim()||XW(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function U9(){let $=K0(),f=await V0($.discoveryPath);if(!f?.url)return!1;try{if(await t8(f.url,f.authToken))return!0}catch{}return!1}async function Mf($){if(!G9($.url))return;let f=K0(),J=await V0(f.discoveryPath);if(!J?.url||!BF(J.url,$.url))return;if(!await KF(J.url,J.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await U9())return;if(!await AF(J.url))return;return await k0(f.discoveryPath).catch(()=>{return}),await _1({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}function FF($,f){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let J=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(J?`Failed to connect to hub at ${f} (${J} event before socket open).`:`Failed to connect to hub at ${f}.`)}var PF="cline-hub-auth.";function UF($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function DF($,f){let J=new URL($),Q=new URL(f);return J.search="",J.hash="",Q.search="",Q.hash="",J.toString()===Q.toString()}async function RF($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=K0(),Q=await V0(J.discoveryPath);if(Q?.url&&DF($.toString(),Q.url))return Q.authToken;return}async function D9($={}){let f=f$($);if(!UF($)){let J=K0(),Q=await V0(J.discoveryPath);if(Q?.url)return Q.url}return n0(f.host,f.port,f.pathname)}async function qf($){return await new Promise((f,J)=>{(async()=>{let Q=new URL($),Z=await RF(Q);Q.hash="";let W=new WebSocket(Q.toString(),Z?[`${PF}${Z}`]:void 0),j=new Map,X=0;W.addEventListener("open",()=>{f({send(H){let Y=H.requestId??`hub-client-${++X}`;return new Promise((V,A)=>{j.set(Y,{resolve:V,reject:A});let B={kind:"command",envelope:{...H,requestId:Y}};W.send(JSON.stringify(B))})},close(){W.close()}})}),W.addEventListener("message",(H)=>{let Y=JSON.parse(String(H.data));if(Y.kind==="reply"&&Y.envelope.requestId){let V=j.get(Y.envelope.requestId);if(V)j.delete(Y.envelope.requestId),V.resolve(Y.envelope)}}),W.addEventListener("close",()=>{for(let H of j.values())H.reject(Error("Hub connection closed"));j.clear()}),W.addEventListener("error",(H)=>{J(FF(H,$))})})().catch(J)})}async function HW($){try{return(await qf($)).close(),!0}catch{return!1}}async function YW($,f){let J=await D9($),Q=await qf(J);try{return await Q.send({version:f.version??"v1",clientId:f.clientId??"hub-client",...f})}finally{Q.close()}}function R9($){return $?JSON.parse(JSON.stringify($)):{}}function yf($){let f=$?.session&&typeof $.session==="object"?$.session:void 0;if(!f)return;let J=f.metadata&&typeof f.metadata==="object"?R9(f.metadata):void 0;return{sessionId:typeof f.sessionId==="string"?f.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function VW($,f){return $.error?.message??`hub command failed: ${f}`}function LF($){let f=R9($);if(typeof f.error==="string"&&f.error.trim())return{...f,error:f.error.trim()};let J=f.result&&typeof f.result==="object"?f.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...f,error:J.text.trim()};let Q=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...f,error:Q.message.trim()};return f}function AW($){let f=$?.sessionId;return typeof f==="string"&&f.trim()?f.trim():void 0}function OF($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))throw Error("hub checkpoint restore returned no checkpoint");let J=f;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function zF($){let f=R9($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||AW(f)||"",eventType:"schedule.execution.completed",payload:f};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||AW(f)||"",eventType:"schedule.execution.failed",payload:f};let J=$.sessionId?.trim();if(!J)return;switch($.event){case"iteration.started":return{sessionId:J,eventType:"runtime.chat.iteration_start",payload:f};case"iteration.finished":return{sessionId:J,eventType:"runtime.chat.iteration_end",payload:f};case"assistant.delta":return{sessionId:J,eventType:"runtime.chat.text_delta",payload:f};case"usage.updated":return{sessionId:J,eventType:"runtime.chat.usage",payload:f};case"tool.started":return{sessionId:J,eventType:"runtime.chat.tool_call_start",payload:f};case"tool.finished":return{sessionId:J,eventType:"runtime.chat.tool_call_end",payload:f};case"approval.requested":return{sessionId:J,eventType:"approval.requested",payload:f};case"run.aborted":return{sessionId:J,eventType:"runtime.chat.aborted",payload:f};case"run.failed":return{sessionId:J,eventType:"runtime.chat.failed",payload:LF($.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:f};default:return}}class L9{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new a0({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let f=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),J=yf(f.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession($,f,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:f.prompt,mode:f.config.mode,attachments:f.attachments,delivery:f.delivery,timeoutSeconds:f.config.timeoutSeconds},$,J)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let f=await this.client.command("session.get",void 0,$);return yf(f.payload)}async readMessages($){let f=$.trim();if(!f)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw Error(VW(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,Z=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},f);if(!Z.ok)throw Error(VW(Z,"session.restore"));let W=yf(Z.payload);if(J&&!W?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,X=OF(Z.payload);return{sessionId:W?.sessionId,startResult:W?.sessionId?{sessionId:W.sessionId,manifestPath:"",messagesPath:W.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let f=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(f.payload?.sessions)?f.payload?.sessions:[]).map((Q)=>yf({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,f=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:f})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,f){let J=new Set(($.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),Q=this.client.subscribe((Z)=>{let W=zF(Z);if(!W)return;if(J.size>0&&!J.has(W.sessionId))return;f.onEvent?.(W)});return this.ensureMetadataApplied().catch((Z)=>{f.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}streamTeamProgress($,f){let J=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;f.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{f.onError?.(Q instanceof Error?Q:Error(String(Q)))}),J}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.list");return Array.isArray(f.payload?.schedules)?f.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...f})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,f){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:$,limit:f});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(f.payload?.upcoming)?f.payload?.upcoming:[]}}class O9{client;constructor($){this.client=new a0({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let f=await this.client.command("session.list",{limit:$});return Array.isArray(f.payload?.sessions)?f.payload.sessions:[]}subscribeUI($){return this.client.subscribe((f)=>{switch(f.event){case"ui.notify":$.onNotify?.(f.payload);break;case"ui.show_window":$.onShowWindow?.(f.payload);break;case"hub.client.registered":$.onClientRegistered?.(f.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(f.payload??{});break;case"session.created":$.onSessionCreated?.(f.payload??{});break;case"session.updated":$.onSessionUpdated?.(f.payload??{});break;case"session.detached":$.onSessionDetached?.(f.payload??{});break}})}}import{normalizeProviderId as aq}from"@cline/llms";var MA={};y(MA,{LocalRuntimeHost:()=>B$});import{readdirSync as vq}from"node:fs";import{homedir as uq}from"node:os";import{isAbsolute as cq,join as cZ,resolve as dZ}from"node:path";import{captureSdkError as X2,createSessionId as dq,isLikelyAuthError as lq,normalizeUserInput as pq}from"@cline/shared";import{setHomeDirIfUnset as rq}from"@cline/shared/storage";L0();var xW={};y(xW,{createContextCompactionPrepareTurn:()=>Q4});import{createHandlerAsync as qF}from"@cline/llms";import{estimateTokens as z9}from"@cline/shared";var KW=200000,_9=0.9,FW=16384,N9=20000,BW=1024,GW=2000,PW=2000,UW=8;function l$($,f){if($.length<=f)return $;return`${$.slice(0,f)}
|
|
280
|
-
...[truncated ${$.length-f} chars]`}function
|
|
277
|
+
WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,f,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,f){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(f,K0(),$)}attachReportPathToRun($,f){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(f,K0(),$)}}function K4($){return $?new Date($).getTime():void 0}function XG($){let f=$.metadata?{...$.metadata}:void 0;if(f)delete f.__hubScheduleCreatedBy,delete f.__hubScheduleCwd,delete f.__hubRuntimeOptions;return f}function B4($){let f=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof f?.__hubScheduleCwd==="string"?f.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:K4($.nextRunAt),lastRunAt:K4($.lastRunAt),createdBy:typeof f?.__hubScheduleCreatedBy==="string"?f.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:f?.__hubRuntimeOptions&&typeof f.__hubRuntimeOptions==="object"&&!Array.isArray(f.__hubRuntimeOptions)?f.__hubRuntimeOptions:void 0,metadata:XG($)}}function YG($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function TW($,f){return{executionId:$.runId,scheduleId:f,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:K4($.startedAt),endedAt:K4($.completedAt),status:YG($.status),errorMessage:$.error}}class qf{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new s2({dbPath:$.dbPath}),this.materializer=new l2({store:this.store}),this.runner=new i2({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,eventPublisher:$.eventPublisher,workspaceRoot:"",logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule($){if(LW($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return B4(this.store.createHubSchedule($))}getSchedule($){let f=this.store.getHubSchedule($);return f?B4(f):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((f)=>B4(f))}updateSchedule($,f){if(f.cronPattern!==void 0)LW(f.cronPattern);let J=this.store.getHubSchedule($);if(!J)return;let W=f.workspaceRoot!==void 0?f.workspaceRoot.trim():J.workspaceRoot;if((f.enabled??J.enabled)&&!W)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule($,{...f,scheduleId:$});return Q?B4(Q):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;await this.runner.tick();let J=this.store.getRun(f.runId)??f;return TW(J,$)}triggerScheduleNowDetached($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;return this.runner.tick().catch(()=>{return}),TW(f,$)}listScheduleExecutions($){let f=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,J={specId:f?.specId,limit:$.limit};return this.store.listRuns(J).map((Z)=>{let Q=f??this.store.getSpec(Z.specId);if(!Q||Q.source!=="hub-schedule")return;return TW(Z,Q.externalId)}).filter((Z)=>{if(!Z)return!1;return!$.status||Z.status===$.status})}getScheduleStats($){let f=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(f.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,W=0,Z=0,Q;for(let j of f){if(j.status==="success"||j.status==="completed")J+=1;if(!Q&&j.status!=="success"&&j.status!=="completed")Q=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,W+=1}return{totalRuns:f.length,successRate:J/f.length,avgDurationSeconds:W>0?Z/W/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let f=this.store.getSpec($.specId);if(!f||f.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:f.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:f.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+f.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let f={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(f).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,W)=>String(J.nextRunAt).localeCompare(String(W.nextRunAt))).slice(0,$).map(({spec:J,nextRunAt:W})=>({scheduleId:J.externalId,name:J.title,nextRunAt:W}))}}m4();import{createSessionId as iP,resolveHubCommandTimeoutMs as nP}from"@cline/shared";var _3={};w(_3,{splitCoreSessionConfig:()=>X8,isSessionNotFoundError:()=>y$,SessionNotFoundError:()=>M$,SESSION_NOT_FOUND_ERROR_CODE:()=>C1});var C1="session_not_found";class M$ extends Error{sessionId;code="session_not_found";constructor($,f){super(f??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function y$($){return $ instanceof M$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function X8($){let{hooks:f,logger:J,telemetry:W,extensionContext:Z,extraTools:Q,extensions:j,onTeamEvent:H,onConsecutiveMistakeLimitReached:X,checkpoint:Y,compaction:A,...V}=$,B={};if(f)B.hooks=f;if(J)B.logger=J;if(W)B.telemetry=W;if(Z)B.extensionContext=Z;if(Q)B.extraTools=Q;if(j)B.extensions=j;if(H)B.onTeamEvent=H;if(X)B.onConsecutiveMistakeLimitReached=X;if(Y?.createCheckpoint)B.checkpoint=Y;if(A?.compact)B.compaction=A;let K=Object.keys(B).length>0?B:void 0;return{config:{...V,...Y?{checkpoint:{enabled:Y.enabled}}:{},...A?{compaction:{enabled:A.enabled,strategy:A.strategy,thresholdRatio:A.thresholdRatio,reserveTokens:A.reserveTokens,preserveRecentTokens:A.preserveRecentTokens,maxInputTokens:A.maxInputTokens,summarizer:A.summarizer}}:{}},...K?{localRuntime:K}:{}}}import{spawn as NP}from"node:child_process";import{closeSync as MP,mkdirSync as yP,openSync as qP}from"node:fs";import{basename as wP,dirname as SP,join as hP}from"node:path";import{fileURLToPath as CP}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as EP,isHubDaemonProcess as k3,withResolvedClineBuildEnv as bP}from"@cline/shared";import{createHash as ZP,randomBytes as QP}from"node:crypto";import{existsSync as jP}from"node:fs";import{chmod as HP,mkdir as wW,readFile as y3,rm as SW,writeFile as q3}from"node:fs/promises";import{dirname as w3,join as hW}from"node:path";import{resolveClineDataDir as A8,resolveClineDir as S3}from"@cline/shared/storage";var T3="0.0.43";var Y8={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:T3,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var XP="CLINE_HUB_DISCOVERY_PATH",YP="CLINE_HUB_BUILD_ID",N3=30000,AP=15000,VP=100;function BP($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function KP($){return ZP("sha256").update($).digest("hex").slice(0,12)}function GP($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f?String(f.code)==="EPERM":!1}}function g4(){return QP(32).toString("hex")}function PP($){return new Promise((f)=>setTimeout(f,$))}function FP($){return`${$}.lock`}async function UP($){try{let f=JSON.parse(await y3(hW($,"owner.json"),"utf8"));if(typeof f.pid!=="number"||typeof f.acquiredAt!=="string")return;return{pid:f.pid,acquiredAt:f.acquiredAt}}catch{return}}async function M3($){await SW($,{recursive:!0,force:!0}).catch(()=>{return})}function t$(){return process.env[YP]?.trim()||String(Y8.version)}function q$($=process.argv[1]?.trim()||process.cwd()){let f=`hub-${KP($)}`,J=process.env[XP]?.trim()||hW(A8(),"locks","hub","owners",`${BP(f)}.json`);return{ownerId:f,discoveryPath:J}}function h3($=`hub-${Date.now().toString(36)}`){return q$($)}async function V0($){try{let f=JSON.parse(await y3($,"utf8"));if(typeof f.hubId!=="string"||typeof f.protocolVersion!=="string"||typeof f.authToken!=="string"||typeof f.host!=="string"||typeof f.port!=="number"||typeof f.url!=="string"||typeof f.startedAt!=="string"||typeof f.updatedAt!=="string")return;return{hubId:f.hubId,protocolVersion:f.protocolVersion,coreVersion:typeof f.coreVersion==="string"?f.coreVersion:void 0,buildId:typeof f.buildId==="string"?f.buildId:void 0,authToken:f.authToken,host:f.host,port:f.port,url:f.url,pid:typeof f.pid==="number"?f.pid:void 0,startedAt:f.startedAt,updatedAt:f.updatedAt}}catch{return}}async function v4($,f){await wW(w3($),{recursive:!0}),await SW($,{force:!0}).catch(()=>{return}),await q3($,`${JSON.stringify(f,null,2)}
|
|
278
|
+
`,{encoding:"utf8",mode:384}),await HP($,384)}async function b0($){await SW($,{force:!0}).catch(()=>{return})}async function u4($,f){let J=FP($);await wW(w3(J),{recursive:!0});let W=Date.now()+AP;while(!0)try{await wW(J,{recursive:!1}),await q3(hW(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
279
|
+
`,"utf8");try{return await f()}finally{await M3(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await UP(J),H=j?Date.now()-Date.parse(j.acquiredAt):N3+1;if(!j||!GP(j.pid)||H>N3){await M3(J);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${J}`);await PP(VP)}}async function Q$($){try{let f=await fetch(CW($));if(!f.ok)return;return await f.json()}catch{return}}function t0($,f,J="/hub"){return new URL(`ws://${$}:${f}${J}`).toString()}function CW($){let f=new URL($);return f.protocol=f.protocol==="wss:"?"https:":"http:",f.pathname="/health",f.search="",f.toString()}function C3($){return jP($)}import{CLINE_HUB_DEV_PORT as RP,CLINE_HUB_PORT as DP,resolveClineBuildEnv as LP}from"@cline/shared";var OP="CLINE_HUB_HOST",_P="CLINE_HUB_PORT",zP="CLINE_HUB_PATHNAME",EW="127.0.0.1",bW=DP,kW="/hub";function E3($){return LP($)==="development"?RP:bW}function IW($={}){return($.env??process.env)[OP]?.trim()||EW}function Ef($={}){let J=($.env??process.env)[_P]?.trim();if(!J)return E3($);let W=Number.parseInt(J,10);if(!Number.isInteger(W)||W<1||W>65535)return E3($);return W}function xW($={}){return($.env??process.env)[zP]?.trim()||kW}function j$($={},f={}){return{host:$.host??IW(f),port:$.port??Ef(f),pathname:$.pathname??xW(f)}}var TP="shared:cline";function b3($){let f=L$($.trim());return q$(`workspace:${f||$.trim()}`)}function G0($=TP){return q$($)}var kP=8000,IP=200,xP=3000,mP=100,gP=[100,250,500,1000,2000],vP="--cline-hub-daemon";function uP($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function cP(){try{let $=hP(A8(),"logs","hub-daemon.log");return yP(SP($),{recursive:!0}),{fd:qP($,"a"),logPath:$}}catch{return}}function V8($){let f=$.buildId?.trim();return!!f&&f===t$()}async function E1($){try{return await Q$($)}catch{return}}async function dP($,f){let J=Date.now()+f;while(Date.now()<J){if(!(await E1($))?.url)return!0;await new Promise((Z)=>setTimeout(Z,mP))}return!1}async function B8($,f){if(V8($))return;if(await K8($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}await dP($.url,xP),await b0(f).catch(()=>{return})}function lP(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return CP(new URL(`./entry.${$}`,import.meta.url))}function pP($,f){let J=lP(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let Z=wP(W).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),H=Q?[vP]:[...j?["--conditions=development"]:[],J];return{launcher:W,args:[...H,"--cwd",$,...uP(f)],cwd:$,env:{...bP(process.env),CLINE_NO_INTERACTIVE:"1",[EP]:"1"}}}function rP($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let J="message"in $?$.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function mW($,f={}){if(k3())return;let J=pP($,f),W=cP();try{NP(J.launcher,J.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(W)MP(W.fd)}}async function bf($,f={}){for(let J=0;;J++)try{mW($,f);return}catch(W){let Z=gP[J];if(!rP(W)||Z===void 0)throw W;await new Promise((Q)=>setTimeout(Q,Z))}}function c4($,f={}){if(k3())return;let J=G0(),W=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=j$(f),Q=t0(Z.host,Z.port,Z.pathname);V0(J.discoveryPath).then(async(j)=>{if(j?.url){let A=await E1(j.url);if(A?.url&&V8(A)&&await H$(A.url,{authToken:j.authToken}))return;if(A?.url)await B8({...A,authToken:j.authToken},J.discoveryPath);else await b0(J.discoveryPath).catch(()=>{return})}let H=await E1(Q);if(H?.url)await B8(H,J.discoveryPath);let Y=!W&&Z.port!==0?{...Z,port:0}:Z;await bf($,Y)}).catch(()=>{})}async function I3($,f={}){let J=G0(),W=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=j$(f),j=t0(Q.host,Q.port,Q.pathname),H=(K)=>{if(!W)s$(K.url,K.authToken);return K},X=await V0(J.discoveryPath);if(X?.url){let K=await E1(X.url);if(K?.url&&V8(K)&&await H$(K.url,{authToken:X.authToken}))return H({url:K.url,authToken:X.authToken});if(K?.url)await B8({...K,authToken:X.authToken},J.discoveryPath);else await b0(J.discoveryPath).catch(()=>{return})}let Y=await E1(j);if(Y?.url)await B8(Y,J.discoveryPath);let V=!Z&&Q.port!==0?{...Q,port:0}:Q;await bf($,V);let B=Date.now()+kP;while(Date.now()<B){let K=await V0(J.discoveryPath);if(K?.url){let R=await E1(K.url);if(R?.url&&V8(R)&&await H$(R.url,{authToken:K.authToken}))return H({url:R.url,authToken:K.authToken})}let G=await E1(j);if(G?.url&&!V8(G))await B8(G,J.discoveryPath);await new Promise((R)=>setTimeout(R,IP))}throw Error("Timed out waiting for detached hub startup.")}function aP(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function u3($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return u3($.data);return String($)}function tP($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function x3($){let f=$,J=tP(f.reason);return new O0("hub_connection_closed",f.code||J?`Hub connection closed (code=${f.code??0}${J?`, reason=${J}`:""})`:gW,{closeCode:f.code,closeReason:J||void 0})}function sP($,f){if($ instanceof O0)return $;if($ instanceof Error)return new O0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new O0("hub_connect_failed",$.error.message);let J=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(J)return new O0("hub_connect_failed",J);let W=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new O0("hub_connect_failed",W?`Failed to connect to hub at ${f.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${f.toString()}.`)}var oP=8000,eP=200,m3="*",g3=8000,$F="cline-hub-auth.",c3=new Map,d3=new Set,fF=3000,JF=3000,WF=100,gW="Hub connection closed",ZF=250,QF=5000,v3=0.5;class O0 extends Error{code;details;constructor($,f,J){super(f);this.code=$;this.details=J;this.name="HubTransportError"}}function cW($){return $ instanceof O0}class kf extends Error{command;code;constructor($,f,J){super(J);this.command=$;this.code=f;this.name="HubCommandError"}}function d4($,f){return $ instanceof kf&&$.code==="hub_command_timeout"&&(f===void 0||$.command===f)}function l3($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=dW($.toString());return J?c3.get(J):void 0}function jF($){try{let J=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function dW($){if(!jF($))return;let f=new URL(o$($));return f.search="",f.hash="",f.toString()}function vW($){let f=dW($);return!!f&&d3.has(f)}function s$($,f){let J=dW($);if(J){if(d3.add(J),f?.trim())c3.set(J,f)}return $}class s0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new O0("hub_connection_closed",gW);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),f=this.options.authToken?.trim()||l3($);$.hash="";let W=new(aP())($.toString(),f?[`${$F}${f}`]:void 0);this.socket=W;let Z=!1;this.connectPromise=new Promise((Q,j)=>{let H=!1,X=setTimeout(()=>{if(H)return;H=!0,Z=!0,this.lastCloseError=new O0("hub_connect_timeout",`Timed out connecting to hub after ${g3}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}j(this.lastCloseError)},g3);W.addEventListener("open",()=>{if(H)return;H=!0,clearTimeout(X),Q()}),W.addEventListener("error",(Y)=>{if(H)return;H=!0,clearTimeout(X),this.lastCloseError=sP(Y,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),W.addEventListener("close",(Y)=>{if(H)return;if(H=!0,clearTimeout(X),!Z)this.lastCloseError=x3(Y),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),W.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(u3(Q)))}),W.addEventListener("close",(Q)=>{if(this.socket!==W)return;if(!Z)this.lastCloseError=x3(Q),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe($,f){let J=f?.sessionId?.trim()||void 0,W={listener:$,sessionId:J};return this.listeners.add(W),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(W))return;this.adjustSubscriptionCount(J,-1)}}async command($,f,J,W){let Z=0,Q=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,f,J,W)}catch(j){if(!Q||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce($,f,J,W){await this.connect();let Z=iP("hubreq_"),Q=nP($,W?.timeoutMs),j=new Promise((X,Y)=>{let A=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;Y(new kf($,"hub_command_timeout",`Hub command ${$} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(Z,{resolve:(V)=>{if(A)clearTimeout(A);X(V)},reject:(V)=>{if(A)clearTimeout(A);Y(V)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:f}})}catch(X){throw this.pendingReplies.delete(Z),X}let H=await j;if(!H.ok){if(H.error?.code===C1){let X=J??(typeof f?.sessionId==="string"?f.sessionId:void 0);throw new M$(X,H.error.message)}throw new kf($,H.error?.code,H.error?.message??`Hub command ${$} failed`)}return H}async recoverLocalHubTransport($){if(!vW(this.currentUrl)||!cW($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let f=await b1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!f)return!1;return this.currentUrl=f,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(ZF*2**this.reconnectAttempt,QF),f=Math.round($*(1-v3)+Math.random()*$*v3);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},f)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!vW(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await b1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!$)return;this.lastCloseError=new O0("hub_connection_closed",gW),this.sawSocketClose=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new O0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,f){this.sendFrame({kind:$,clientId:this.clientId,...f?{sessionId:f}:{}})}adjustSubscriptionCount($,f){let J=this.subscriptionKeyForSessionId($),W=(this.subscriptionCounts.get(J)??0)+f;if(W<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(f<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(J,W),f>0&&W===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??m3}subscriptionSessionIdFromKey($){return $===m3?void 0:$}handleFrame($){switch($.kind){case"reply":{let f=$.envelope.requestId;if(!f)return;let J=this.pendingReplies.get(f);if(!J)return;this.pendingReplies.delete(f),J.resolve($.envelope);return}case"event":for(let f of this.listeners){if(f.sessionId&&f.sessionId!==$.envelope.sessionId?.trim())continue;f.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function o$($){let f=new URL($);if(f.protocol==="http:")f.protocol="ws:";else if(f.protocol==="https:")f.protocol="wss:";return f.toString()}async function H$($,f){let J=new s0({url:$,authToken:f?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function uW($,f){let J=o$($),W=await Q$(J);if(!W)return{status:"unreachable",url:J};let Z=t$(),Q=W.buildId?.trim();if(!Q||Q!==Z)return{status:"build_mismatch",url:J};if(f?.verifyConnection===!0&&!await H$(J,{workspaceRoot:f.workspaceRoot,cwd:f.cwd,authToken:f.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function HF($){let f=Date.now()+oP;while(Date.now()<f){let J=await V0($.discoveryPath);if(J?.url){let W=await uW(J.url,{verifyConnection:!0,authToken:J.authToken});if(W.status==="compatible")return s$(W.url,J.authToken)}await new Promise((W)=>setTimeout(W,eP))}return}async function XF($){let f=Date.now()+JF;while(Date.now()<f){if(!(await Q$($).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,WF))}return!1}function YF($,f){try{return o$($)===o$(f)}catch{return!1}}function AF($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let W=J;if(W.status==="running"||W.status==="idle"||W.status==="pending")return!0;return Array.isArray(W.participants)&&W.participants.length>0})}async function VF($,f,J){let W=new s0({url:$,authToken:f,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await W.command("session.list",{limit:500},void 0,{timeoutMs:fF});return!AF(Z.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function G8($={}){if($.endpoint?.trim()){let Z=await uW($.endpoint);return Z.status==="compatible"?Z.url:void 0}let f=G0(),J=await V0(f.discoveryPath);if(!J?.url)return;let W=await uW(J.url);if(W.status==="compatible")return s$(W.url,J.authToken);if(W.status==="build_mismatch")await b0(f.discoveryPath).catch(()=>{return});return}async function b1($={}){let f=await G8($);if(f&&await H$(f,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return f;if($.endpoint?.trim())return;let J=G0();return await bf($.workspaceRoot??process.cwd()),await HF(J)}async function K8($,f){let J=new URL($),W=f?.trim()||l3(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:W?{authorization:`Bearer ${W}`}:void 0})).ok}async function lW(){let $=G0(),f=await V0($.discoveryPath);if(!f?.url)return!1;try{if(await K8(f.url,f.authToken))return!0}catch{}return!1}async function l4($){if(!vW($.url))return;let f=G0(),J=await V0(f.discoveryPath);if(!J?.url||!YF(J.url,$.url))return;if(!await VF(J.url,J.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await lW())return;if(!await XF(J.url))return;return await b0(f.discoveryPath).catch(()=>{return}),await b1({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}function BF($,f){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let J=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(J?`Failed to connect to hub at ${f} (${J} event before socket open).`:`Failed to connect to hub at ${f}.`)}var KF="cline-hub-auth.";function GF($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function PF($,f){let J=new URL($),W=new URL(f);return J.search="",J.hash="",W.search="",W.hash="",J.toString()===W.toString()}async function FF($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=G0(),W=await V0(J.discoveryPath);if(W?.url&&PF($.toString(),W.url))return W.authToken;return}async function pW($={}){let f=j$($);if(!GF($)){let J=G0(),W=await V0(J.discoveryPath);if(W?.url)return W.url}return t0(f.host,f.port,f.pathname)}async function p4($){return await new Promise((f,J)=>{(async()=>{let W=new URL($),Z=await FF(W);W.hash="";let Q=new WebSocket(W.toString(),Z?[`${KF}${Z}`]:void 0),j=new Map,H=0;Q.addEventListener("open",()=>{f({send(X){let Y=X.requestId??`hub-client-${++H}`;return new Promise((A,V)=>{j.set(Y,{resolve:A,reject:V});let B={kind:"command",envelope:{...X,requestId:Y}};Q.send(JSON.stringify(B))})},close(){Q.close()}})}),Q.addEventListener("message",(X)=>{let Y=JSON.parse(String(X.data));if(Y.kind==="reply"&&Y.envelope.requestId){let A=j.get(Y.envelope.requestId);if(A)j.delete(Y.envelope.requestId),A.resolve(Y.envelope)}}),Q.addEventListener("close",()=>{for(let X of j.values())X.reject(Error("Hub connection closed"));j.clear()}),Q.addEventListener("error",(X)=>{J(BF(X,$))})})().catch(J)})}async function p3($){try{return(await p4($)).close(),!0}catch{return!1}}async function r3($,f){let J=await pW($),W=await p4(J);try{return await W.send({version:f.version??"v1",clientId:f.clientId??"hub-client",...f})}finally{W.close()}}function rW($){return $?JSON.parse(JSON.stringify($)):{}}function r4($){let f=$?.session&&typeof $.session==="object"?$.session:void 0;if(!f)return;let J=f.metadata&&typeof f.metadata==="object"?rW(f.metadata):void 0;return{sessionId:typeof f.sessionId==="string"?f.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function i3($,f){return $.error?.message??`hub command failed: ${f}`}function UF($){let f=rW($);if(typeof f.error==="string"&&f.error.trim())return{...f,error:f.error.trim()};let J=f.result&&typeof f.result==="object"?f.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...f,error:J.text.trim()};let W=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof W?.message==="string"&&W.message.trim())return{...f,error:W.message.trim()};return f}function n3($){let f=$?.sessionId;return typeof f==="string"&&f.trim()?f.trim():void 0}function RF($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))throw Error("hub checkpoint restore returned no checkpoint");let J=f;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function DF($){let f=rW($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||n3(f)||"",eventType:"schedule.execution.completed",payload:f};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||n3(f)||"",eventType:"schedule.execution.failed",payload:f};let J=$.sessionId?.trim();if(!J)return;switch($.event){case"iteration.started":return{sessionId:J,eventType:"runtime.chat.iteration_start",payload:f};case"iteration.finished":return{sessionId:J,eventType:"runtime.chat.iteration_end",payload:f};case"assistant.delta":return{sessionId:J,eventType:"runtime.chat.text_delta",payload:f};case"usage.updated":return{sessionId:J,eventType:"runtime.chat.usage",payload:f};case"tool.started":return{sessionId:J,eventType:"runtime.chat.tool_call_start",payload:f};case"tool.finished":return{sessionId:J,eventType:"runtime.chat.tool_call_end",payload:f};case"approval.requested":return{sessionId:J,eventType:"approval.requested",payload:f};case"run.aborted":return{sessionId:J,eventType:"runtime.chat.aborted",payload:f};case"run.failed":return{sessionId:J,eventType:"runtime.chat.failed",payload:UF($.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:f};default:return}}class iW{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new s0({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let f=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),J=r4(f.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession($,f,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:f.prompt,mode:f.config.mode,attachments:f.attachments,delivery:f.delivery,timeoutSeconds:f.config.timeoutSeconds},$,J)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(y$(J))return;throw J}return r4(f.payload)}async readMessages($){let f=$.trim();if(!f)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw Error(i3(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async restore($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let W=$.config,Z=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.workspaceRoot,cwd:W.cwd,sessionConfig:{providerId:W.provider,modelId:W.model,apiKey:W.apiKey,cwd:W.cwd??W.workspaceRoot,workspaceRoot:W.workspaceRoot,systemPrompt:W.systemPrompt??"",mode:W.mode??"act",rules:W.rules,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawnAgent:W.enableSpawn!==!1,enableAgentTeams:W.enableTeams!==!1,disableMcpSettingsTools:W.disableMcpSettingsTools,missionLogIntervalSteps:W.missionStepInterval,missionLogIntervalMs:W.missionTimeIntervalMs},metadata:{source:W.source??"cli",provider:W.provider,model:W.model,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,prompt:void 0,interactive:W.interactive!==!1},runtimeOptions:{mode:W.mode,systemPrompt:W.systemPrompt,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,autoApproveTools:W.autoApproveTools,configExtensions:W.configExtensions},modelSelection:{provider:W.provider,model:W.model,apiKey:W.apiKey},toolPolicies:W.toolPolicies}:{}},f);if(!Z.ok)throw Error(i3(Z,"session.restore"));let Q=r4(Z.payload);if(J&&!Q?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,H=RF(Z.payload);return{sessionId:Q?.sessionId,startResult:Q?.sessionId?{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:H}}async listSessions($){await this.ensureMetadataApplied();let f=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(f.payload?.sessions)?f.payload?.sessions:[]).map((W)=>r4({session:W})).filter((W)=>Boolean(W?.sessionId))}async deleteSession($,f=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:f})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,f){let J=new Set(($.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),W=this.client.subscribe((Z)=>{let Q=DF(Z);if(!Q)return;if(J.size>0&&!J.has(Q.sessionId))return;f.onEvent?.(Q)});return this.ensureMetadataApplied().catch((Z)=>{f.onError?.(Z instanceof Error?Z:Error(String(Z)))}),W}streamTeamProgress($,f){let J=this.client.subscribe((W)=>{if(W.event!=="team.progress"||!W.payload)return;f.onProjection?.(W.payload)});return this.ensureMetadataApplied().catch((W)=>{f.onError?.(W instanceof Error?W:Error(String(W)))}),J}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.list");return Array.isArray(f.payload?.schedules)?f.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...f})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,f){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:$,limit:f});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(f.payload?.upcoming)?f.payload?.upcoming:[]}}class nW{client;constructor($){this.client=new s0({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let f=await this.client.command("session.list",{limit:$});return Array.isArray(f.payload?.sessions)?f.payload.sessions:[]}subscribeUI($){return this.client.subscribe((f)=>{switch(f.event){case"ui.notify":$.onNotify?.(f.payload);break;case"ui.show_window":$.onShowWindow?.(f.payload);break;case"hub.client.registered":$.onClientRegistered?.(f.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(f.payload??{});break;case"session.created":$.onSessionCreated?.(f.payload??{});break;case"session.updated":$.onSessionUpdated?.(f.payload??{});break;case"session.detached":$.onSessionDetached?.(f.payload??{});break}})}}import{normalizeProviderId as gw}from"@cline/llms";var _B={};w(_B,{LocalRuntimeHost:()=>U$});import{readdirSync as Sw}from"node:fs";import{homedir as hw}from"node:os";import{isAbsolute as Cw,join as N7,resolve as M7}from"node:path";import{captureSdkError as Df,createSessionId as Ew,isLikelyAuthError as bw,normalizeUserInput as kw}from"@cline/shared";import{setHomeDirIfUnset as Iw}from"@cline/shared/storage";L0();var Lj={};w(Lj,{createContextCompactionPrepareTurn:()=>L8});import{createHandlerAsync as TF}from"@cline/llms";import{estimateTokens as aW}from"@cline/shared";var s3=200000,tW=0.9,o3=16384,sW=20000,a3=1024,t3=2000,e3=2000,$j=8;function e$($,f){if($.length<=f)return $;return`${$.slice(0,f)}
|
|
280
|
+
...[truncated ${$.length-f} chars]`}function LF($){let f=oW($);if(typeof f==="string")return f;return f.map((J)=>{switch(J.type){case"text":return J.text;case"file":return`<file path="${J.path}">
|
|
281
281
|
${J.content}
|
|
282
282
|
</file>`;case"image":return`[image:${J.mediaType}]`;default:return""}}).join(`
|
|
283
|
-
`)}function
|
|
284
|
-
`)}function
|
|
283
|
+
`)}function oW($){if(typeof $==="string")return e$($,t3);return $.map((f)=>{switch(f.type){case"text":return{...f,text:e$(f.text,t3)};case"file":return{...f,content:e$(f.content,e3)};case"image":return f;default:return f}})}function OF($){return Object.entries($).map(([f,J])=>`${f}=${JSON.stringify(J)}`).join(", ")}function fj($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let f=[];for(let J of $.content)switch(J.type){case"text":f.push(`[${$.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":f.push(`[Bot thinking]: ${e$(J.thinking,2000)}`);break;case"redacted_thinking":f.push("[Bot thinking]: [redacted]");break;case"tool_use":f.push(`[Bot tool calls]: ${J.name}(${OF(J.input)})`);break;case"tool_result":f.push(`[Tool result]: ${LF(J.content)}`);break;case"file":f.push(`[${$.role==="user"?"User":"Bot"} file ${J.path}]: ${e$(J.content,e3)}`);break;case"image":f.push(`[${$.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return f.join(`
|
|
284
|
+
`)}function Jj($){return $.map(fj).join(`
|
|
285
285
|
|
|
286
|
-
`).trim()}function
|
|
287
|
-
`):"- none",J=$.modifiedFiles.length>0?$.modifiedFiles.map((
|
|
286
|
+
`).trim()}function Wj(){let $=new WeakMap;return(f)=>{let J=f,W=$.get(J);if(typeof W==="number")return W;let Z;try{Z=JSON.stringify(f)}catch{Z=fj(f)}let Q=aW(Z.length);return $.set(J,Q),Q}}function U8($){return $.metadata?.kind==="compaction_summary"}function eW($){if(!U8($))return;let f=$.metadata;if(!f)return;let J=f.details;return{kind:"compaction_summary",summary:String(f.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[]},tokensBefore:Number(f.tokensBefore??0),generatedAt:Number(f.generatedAt??0)}}function _F($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((f)=>f.type==="tool_result")}function R8($){return $.role==="user"&&!_F($)&&!U8($)}function Zj($){for(let f=0;f<$.length;f+=1)if(R8($[f]))return f;return-1}function i4($){for(let f=$.length-1;f>=0;f-=1)if(R8($[f]))return f;return 0}function Qj($){for(let f=$.length-1;f>=0;f-=1)if($[f].role==="assistant")return f;return-1}function jj($){for(let f=$.length-1;f>=0;f-=1)if(U8($[f]))return f;return-1}function Hj($,f,J){let W=i4($);if(W<=0)return 0;let Z=0,Q=$.length;for(let H=$.length-1;H>=0;H-=1)if(Z+=J($[H]),Q=H,Z>=f)break;if(Q<=0)return 0;let j=Math.min(Q,W);while(j>0&&!R8($[j]))j-=1;return j}function F8($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((f)=>F8(f));if($&&typeof $==="object"){let f=$,J=[];for(let W of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...F8(f[W]));if(Array.isArray(f.files)){for(let W of f.files)if(W&&typeof W==="object")J.push(...F8(W.path))}if(Array.isArray(f.file_paths))J.push(...F8(f.file_paths));return J}return[]}function P8($,f){let J=new Set($);for(let W of f){let Z=W.trim();if(!Z)continue;J.add(Z)}return[...J].sort((W,Z)=>W.localeCompare(Z))}function Xj($){let f=[],J=[];for(let W of $){let Z=eW(W);if(Z){f=P8(f,Z.details.readFiles),J=P8(J,Z.details.modifiedFiles);continue}if(!Array.isArray(W.content))continue;for(let Q of W.content){if(Q.type==="file"){f=P8(f,[Q.path]);continue}if(Q.type!=="tool_use")continue;let j=F8(Q.input);if(Q.name==="read_files"){f=P8(f,j);continue}if(Q.name==="editor"||Q.name==="apply_patch")J=P8(J,j)}}return{readFiles:f,modifiedFiles:J}}function zF($){let f=$.readFiles.length>0?$.readFiles.map((W)=>`- ${W}`).join(`
|
|
287
|
+
`):"- none",J=$.modifiedFiles.length>0?$.modifiedFiles.map((W)=>`- ${W}`).join(`
|
|
288
288
|
`):"- none";return`## Files
|
|
289
289
|
Read:
|
|
290
290
|
${f}
|
|
291
291
|
Modified:
|
|
292
|
-
${J}`}function
|
|
292
|
+
${J}`}function Yj($,f){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
|
|
293
293
|
|
|
294
|
-
${
|
|
294
|
+
${zF(f)}`.trim()}function Aj($){let f=[`Summarize this session for continuation. Be concise and factual.
|
|
295
295
|
|
|
296
296
|
## Goal
|
|
297
297
|
One sentence: what is being built or fixed.
|
|
@@ -313,11 +313,11 @@ Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.tr
|
|
|
313
313
|
${$.previousSummary.trim()}`);return f.push(`Conversation:
|
|
314
314
|
${$.conversationText||"(empty)"}`),f.join(`
|
|
315
315
|
|
|
316
|
-
`)}function
|
|
316
|
+
`)}function Vj($){let f=$.summarizer,J=(Z)=>{if(Z.providerId==="openai-codex"){let{maxOutputTokens:Q,...j}=Z;return{...j,thinking:!1}}return{...Z,maxOutputTokens:Z.maxOutputTokens??a3,thinking:!1}};if(!f)return J($.activeProviderConfig);let W=f.providerConfig?.providerId===f.providerId?f.providerConfig:void 0;return J({...W??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??W?.apiKey,baseUrl:f.baseUrl??W?.baseUrl,headers:f.headers??W?.headers,knownModels:f.knownModels??W?.knownModels,maxOutputTokens:f.maxOutputTokens??a3})}function Bj($){return{role:"user",content:`Context summary:
|
|
317
317
|
|
|
318
|
-
${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function yF($){let f=await qF($.providerConfig),J="";for await(let Q of f.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Q.type==="text"){J+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return $.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),J.trim()}function wF($){try{return JSON.stringify($).length}catch{return String($).length}}async function SW($){let f=$.context.messages;if(f.length<2)return;let J=NW(f,$.preserveRecentTokens,$.estimateMessageTokens);if(J<=0||J>=f.length)return;let Q=f.slice(0,J),Z=_W(Q),W=Z>=0?M9(Q[Z])?.summary:void 0,j=Z>=0?Q.slice(Z+1):Q;if(j.length===0)return;let X=TW(Q),H=RW(j),Y=qW({previousSummary:W,conversationText:H,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:j.length,preservedMessages:f.length-J,previousSummaryChars:W?.length??0,conversationTextChars:H.length,summaryRequestChars:Y.length,summaryRequestEstimatedTokens:z9(Y.length),newMessagesJsonChars:wF(j),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let V=await yF({providerConfig:yW({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:Y,logger:$.logger});if(!V.trim())return;let A=MW(V,X),B=f.reduce((D,F)=>D+$.estimateMessageTokens(F),0),G=[wW({summary:A,fileOps:X,tokensBefore:B}),...f.slice(J)],K=G.reduce((D,F)=>D+$.estimateMessageTokens(F),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:f.length,messagesAfter:G.length,messagesSummarized:J,messagesPreserved:f.length-J,tokensBefore:B,tokensAfter:K,maxInputTokens:$.context.maxInputTokens}),{messages:G}}function EW($){if($4($))return;if(typeof $.content==="string"){let J=$.content.trim();return J?{...$,content:J}:void 0}let f=$.content.filter((J)=>J.type!=="text"||J.text.trim());if(f.length===0)return;return{...$,content:f.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J.type==="tool_result"?{...J,content:T9(J.content)}:J)}}function J4($,f){return $.reduce((J,Q)=>J+f(Q),0)}function hW($,f){let J=Math.max(1,f),Q=Math.max(16,J*4);if(typeof $.content==="string"){let j=l$($.content,Q).trim();return{...$,content:j||"..."}}let Z=Q,W=$.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let X=l$(j.text,Z).trim();return Z-=X.length,{...j,text:X||"..."}});return{...$,content:W}}function SF($,f){let J=OW($),Q=wf($),Z=zW($),W=[];for(let j=0;j<$.length;j+=1){let X=EW($[j]);if(!X)continue;W.push({index:j,message:X,estimatedTokens:f(X),isFirstUser:j===J,isLastUser:j===Q,isLastAssistant:j===Z})}return W}function CW($,f,J,Q){let Z=$[f];Z.message=J,Z.estimatedTokens=Q(J)}function hF($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_use")f.add(J.id);return f}function CF($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_result")f.add(J.tool_use_id);return f}function bW($){return new Set([...hF($.message),...CF($.message)])}function EF($){let f=new Map;for(let J=0;J<$.length;J+=1)for(let Q of bW($[J])){let Z=f.get(Q);if(Z)Z.add(J);else f.set(Q,new Set([J]))}return f}function bF($,f){let J=EF($),Q=new Set,Z=[f];while(Z.length>0){let W=Z.shift();if(W===void 0||Q.has(W))continue;Q.add(W);for(let j of bW($[W]))for(let X of J.get(j)??[])if(!Q.has(X))Z.push(X)}return Q}function Sf($,f,J,Q){let Z=J4($.map((W)=>W.message),Q);for(let W=0;W<$.length&&Z>J;){if(!f($[W])){W+=1;continue}let j=bF($,W);Z-=Array.from(j).reduce((X,H)=>X+$[H].estimatedTokens,0);for(let X of Array.from(j).sort((H,Y)=>Y-H))$.splice(X,1)}}function kF($,f,J){let Q=J4($.map((W)=>W.message),J);if(Q<=f)return;for(let W=$.length-1;W>=0&&Q>f;W-=1){let j=$[W];if(j.isFirstUser)continue;let X=Math.max(UW,j.estimatedTokens-(Q-f));if(X>=j.estimatedTokens)continue;CW($,W,hW(j.message,X),J),Q=J4($.map((H)=>H.message),J)}if(Q<=f)return;let Z=$.findIndex((W)=>W.isFirstUser);if(Z>=0){let W=Math.max(1,$[Z].estimatedTokens-(Q-f));CW($,Z,hW($[Z].message,W),J)}}function IF($,f){return JSON.stringify($)!==JSON.stringify(f)}function xF($){let f=wf($);if(f<0||f===0&&!f4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,f),protectedTail:$.slice(f)}}function kW($){let f=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:J,protectedTail:Q}=xF($.context.messages);if(J.length===0)return;let Z=SF(J,$.estimateMessageTokens);if(Z.length===0)return;Sf(Z,(H)=>H.message.role==="assistant"&&!H.isLastAssistant,f,$.estimateMessageTokens),Sf(Z,(H)=>H.message.role==="user"&&!H.isFirstUser&&!H.isLastUser,f,$.estimateMessageTokens),Sf(Z,(H)=>H.message.role==="assistant"&&H.isLastAssistant,f,$.estimateMessageTokens),Sf(Z,(H)=>H.message.role==="user"&&H.isLastUser&&!H.isFirstUser,f,$.estimateMessageTokens),kF(Z,f,$.estimateMessageTokens);let W=[...Z.map((H)=>H.message),...Q];if(!IF($.context.messages,W))return;let j=J4([...J.map((H)=>EW(H)??H),...Q],$.estimateMessageTokens),X=J4(W,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:W.length,messagesRemoved:$.context.messages.length-W.length,tokensBefore:j,tokensAfter:X,targetTokens:f,maxInputTokens:$.context.maxInputTokens}),{messages:W}}function IW($){try{return JSON.stringify($).length}catch{return String($).length}}function mF($){let f=0,J=0,Q=0;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let W of Z.content){if(W.type!=="tool_result")continue;let j=IW(W.content);f+=1,J+=j,Q=Math.max(Q,j)}}return{toolResultCount:f,toolResultSerializedChars:J,maxToolResultSerializedChars:Q}}var gF={basic:({context:$,estimateMessageTokens:f,logger:J})=>kW({context:$,estimateMessageTokens:f,logger:J}),agentic:({context:$,providerConfig:f,compaction:J,mode:Q,estimateMessageTokens:Z,logger:W})=>SW({context:$,providerConfig:f,summarizer:J?.summarizer,preserveRecentTokens:Q==="manual"?Math.min(J?.preserveRecentTokens??N9,$.triggerTokens):J?.preserveRecentTokens??N9,estimateMessageTokens:Z,logger:W})};function vF($){if(typeof $.config.reserveTokens==="number"){let Q=Math.max(0,$.config.reserveTokens),Z=Math.max(0,$.maxInputTokens-Q);return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let Q=Math.max(0,Math.min($.maxInputTokens-FW,$.maxInputTokens*_9));return{shouldCompact:$.inputTokens>Q,triggerTokens:Q,thresholdRatio:$.maxInputTokens>0?Q/$.maxInputTokens:0}}let f=$.config.thresholdRatio??_9,J=$.maxInputTokens*f;return{shouldCompact:$.inputTokens>J,triggerTokens:J,thresholdRatio:f}}function uF($){let f=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,f)),Q=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*J)));return{triggerTokens:Q,thresholdRatio:$.maxInputTokens>0?Q/$.maxInputTokens:0}}function Q4($,f={}){let J=$.compaction;if(J?.enabled!==!0)return;let Q=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},Z=LW(),W=J?.strategy??"basic",j=gF[W],X=f.mode??"auto",H=J?.compact?"custom":W;return async(Y)=>{let V=Y.apiMessages.reduce((L,N)=>L+Z(N),0),A=J?.maxInputTokens??Y.model.info?.maxInputTokens??Y.model.info?.contextWindow??KW;if(typeof A!=="number"||!Number.isFinite(A)||A<=0)return;let B=vF({inputTokens:V,maxInputTokens:A,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:W,iteration:Y.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:V,maxInputTokens:A,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,shouldCompact:B.shouldCompact,messageCount:Y.messages.length,apiMessageCount:Y.apiMessages.length,apiMessagesJsonChars:IW(Y.apiMessages),...mF(Y.apiMessages)}),X==="auto"&&!B.shouldCompact)return;let G=X==="manual"?uF({inputTokens:V,maxInputTokens:A,autoTriggerTokens:B.triggerTokens,manualTargetRatio:f.manualTargetRatio}):B,K={agentId:Y.agentId,conversationId:Y.conversationId,parentAgentId:Y.parentAgentId,iteration:Y.iteration,messages:Y.messages,model:Y.model,maxInputTokens:A,triggerTokens:G.triggerTokens,thresholdRatio:G.thresholdRatio,utilizationRatio:A>0?V/A:0},D=X==="manual"?"manual_compaction":"auto_compaction";Y.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:D,reason:D,iteration:Y.iteration,triggerTokens:G.triggerTokens,maxInputTokens:A});let F=Y.messages.length,P=Date.now(),U=J?.compact?await J.compact(K):await j({context:K,providerConfig:{...Q,abortSignal:Y.abortSignal},compaction:J,mode:X,estimateMessageTokens:Z,logger:$.logger}),z=Date.now()-P,_=$.sessionId??Y.conversationId,R={agentId:Y.agentId,conversationId:Y.conversationId,parentAgentId:Y.parentAgentId??void 0};if(U?.messages){let L=U.messages.reduce((N,w)=>N+Z(w),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:W,maxInputTokens:A,inputTokens:V,afterTokens:L,tokensSaved:V-L,utilizationBefore:`${(V/A*100).toFixed(1)}%`,utilizationAfter:`${(L/A*100).toFixed(1)}%`,thresholdTrigger:`${(G.thresholdRatio*100).toFixed(1)}%`,messagesBefore:F,messagesAfter:U.messages.length,messagesRemoved:F-U.messages.length}),Af($.telemetry,{ulid:_,strategy:H,mode:X,messagesBefore:F,messagesAfter:U.messages.length,messagesRemoved:F-U.messages.length,tokensBefore:V,tokensAfter:L,tokensSaved:V-L,triggerTokens:G.triggerTokens,maxInputTokens:A,thresholdRatio:G.thresholdRatio,durationMs:z,provider:$.providerId,modelId:$.modelId,...R})}else Bf($.telemetry,{ulid:_,strategy:H,mode:X,reason:"no_result",tokensBefore:V,triggerTokens:G.triggerTokens,maxInputTokens:A,thresholdRatio:G.thresholdRatio,durationMs:z,provider:$.providerId,modelId:$.modelId,...R});return U}}var tj={};y(tj,{zodToJsonSchema:()=>ZD,validateWithZod:()=>QD,resolveToolRoutingConfig:()=>S2,resolveToolPresetName:()=>M$,resolveCoreSelectedToolIds:()=>uf,getCoreHeadlessToolNames:()=>L4,getCoreDefaultEnabledToolIds:()=>vf,getCoreBuiltinToolCatalog:()=>C1,getCoreAcpToolNames:()=>cf,createWindowsShellTool:()=>k9,createWebFetchTool:()=>I9,createWebFetchExecutor:()=>D4,createToolPoliciesWithPreset:()=>kf,createSubmitAndExitTool:()=>v9,createSkillsTool:()=>T1,createSearchTool:()=>E9,createSearchExecutor:()=>U4,createReadFilesTool:()=>C9,createFileReadExecutor:()=>P4,createEditorTool:()=>m9,createEditorExecutor:()=>K4,createDefaultToolsWithPreset:()=>If,createDefaultTools:()=>a$,createDefaultExecutors:()=>y2,createBuiltinTools:()=>E1,createBashTool:()=>b9,createBashExecutor:()=>G4,createAskQuestionTool:()=>g9,createApplyPatchTool:()=>x9,createApplyPatchExecutor:()=>B4,WebFetchRequestSchema:()=>S9,ToolPresets:()=>g0,TEAM_TOOL_NAMES:()=>b2,SubmitInputSchema:()=>A4,SkillsInputSchema:()=>Y4,SearchCodebaseInputSchema:()=>W4,RunCommandsInputSchema:()=>T2,ReadFilesInputSchema:()=>Z4,ReadFileRequestSchema:()=>p$,FetchWebContentInputSchema:()=>j4,EditFileInputSchema:()=>X4,DefaultToolNames:()=>f0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>w2,AskQuestionInputSchema:()=>V4,ApplyPatchInputSchema:()=>H4,ALL_DEFAULT_TOOL_NAMES:()=>I$});import{validateWithZod as QD,zodToJsonSchema as ZD}from"@cline/shared";import{createTool as N$,validateWithZod as n$,zodToJsonSchema as Z$}from"@cline/shared";import{validateWithZod as pW}from"@cline/shared";import{z as O}from"zod";var r$=6000,q9=O.string().describe("The absolute file path of a text file to read content from"),mW=O.object({start_line:O.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:O.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),p$=O.object({path:q9,start_line:mW.shape.start_line,end_line:mW.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),Z4=O.object({files:O.array(p$).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.")}),gW=O.union([Z4,p$,O.array(p$),O.array(O.string()),O.string(),O.object({files:p$}),O.object({file_paths:O.array(q9)}),O.object({file_paths:O.string()}),O.object({paths:O.array(O.union([q9,p$]))}),O.object({paths:p$}),O.object({paths:O.string()})]),W4=O.object({queries:O.array(O.string()).describe("Array of regex search queries to execute")}),vW=O.union([W4,O.array(O.string()),O.string(),O.object({queries:O.string()})]),N1=O.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${r$*2} characters) to avoid timeouts.`),T2=O.object({commands:O.array(N1).describe("Array of shell commands to execute")}),uW=O.union([T2,O.object({commands:N1}),O.object({command:N1}),O.object({cmd:N1}),O.array(O.string()),O.string()]),y9=O.object({command:O.string().min(1).describe("The executable to run directly without shell parsing."),args:O.array(O.string()).optional().describe("Optional argv list passed directly to the executable.")}),cW=O.union([N1,y9]),w9=O.object({commands:O.array(cW).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.")}),dW=O.union([T2,w9,O.object({commands:cW}),O.array(y9),y9,O.object({command:N1}),O.object({cmd:N1}),O.array(O.string()),O.string()]),S9=O.object({url:O.string().describe("The URL to fetch"),prompt:O.string().min(2).describe("Analysis prompt for the fetched content")}),j4=O.object({requests:O.array(S9).describe("Array of the URLs for the web fetch requests")}),X4=O.object({path:O.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:O.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${r$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:O.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${r$} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:O.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),H4=O.object({input:O.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),lW=O.union([H4,O.string()]),Y4=O.object({skill:O.string().min(1).describe("Name of the skill to execute."),args:O.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),V4=O.object({question:O.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:O.array(O.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),A4=O.object({summary:O.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:O.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
|
|
318
|
+
${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function NF($){let f=await TF($.providerConfig),J="";for await(let W of f.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(W.type==="text"){J+=W.text;continue}if(W.type==="done"&&!W.success&&W.error)throw Error(W.error)}return $.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),J.trim()}function MF($){try{return JSON.stringify($).length}catch{return String($).length}}async function Kj($){let f=$.context.messages;if(f.length<2)return;let J=Hj(f,$.preserveRecentTokens,$.estimateMessageTokens);if(J<=0||J>=f.length)return;let W=f.slice(0,J),Z=jj(W),Q=Z>=0?eW(W[Z])?.summary:void 0,j=Z>=0?W.slice(Z+1):W;if(j.length===0)return;let H=Xj(W),X=Jj(j),Y=Aj({previousSummary:Q,conversationText:X,fileOps:H});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:W.length,newMessagesToFold:j.length,preservedMessages:f.length-J,previousSummaryChars:Q?.length??0,conversationTextChars:X.length,summaryRequestChars:Y.length,summaryRequestEstimatedTokens:aW(Y.length),newMessagesJsonChars:MF(j),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let A=await NF({providerConfig:Vj({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:Y,logger:$.logger});if(!A.trim())return;let V=Yj(A,H),B=f.reduce((R,P)=>R+$.estimateMessageTokens(P),0),K=[Bj({summary:V,fileOps:H,tokensBefore:B}),...f.slice(J)],G=K.reduce((R,P)=>R+$.estimateMessageTokens(P),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:f.length,messagesAfter:K.length,messagesSummarized:J,messagesPreserved:f.length-J,tokensBefore:B,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function Fj($){if(U8($))return;if(typeof $.content==="string"){let J=$.content.trim();return J?{...$,content:J}:void 0}let f=$.content.filter((J)=>J.type!=="text"||J.text.trim());if(f.length===0)return;return{...$,content:f.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J.type==="tool_result"?{...J,content:oW(J.content)}:J)}}function D8($,f){return $.reduce((J,W)=>J+f(W),0)}function Gj($,f){let J=Math.max(1,f),W=Math.max(16,J*4);if(typeof $.content==="string"){let j=e$($.content,W).trim();return{...$,content:j||"..."}}let Z=W,Q=$.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let H=e$(j.text,Z).trim();return Z-=H.length,{...j,text:H||"..."}});return{...$,content:Q}}function yF($,f){let J=Zj($),W=i4($),Z=Qj($),Q=[];for(let j=0;j<$.length;j+=1){let H=Fj($[j]);if(!H)continue;Q.push({index:j,message:H,estimatedTokens:f(H),isFirstUser:j===J,isLastUser:j===W,isLastAssistant:j===Z})}return Q}function Pj($,f,J,W){let Z=$[f];Z.message=J,Z.estimatedTokens=W(J)}function qF($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_use")f.add(J.id);return f}function wF($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_result")f.add(J.tool_use_id);return f}function Uj($){return new Set([...qF($.message),...wF($.message)])}function SF($){let f=new Map;for(let J=0;J<$.length;J+=1)for(let W of Uj($[J])){let Z=f.get(W);if(Z)Z.add(J);else f.set(W,new Set([J]))}return f}function hF($,f){let J=SF($),W=new Set,Z=[f];while(Z.length>0){let Q=Z.shift();if(Q===void 0||W.has(Q))continue;W.add(Q);for(let j of Uj($[Q]))for(let H of J.get(j)??[])if(!W.has(H))Z.push(H)}return W}function n4($,f,J,W){let Z=D8($.map((Q)=>Q.message),W);for(let Q=0;Q<$.length&&Z>J;){if(!f($[Q])){Q+=1;continue}let j=hF($,Q);Z-=Array.from(j).reduce((H,X)=>H+$[X].estimatedTokens,0);for(let H of Array.from(j).sort((X,Y)=>Y-X))$.splice(H,1)}}function CF($,f,J){let W=D8($.map((Q)=>Q.message),J);if(W<=f)return;for(let Q=$.length-1;Q>=0&&W>f;Q-=1){let j=$[Q];if(j.isFirstUser)continue;let H=Math.max($j,j.estimatedTokens-(W-f));if(H>=j.estimatedTokens)continue;Pj($,Q,Gj(j.message,H),J),W=D8($.map((X)=>X.message),J)}if(W<=f)return;let Z=$.findIndex((Q)=>Q.isFirstUser);if(Z>=0){let Q=Math.max(1,$[Z].estimatedTokens-(W-f));Pj($,Z,Gj($[Z].message,Q),J)}}function EF($,f){return JSON.stringify($)!==JSON.stringify(f)}function bF($){let f=i4($);if(f<0||f===0&&!R8($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,f),protectedTail:$.slice(f)}}function Rj($){let f=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:J,protectedTail:W}=bF($.context.messages);if(J.length===0)return;let Z=yF(J,$.estimateMessageTokens);if(Z.length===0)return;n4(Z,(X)=>X.message.role==="assistant"&&!X.isLastAssistant,f,$.estimateMessageTokens),n4(Z,(X)=>X.message.role==="user"&&!X.isFirstUser&&!X.isLastUser,f,$.estimateMessageTokens),n4(Z,(X)=>X.message.role==="assistant"&&X.isLastAssistant,f,$.estimateMessageTokens),n4(Z,(X)=>X.message.role==="user"&&X.isLastUser&&!X.isFirstUser,f,$.estimateMessageTokens),CF(Z,f,$.estimateMessageTokens);let Q=[...Z.map((X)=>X.message),...W];if(!EF($.context.messages,Q))return;let j=D8([...J.map((X)=>Fj(X)??X),...W],$.estimateMessageTokens),H=D8(Q,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:Q.length,messagesRemoved:$.context.messages.length-Q.length,tokensBefore:j,tokensAfter:H,targetTokens:f,maxInputTokens:$.context.maxInputTokens}),{messages:Q}}function Dj($){try{return JSON.stringify($).length}catch{return String($).length}}function kF($){let f=0,J=0,W=0;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content){if(Q.type!=="tool_result")continue;let j=Dj(Q.content);f+=1,J+=j,W=Math.max(W,j)}}return{toolResultCount:f,toolResultSerializedChars:J,maxToolResultSerializedChars:W}}var IF={basic:({context:$,estimateMessageTokens:f,logger:J})=>Rj({context:$,estimateMessageTokens:f,logger:J}),agentic:({context:$,providerConfig:f,compaction:J,mode:W,estimateMessageTokens:Z,logger:Q})=>Kj({context:$,providerConfig:f,summarizer:J?.summarizer,preserveRecentTokens:W==="manual"?Math.min(J?.preserveRecentTokens??sW,$.triggerTokens):J?.preserveRecentTokens??sW,estimateMessageTokens:Z,logger:Q})};function xF($){if(typeof $.config.reserveTokens==="number"){let W=Math.max(0,$.config.reserveTokens),Z=Math.max(0,$.maxInputTokens-W);return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let W=Math.max(0,Math.min($.maxInputTokens-o3,$.maxInputTokens*tW));return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}let f=$.config.thresholdRatio??tW,J=$.maxInputTokens*f;return{shouldCompact:$.inputTokens>J,triggerTokens:J,thresholdRatio:f}}function mF($){let f=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,f)),W=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*J)));return{triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}function L8($,f={}){let J=$.compaction;if(J?.enabled!==!0)return;let W=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},Z=Wj(),Q=J?.strategy??"basic",j=IF[Q],H=f.mode??"auto",X=J?.compact?"custom":Q;return async(Y)=>{let A=Y.apiMessages.reduce((O,N)=>O+Z(N),0),V=J?.maxInputTokens??Y.model.info?.maxInputTokens??Y.model.info?.contextWindow??s3;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let B=xF({inputTokens:A,maxInputTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:H,strategy:Q,iteration:Y.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:A,maxInputTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,shouldCompact:B.shouldCompact,messageCount:Y.messages.length,apiMessageCount:Y.apiMessages.length,apiMessagesJsonChars:Dj(Y.apiMessages),...kF(Y.apiMessages)}),H==="auto"&&!B.shouldCompact)return;let K=H==="manual"?mF({inputTokens:A,maxInputTokens:V,autoTriggerTokens:B.triggerTokens,manualTargetRatio:f.manualTargetRatio}):B,G={agentId:Y.agentId,conversationId:Y.conversationId,parentAgentId:Y.parentAgentId,iteration:Y.iteration,messages:Y.messages,model:Y.model,maxInputTokens:V,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:V>0?A/V:0},R=H==="manual"?"manual_compaction":"auto_compaction";Y.emitStatusNotice?.(H==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:Y.iteration,triggerTokens:K.triggerTokens,maxInputTokens:V});let P=Y.messages.length,F=Date.now(),U=J?.compact?await J.compact(G):await j({context:G,providerConfig:{...W,abortSignal:Y.abortSignal},compaction:J,mode:H,estimateMessageTokens:Z,logger:$.logger}),_=Date.now()-F,z=$.sessionId??Y.conversationId,D={agentId:Y.agentId,conversationId:Y.conversationId,parentAgentId:Y.parentAgentId??void 0};if(U?.messages){let O=U.messages.reduce((N,q)=>N+Z(q),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:Q,maxInputTokens:V,inputTokens:A,afterTokens:O,tokensSaved:A-O,utilizationBefore:`${(A/V*100).toFixed(1)}%`,utilizationAfter:`${(O/V*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:P,messagesAfter:U.messages.length,messagesRemoved:P-U.messages.length}),w4($.telemetry,{ulid:z,strategy:X,mode:H,messagesBefore:P,messagesAfter:U.messages.length,messagesRemoved:P-U.messages.length,tokensBefore:A,tokensAfter:O,tokensSaved:A-O,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:_,provider:$.providerId,modelId:$.modelId,...D})}else S4($.telemetry,{ulid:z,strategy:X,mode:H,reason:"no_result",tokensBefore:A,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:_,provider:$.providerId,modelId:$.modelId,...D});return U}}var kH={};w(kH,{zodToJsonSchema:()=>XD,validateWithZod:()=>HD,resolveToolRoutingConfig:()=>uf,resolveToolPresetName:()=>E$,resolveCoreSelectedToolIds:()=>j6,getCoreHeadlessToolNames:()=>m8,getCoreDefaultEnabledToolIds:()=>Q6,getCoreBuiltinToolCatalog:()=>l1,getCoreAcpToolNames:()=>H6,createWindowsShellTool:()=>HZ,createWebFetchTool:()=>XZ,createWebFetchExecutor:()=>I8,createToolPoliciesWithPreset:()=>e4,createSubmitAndExitTool:()=>BZ,createSkillsTool:()=>x1,createSearchTool:()=>QZ,createSearchExecutor:()=>k8,createReadFilesTool:()=>ZZ,createFileReadExecutor:()=>b8,createEditorTool:()=>AZ,createEditorExecutor:()=>C8,createDefaultToolsWithPreset:()=>$6,createDefaultTools:()=>J1,createDefaultExecutors:()=>gf,createBuiltinTools:()=>p1,createBashTool:()=>jZ,createBashExecutor:()=>h8,createAskQuestionTool:()=>VZ,createApplyPatchTool:()=>YZ,createApplyPatchExecutor:()=>S8,WebFetchRequestSchema:()=>JZ,ToolPresets:()=>m0,TEAM_TOOL_NAMES:()=>pf,SubmitInputSchema:()=>w8,SkillsInputSchema:()=>y8,SearchCodebaseInputSchema:()=>z8,RunCommandsInputSchema:()=>If,ReadFilesInputSchema:()=>_8,ReadFileRequestSchema:()=>w$,FetchWebContentInputSchema:()=>T8,EditFileInputSchema:()=>N8,DefaultToolNames:()=>J0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>vf,AskQuestionInputSchema:()=>q8,ApplyPatchInputSchema:()=>M8,ALL_DEFAULT_TOOL_NAMES:()=>l$});import{validateWithZod as HD,zodToJsonSchema as XD}from"@cline/shared";L0();import{createTool as S$,validateWithZod as h$,zodToJsonSchema as Y$}from"@cline/shared";var Oj="__clineInternalTelemetry";function _j($){let f=$?.__clineInternalTelemetry;return f&&typeof f==="object"&&"capture"in f&&typeof f.capture==="function"?f:void 0}import{validateWithZod as gF}from"@cline/shared";import{z as L}from"zod";var $1=6000,O8=L.string().describe("The absolute file path of a text file to read content from"),zj=L.object({start_line:L.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:L.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),w$=L.object({path:O8,start_line:zj.shape.start_line,end_line:zj.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),_8=L.object({files:L.array(w$).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.")}),Tj=L.union([_8,w$,L.array(w$),L.array(L.string()),L.string(),L.object({files:L.array(L.union([O8,w$]))}),L.object({files:w$}),L.object({files:O8}),L.object({file_paths:L.array(O8)}),L.object({file_paths:L.string()}),L.object({paths:L.array(L.union([O8,w$]))}),L.object({paths:w$}),L.object({paths:L.string()})]),z8=L.object({queries:L.array(L.string()).describe("Array of regex search queries to execute")}),Nj=L.union([z8,L.array(L.string()),L.string(),L.object({queries:L.string()})]),k1=L.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${$1*2} characters) to avoid timeouts.`),If=L.object({commands:L.array(k1).describe("Array of shell commands to execute")}),Mj=L.union([If,L.object({commands:k1}),L.object({command:k1}),L.object({cmd:k1}),L.array(L.string()),L.string()]),$Z=L.object({command:L.string().min(1).describe("The executable to run directly without shell parsing."),args:L.array(L.string()).optional().describe("Optional argv list passed directly to the executable.")}),yj=L.union([k1,$Z]),fZ=L.object({commands:L.array(yj).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.")}),qj=L.union([If,fZ,L.object({commands:yj}),L.array($Z),$Z,L.object({command:k1}),L.object({cmd:k1}),L.array(L.string()),L.string()]),JZ=L.object({url:L.string().describe("The URL to fetch"),prompt:L.string().min(2).describe("Analysis prompt for the fetched content")}),T8=L.object({requests:L.array(JZ).describe("Array of the URLs for the web fetch requests")}),N8=L.object({path:L.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:L.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${$1} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:L.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${$1} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:L.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),M8=L.object({input:L.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),wj=L.union([M8,L.string()]),y8=L.object({skill:L.string().min(1).describe("Name of the skill to execute."),args:L.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),q8=L.object({question:L.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:L.array(L.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),w8=L.object({summary:L.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:L.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
|
|
319
319
|
'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
|
|
320
|
-
IMPORTANT: You must run the specific failing test(s) mentioned in the issue or test patch and include the test output in your reasoning. If the test still fails after your fix, you must revise. Do NOT submit with 'true' unless the test output shows the test passing.`)});function
|
|
320
|
+
IMPORTANT: You must run the specific failing test(s) mentioned in the issue or test patch and include the test output in your reasoning. If the test still fails after your fix, you must revise. Do NOT submit with 'true' unless the test output shows the test passing.`)});function f1($){if($ instanceof Error)return $.message;return String($)}function Sj($){if(typeof $.old_text==="string"&&$.old_text.length>$1)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${$1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>$1)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${$1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class I1 extends Error{timeoutMs;constructor($,f){super($);this.name="TimeoutError",this.timeoutMs=f}}function X$($,f,J){return Promise.race([$,new Promise((W,Z)=>{setTimeout(()=>Z(new I1(J,f)),f)})])}function a4($){let{path:f,start_line:J,end_line:W}=$;if(J==null&&W==null)return f;return`${f}:${J??1}-${W??"EOF"}`}function hj($){let{start_line:f,end_line:J}=$;if(f==null||J==null||f<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${f}, end_line: ${J})`}function Cj($){let f=gF(qj,$);if(typeof f==="string")return[f];if(Array.isArray(f))return f;if("commands"in f)return Array.isArray(f.commands)?f.commands:[f.commands];if("command"in f)return"args"in f?[f]:[f.command];if("cmd"in f)return[f.cmd];return[f]}function WZ($){if(typeof $==="string")return $;let f=$.args??[];if(f.length===0)return $.command;let J=f.map((W)=>/[\s"]/u.test(W)?JSON.stringify(W):W);return`${$.command} ${J.join(" ")}`}function Ej($,f){let J=$.metadata?.[f];return typeof J==="string"?J:void 0}function bj($,f){B3(_j($.metadata),{tool_name:"run_commands",effective_timeout_ms:f.effectiveTimeoutMs,timeout_source:f.timeoutSource,command_count:f.commandCount,duration_ms:f.durationMs,ulid:$.sessionId,mode:Ej($,"mode"),source:Ej($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function ZZ($,f={}){let J=f.fileReadTimeoutMs??1e4;return S$({name:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. ",inputSchema:Y$(_8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(W,Z)=>{let Q=h$(Tj,W),j;if(typeof Q==="string")j=[{path:Q}];else if(Array.isArray(Q))j=Q.map((H)=>typeof H==="string"?{path:H}:H);else if("files"in Q)j=(Array.isArray(Q.files)?Q.files:[Q.files]).map((X)=>typeof X==="string"?{path:X}:X);else if("file_paths"in Q)j=(Array.isArray(Q.file_paths)?Q.file_paths:[Q.file_paths]).map((X)=>({path:X}));else if("paths"in Q)j=(Array.isArray(Q.paths)?Q.paths:[Q.paths]).map((X)=>typeof X==="string"?{path:X}:X);else j=[Q];return Promise.all(j.map(async(H)=>{let X=hj(H);if(X)return{query:a4(H),result:"",error:`Invalid file range: ${X}`,success:!1};try{let Y=await X$($(H,Z),J,`File read timed out after ${J}ms`);return{query:a4(H),result:Y,success:!0}}catch(Y){let A=f1(Y);return{query:a4(H),result:"",error:`Error reading file: ${A}`,success:!1}}}))}})}function QZ($,f={}){let J=f.searchTimeoutMs??30000,W=f.cwd??process.cwd();return S$({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:Y$(z8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Z,Q)=>{let j=h$(Nj,Z),H=Array.isArray(j)?j:typeof j==="object"?Array.isArray(j.queries)?j.queries:[j.queries]:[j];return Promise.all(H.map(async(X)=>{try{let Y=await X$($(X,W,Q),J,`Search timed out after ${J}ms`),A=Y.length>0&&!Y.includes("No results found");return{query:X,result:Y,success:A}}catch(Y){let A=f1(Y);return{query:X,result:"",error:`Search failed: ${A}`,success:!1}}}))}})}function jZ($,f={}){let J=f.bashTimeoutMs??30000,W=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return S$({name:"run_commands",description:"Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped and targeted to avoid error or timeout. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.",inputSchema:Y$(If),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let H=h$(Mj,Q),X;if(typeof H==="string")X=[H];else if(Array.isArray(H))X=H;else if("commands"in H)X=Array.isArray(H.commands)?H.commands:[H.commands];else if("command"in H)X=[H.command];else X=[H.cmd];return Promise.all(X.map(async(Y)=>{let A=Date.now();try{let V=await X$($(Y,Z,j),J,`Command timed out after ${J}ms`);return{query:Y,result:V,success:!0}}catch(V){if(V instanceof I1)bj(j,{effectiveTimeoutMs:V.timeoutMs,timeoutSource:W,commandCount:X.length,durationMs:Date.now()-A});let B=f1(V);return{query:Y,result:"",error:`Command failed: ${B}`,success:!1}}}))}})}function HZ($,f={}){let J=f.bashTimeoutMs??30000,W=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return S$({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:Y$(fZ),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let H=Cj(Q);return Promise.all(H.map(async(X)=>{let Y=Date.now();try{let A=await X$($(X,Z,j),J,`Command timed out after ${J}ms`);return{query:WZ(X),result:A,success:!0}}catch(A){if(A instanceof I1)bj(j,{effectiveTimeoutMs:A.timeoutMs,timeoutSource:W,commandCount:H.length,durationMs:Date.now()-Y});let V=f1(A);return{query:WZ(X),result:"",error:`Command failed: ${V}`,success:!1}}}))}})}function XZ($,f={}){let J=f.webFetchTimeoutMs??30000;return S$({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:Y$(T8),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(W,Z)=>{let Q=h$(T8,W);return Promise.all(Q.requests.map(async(j)=>{try{let H=await X$($(j.url,j.prompt,Z),J,`Web fetch timed out after ${J}ms`);return{query:j.url,result:H,success:!0}}catch(H){let X=f1(H);return{query:j.url,result:"",error:`Error fetching web content: ${X}`,success:!1}}}))}})}var vF=`Use \`apply_patch\` to edit files with the canonical freeform patch grammar. Pass the patch text directly as the \`input\` string. Prefer the exact format below:
|
|
321
321
|
|
|
322
322
|
*** Begin Patch
|
|
323
323
|
*** Update File: path/to/file.ts
|
|
@@ -353,68 +353,68 @@ Example:
|
|
|
353
353
|
</div>
|
|
354
354
|
);
|
|
355
355
|
}
|
|
356
|
-
*** End Patch`;function
|
|
357
|
-
`),Z=0,
|
|
358
|
-
${this.lines[this.index]}`);if(
|
|
359
|
-
`);this.addWarning({path:this.currentPath||f,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${
|
|
360
|
-
`),chunks:[]}}}function
|
|
361
|
-
`));for(let Y=j;Y<$.length;Y++){let
|
|
362
|
-
`));if(
|
|
363
|
-
`)),
|
|
364
|
-
`));if(V
|
|
365
|
-
`)),
|
|
366
|
-
`));if(V
|
|
367
|
-
`)),
|
|
368
|
-
`).map((f)=>f.replace(/\r$/,""))}function
|
|
369
|
-
`),Z=[],
|
|
370
|
-
`)}async function
|
|
371
|
-
`)}return
|
|
372
|
-
`)}}import{spawn as
|
|
356
|
+
*** End Patch`;function YZ($,f={}){let J=f.applyPatchTimeoutMs??30000,W=f.cwd??process.cwd();return S$({name:"apply_patch",description:vF,inputSchema:Y$(M8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let j=h$(wj,Z),H=typeof j==="string"?j:j.input;try{return{query:"apply_patch",result:await X$($({input:H},W,Q),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(X){return{query:"apply_patch",result:"",error:`apply_patch failed: ${f1(X)}`,success:!1}}}})}function AZ($,f={}){let J=f.editorTimeoutMs??30000,W=f.cwd??process.cwd();return S$({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:Y$(N8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let j=h$(N8,Z),H=j.insert_line==null?"edit":"insert",X=Sj(j);if(X)return{query:`${H}:${j.path}`,result:"",error:X,success:!1};try{let Y=await X$($(j,W,Q),J,`Editor operation timed out after ${J}ms`);return{query:`${H}:${j.path}`,result:Y,success:!0}}catch(Y){let A=f1(Y);return{query:`${H}:${j.path}`,result:"",error:`Editor operation failed: ${A}`,success:!1}}}})}function x1($,f={}){let J=f.skillsTimeoutMs??15000,W='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',Z=S$({name:"skills",description:W,inputSchema:Y$(y8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let H=h$(y8,Q);return X$($(H.skill,H.args||void 0,j),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(Z,"description",{get(){let Q=$.configuredSkills?.filter((j)=>!j.disabled).map((j)=>j.name);if(Q&&Q.length>0)return`${W} Available skills: ${Q.join(", ")}.`;return W},enumerable:!0,configurable:!0}),Z}function VZ($){return{name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:Y$(q8),retryable:!1,maxRetries:0,execute:async(f,J)=>{let W=h$(q8,f);return $(W.question,W.options,J)}}}function BZ($,f={}){let J=f.submitTimeoutMs??15000;return S$({name:"submit_and_exit",description:"Submit the final answer and exit the conversation. For example, submit a summary of the investigation and confirm the issue is resolved. You should only submit once all necessary steps are completed. Make sure to verify your output matches the expected format, data types, and file locations specified. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:Y$(w8),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,Z)=>{let Q=h$(w8,W);return X$($(Q.summary,Q.verified,Z),J,`submit_and_exit timed out after ${J}ms`)}})}function J1($){let{executors:f,enableReadFiles:J=!0,enableSearch:W=!0,enableBash:Z=!0,enableWebFetch:Q=!0,enableApplyPatch:j=!1,enableEditor:H=!0,enableSkills:X=!0,enableAskQuestion:Y=!0,enableSubmitAndExit:A=!1,...V}=$,B=[];if(J&&f.readFile)B.push(ZZ(f.readFile,V));if(W&&f.search)B.push(QZ(f.search,V));if(Z&&f.bash)if(process.platform==="win32")B.push(HZ(f.bash,V));else B.push(jZ(f.bash,V));if(Q&&f.webFetch)B.push(XZ(f.webFetch,V));if(H&&f.editor)B.push(AZ(f.editor,V));else if(j&&f.applyPatch)B.push(YZ(f.applyPatch,V));if(X&&f.skills)B.push(x1(f.skills,V));let K=A?f.submit:void 0;if(Y&&f.askQuestion&&!K)B.push(VZ(f.askQuestion));if(K)B.push(BZ(K,V));return B}import*as I0 from"node:fs/promises";import*as x0 from"node:path";var v={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},Ij=["%%bash","apply_patch","EOF","```"];class Z0 extends Error{constructor($){super($);this.name="DiffError"}}function k0($){let f={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(J)=>f[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class KZ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,f){this.lines=$;this.currentFiles=f}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(v.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(v.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(v.UPDATE)){this.parseUpdate($.substring(v.UPDATE.length).trim());return}if($?.startsWith(v.DELETE)){this.parseDelete($.substring(v.DELETE.length).trim());return}if($?.startsWith(v.ADD)){this.parseAdd($.substring(v.ADD.length).trim());return}throw new Z0(`Unknown line while parsing: ${$}`)}checkDuplicate($,f){if($ in this.patch.actions)throw new Z0(`Duplicate ${f} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let f=this.lines[this.index]?.startsWith(v.MOVE)?(this.lines[this.index++]??"").substring(v.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new Z0(`Update File Error: Missing File: ${$}`);let J=this.currentFiles[$]??"",W=this.parseUpdateFile(J,$);W.movePath=f,this.patch.actions[$]=W,this.currentPath=void 0}parseUpdateFile($,f){let J={type:"update",chunks:[]},W=$.split(`
|
|
357
|
+
`),Z=0,Q=[v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(!Q.some((j)=>this.lines[this.index]?.startsWith(j.trim()))){let j=this.lines[this.index],H=j?.startsWith("@@ ")?j.substring(3):void 0;if(H!==void 0||(j==="@@"?j:void 0)!==void 0)this.index++;else if(Z!==0)throw new Z0(`Invalid Line:
|
|
358
|
+
${this.lines[this.index]}`);if(H?.trim()){let P=k0(H.trim());for(let F=Z;F<W.length;F++){let U=W[F];if(U&&(k0(U)===P||k0(U.trim())===P)){if(Z=F+1,k0(U.trim())===P&&k0(U)!==P)this.fuzz++;break}}}let[Y,A,V,B]=dF(this.lines,this.index),[K,G,R]=cF(W,Y,Z,B);if(K===-1){let P=Y.join(`
|
|
359
|
+
`);this.addWarning({path:this.currentPath||f,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:P.length>200?`${P.substring(0,200)}...`:P}),this.index=V}else{this.fuzz+=G;for(let P of A)P.origIndex+=K,J.chunks.push(P);Z=K+Y.length,this.index=V}}return J}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new Z0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new Z0(`Add File Error: File already exists: ${$}`);this.index++;let f=[],J=[v.END,v.UPDATE,v.DELETE,v.ADD];while(this.hasMoreLines()&&!J.some((W)=>this.lines[this.index]?.startsWith(W.trim()))){let W=this.lines[this.index++];if(W===void 0)break;if(!W.startsWith("+"))throw new Z0(`Invalid Add File line (missing '+'): ${W}`);f.push(W.substring(1))}this.patch.actions[$]={type:"add",newFile:f.join(`
|
|
360
|
+
`),chunks:[]}}}function kj($,f){let J=$.length>f.length?$:f,W=$.length>f.length?f:$;if(J.length===0)return 1;let Z=uF(W,J);return(J.length-Z)/J.length}function uF($,f){let J=f.length+1,W=$.length+1,Z=Array(J*W).fill(0),Q=(H,X)=>Z[H*W+X]??0,j=(H,X,Y)=>{Z[H*W+X]=Y};for(let H=0;H<=f.length;H++)j(H,0,H);for(let H=0;H<=$.length;H++)j(0,H,H);for(let H=1;H<=f.length;H++)for(let X=1;X<=$.length;X++)if(f[H-1]===$[X-1])j(H,X,Q(H-1,X-1));else j(H,X,1+Math.min(Q(H-1,X-1),Q(H,X-1),Q(H-1,X)));return Q(f.length,$.length)}function cF($,f,J,W){if(f.length===0)return[J,0,1];let Z=0,Q=(j)=>{let H=k0(f.join(`
|
|
361
|
+
`));for(let Y=j;Y<$.length;Y++){let A=k0($.slice(Y,Y+f.length).join(`
|
|
362
|
+
`));if(A===H)return[Y,0,1];let V=kj(A,H);if(V>Z)Z=V}for(let Y=j;Y<$.length;Y++){let A=k0($.slice(Y,Y+f.length).map((B)=>B.trimEnd()).join(`
|
|
363
|
+
`)),V=k0(f.map((B)=>B.trimEnd()).join(`
|
|
364
|
+
`));if(A===V)return[Y,1,1]}for(let Y=j;Y<$.length;Y++){let A=k0($.slice(Y,Y+f.length).map((B)=>B.trim()).join(`
|
|
365
|
+
`)),V=k0(f.map((B)=>B.trim()).join(`
|
|
366
|
+
`));if(A===V)return[Y,100,1]}let X=0.66;for(let Y=j;Y<$.length;Y++){let A=k0($.slice(Y,Y+f.length).join(`
|
|
367
|
+
`)),V=kj(A,H);if(V>=X)return[Y,1000,V];if(V>Z)Z=V}return[-1,0,Z]};if(W){let[j,H,X]=Q($.length-f.length);if(j!==-1)return[j,H,X];return[j,H,X]=Q(J),[j,H+1e4,X]}return Q(J)}function dF($,f){let J=f,W=[],Z=[],Q=[],j=[],H="keep",X=["@@",v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(J<$.length){let Y=$[J];if(!Y||X.some((B)=>Y.startsWith(B.trim())))break;if(Y==="***")break;if(Y.startsWith("***"))throw new Z0(`Invalid line: ${Y}`);J++;let A=H,V=Y;if(V[0]==="+")H="add";else if(V[0]==="-")H="delete";else if(V[0]===" ")H="keep";else H="keep",V=` ${V}`;if(V=V.slice(1),H==="keep"&&A!==H){if(Q.length||Z.length)j.push({origIndex:W.length-Z.length,delLines:Z,insLines:Q});Z=[],Q=[]}if(H==="delete")Z.push(V),W.push(V);else if(H==="add")Q.push(V);else W.push(V)}if(Q.length||Z.length)j.push({origIndex:W.length-Z.length,delLines:Z,insLines:Q});if(J<$.length&&$[J]===v.END_FILE)return J++,[W,j,J,!0];return[W,j,J,!1]}function GZ($,f,J){let W=x0.isAbsolute(f),Z=W?x0.normalize(f):x0.resolve($,f);if(!J||W)return Z;let Q=x0.relative($,Z);if(Q.startsWith("..")||x0.isAbsolute(Q))throw new Z0(`Path must stay within cwd: ${f}`);return Z}function lF($){return $.split(`
|
|
368
|
+
`).map((f)=>f.replace(/\r$/,""))}function xj($){if($.trim()==="")return!1;return Ij.some((f)=>$.startsWith(f))}function pF($){let f=0,J=$.length;while(f<J&&xj($[f]??""))f++;while(J>f&&xj($[J-1]??""))J--;return $.slice(f,J)}function rF($){let f=lF($),J=f.findIndex((j)=>j.startsWith(v.BEGIN)),W=-1;for(let j=f.length-1;j>=0;j--)if(f[j]?.startsWith(v.END)){W=j;break}if(J!==-1||W!==-1){if(J===-1||W===-1||W<J)throw new Z0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:f.slice(J,W+1)}}let Z=pF(f);while(Z.length>0&&Z[0]==="")Z.shift();while(Z.length>0&&Z[Z.length-1]==="")Z.pop();return{lines:[v.BEGIN,...Z,v.END]}}function iF($,f){let J=new Set;for(let W of $)for(let Z of f)if(W.startsWith(Z)){J.add(W.substring(Z.length).trim());break}return[...J]}function nF($,f,J){if(f.length===0)return $;let W=$.split(`
|
|
369
|
+
`),Z=[],Q=0;for(let j of f){if(j.origIndex>W.length)throw new Z0(`${J}: chunk.origIndex ${j.origIndex} > lines.length ${W.length}`);if(Q>j.origIndex)throw new Z0(`${J}: currentIndex ${Q} > chunk.origIndex ${j.origIndex}`);Z.push(...W.slice(Q,j.origIndex)),Z.push(...j.insLines),Q=j.origIndex+j.delLines.length}return Z.push(...W.slice(Q)),Z.join(`
|
|
370
|
+
`)}async function aF($,f,J,W){let Z=iF($,[v.UPDATE,v.DELETE]),Q={};for(let j of Z){let H=GZ(f,j,W),X;try{X=await I0.readFile(H,J)}catch{throw new Z0(`File not found: ${j}`)}Q[j]=X.replace(/\r\n/g,`
|
|
371
|
+
`)}return Q}function tF($,f){let J={};for(let[W,Z]of Object.entries($.actions))switch(Z.type){case"delete":J[W]={type:"delete",oldContent:f[W]};break;case"add":if(Z.newFile===void 0)throw new Z0("ADD action without file content");J[W]={type:"add",newContent:Z.newFile};break;case"update":J[W]={type:"update",oldContent:f[W],newContent:nF(f[W]??"",Z.chunks,W),movePath:Z.movePath};break}return J}async function sF($,f,J,W){let Z=[];for(let[Q,j]of Object.entries($)){let H=GZ(f,Q,W);switch(j.type){case"delete":await I0.rm(H,{force:!0}),Z.push(`${Q}: [deleted]`);break;case"add":if(j.newContent===void 0)throw new Z0(`Cannot create ${Q} with no content`);await I0.mkdir(x0.dirname(H),{recursive:!0}),await I0.writeFile(H,j.newContent,{encoding:J}),Z.push(Q);break;case"update":{if(j.newContent===void 0)throw new Z0(`UPDATE change for ${Q} has no new content`);if(j.movePath){let X=GZ(f,j.movePath,W);await I0.mkdir(x0.dirname(X),{recursive:!0}),await I0.writeFile(X,j.newContent,{encoding:J}),await I0.rm(H,{force:!0}),Z.push(`${Q} -> ${j.movePath}`)}else await I0.writeFile(H,j.newContent,{encoding:J}),Z.push(Q);break}}}return Z}function S8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0}=$;return async(W,Z,Q)=>{let j=rF(W.input),H=await aF(j.lines,Z,f,J),X=new KZ(j.lines,H),{patch:Y,fuzz:A}=X.parse(),V=tF(Y,H),B=await sF(V,Z,f,J),K=["Successfully applied patch to the following files:"];for(let G of B)K.push(G);if(A>0)K.push(`Note: Patch applied with fuzz factor ${A}`);if(Y.warnings&&Y.warnings.length>0)for(let G of Y.warnings)K.push(`Warning (${G.path}): ${G.message}`);return K.join(`
|
|
372
|
+
`)}}import{spawn as mj}from"node:child_process";import{getDefaultShell as oF,getShellArgs as eF}from"@cline/shared";function $U($,f,J,W,Z){return new Promise((Q,j)=>{let H=process.platform==="win32",X=mj($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!H}),Y=X.pid,A="",V="",B=0,K=!1,G=!1,R=(D)=>{if(G)return;G=!0,D()},P=()=>{if(!Y)return;if(H){mj("taskkill",["/pid",String(Y),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-Y,"SIGKILL")}catch{X.kill("SIGKILL")}},F=(D)=>{K=!0,P(),R(()=>j(D))},U=setTimeout(()=>F(new I1(`Command timed out after ${J}ms`,J)),J),_=()=>F(Error("Command was aborted"));if(f.signal)f.signal.addEventListener("abort",_);let z=()=>{clearTimeout(U),f.signal?.removeEventListener("abort",_)};X.stdout?.on("data",(D)=>{if(B+=D.length,B<=W)A+=D.toString()}),X.stderr?.on("data",(D)=>{if(B+=D.length,B<=W)V+=D.toString()}),X.on("close",(D)=>{if(z(),K)return;let O=Z?A+(V?`
|
|
373
373
|
[stderr]
|
|
374
|
-
${
|
|
374
|
+
${V}`:""):A;if(B>W)O+=`
|
|
375
375
|
|
|
376
|
-
[Output truncated: ${B} bytes total, showing first ${
|
|
376
|
+
[Output truncated: ${B} bytes total, showing first ${W} bytes]`;if(D!==0)R(()=>j(Error(V||`Command exited with code ${D}`)));else R(()=>Q(O))}),X.on("error",(D)=>{z(),R(()=>j(Error(`Failed to execute command: ${D.message}`)))})})}function h8($={}){let{shell:f=oF(process.platform),timeoutMs:J=30000,maxOutputBytes:W=1e6,env:Z={},combineOutput:Q=!0}=$;return(j,H,X)=>{let Y=typeof j!=="string";return $U({executable:Y?j.command:f,args:Y?j.args??[]:eF(f,j),cwd:H,env:Z},X,J,W,Q)}}import*as e0 from"node:fs/promises";import*as o0 from"node:path";function fU($,f,J){let W=o0.isAbsolute(f),Z=W?o0.normalize(f):o0.resolve($,f);if(!J)return Z;if(W)return Z;let Q=o0.relative($,Z);if(Q.startsWith("..")||o0.isAbsolute(Q))throw Error(`Path must stay within cwd: ${f}`);return Z}function JU($,f){if(f.length===0)return 0;return $.split(f).length-1}function WU($,f,J){let W=$.split(`
|
|
377
377
|
`),Z=f.split(`
|
|
378
|
-
`),
|
|
379
|
-
`)}async function
|
|
380
|
-
${
|
|
381
|
-
`),j=
|
|
382
|
-
`)),await
|
|
383
|
-
`),{encoding:
|
|
384
|
-
`),
|
|
378
|
+
`),Q=Math.max(W.length,Z.length),j=["```diff"],H=0;for(let X=0;X<Q;X++){if(H>=J){j.push("... diff truncated ...");break}let Y=W[X],A=Z[X];if(Y===A)continue;let V=X+1;if(Y!==void 0)j.push(`-${V}: ${Y}`),H++;if(A!==void 0&&H<J)j.push(`+${V}: ${A}`),H++}return j.push("```"),j.join(`
|
|
379
|
+
`)}async function ZU($,f,J){return await e0.mkdir(o0.dirname($),{recursive:!0}),await e0.writeFile($,f,{encoding:J}),`File created successfully at: ${$}`}async function QU($){try{return await e0.access($),!0}catch{return!1}}async function jU($,f,J,W,Z){let Q=await e0.readFile($,W),j=JU(Q,f);if(j===0)throw Error(`No replacement performed: text not found in ${$}.`);if(j>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let H=Q.replace(f,J??"");await e0.writeFile($,H,{encoding:W});let X=WU(Q,H,Z);return`Edited ${$}
|
|
380
|
+
${X}`}async function HU($,f,J,W){let Q=(await e0.readFile($,W)).split(`
|
|
381
|
+
`),j=Q.length+1;if(f<1||f>j)throw Error(`Invalid insert_line: ${f}. insert_line must be a positive one-based boundary line in the range 1-${j}. Use ${j} to append at EOF.`);let H=f-1;return Q.splice(H,0,...J.split(`
|
|
382
|
+
`)),await e0.writeFile($,Q.join(`
|
|
383
|
+
`),{encoding:W}),`Inserted content at line ${f} in ${$}.`}function C8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0,maxDiffLines:W=200}=$;return async(Z,Q,j)=>{let H=fU(Q,Z.path,J);if(Z.insert_line!=null)return HU(H,Z.insert_line,Z.new_text,f);if(!await QU(H))return ZU(H,Z.new_text,f);if(Z.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return jU(H,Z.old_text,Z.new_text,f,W)}}import*as E8 from"node:fs/promises";import*as W1 from"node:path";import{resolveExistingFilePath as XU}from"@cline/shared/storage";var YU=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),AU={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function b8($={}){let{maxFileSizeBytes:f,encoding:J,includeLineNumbers:W}={...AU,...$};return async(Z,Q)=>{let{path:j,start_line:H,end_line:X}=Z,Y=W1.isAbsolute(j)?W1.normalize(j):W1.resolve(process.cwd(),j),A=XU(Y)??Y,V=W1.extname(A).toLowerCase(),B=YU.get(V),K=await E8.stat(A);if(!K.isFile())throw Error(`Path is not a file: ${A}`);if(K.size>f)throw Error(`File too large: ${K.size} bytes (max: ${f} bytes). Consider reading specific sections or using a different approach.`);if(B){if(Q.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let _=await E8.readFile(A);return[{type:"text",text:"Successfully read image"},{type:"image",data:_.toString("base64"),mediaType:B}]}let R=(await E8.readFile(A,J)).split(`
|
|
384
|
+
`),P=Math.max((H??1)-1,0),F=Math.min(X??R.length,R.length),U=R.slice(P,F);if(W){let _=String(R.length).length;return U.map((z,D)=>`${String(P+D+1).padStart(_," ")} | ${z}`).join(`
|
|
385
385
|
`)}return U.join(`
|
|
386
|
-
`)}}import{spawn as
|
|
387
|
-
`).filter((
|
|
388
|
-
`)}let
|
|
389
|
-
`);for(let
|
|
390
|
-
Searched ${
|
|
391
|
-
`)}}function
|
|
386
|
+
`)}}import{spawn as pj}from"node:child_process";import*as rj from"node:fs/promises";import*as o4 from"node:path";var lj={};w(lj,{prewarmFileIndex:()=>s4,getFileIndex:()=>C$,enrichPromptWithMentions:()=>mf});import{spawn as VU}from"node:child_process";import{readdir as BU}from"node:fs/promises";import FZ from"node:path";import{isMainThread as uj,parentPort as gj,Worker as KU}from"node:worker_threads";var GU=15000,PU=600000,FU=1000,UU=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function vj($){let f=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return f==="EACCES"||f==="EPERM"||f==="ENOENT"}var xf=new Map;function RU(){if(!uj)return!1;return!0}function DU($){if(xf.size<=1)return;for(let[f,J]of xf.entries()){if(J.pending)continue;if($-J.lastAccessedAt>PU)xf.delete(f)}}function LU($,f){return FZ.relative($,f).split(FZ.sep).join("/")}async function OU($){let J=(await new Promise((W,Z)=>{let Q=VU("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"]}),j="",H="";Q.stdout.on("data",(X)=>{j+=X.toString()}),Q.stderr.on("data",(X)=>{H+=X.toString()}),Q.on("error",Z),Q.on("close",(X)=>{if(X===0){W(j);return}Z(Error(H||`rg exited with code ${X}`))})})).split(/\r?\n/).map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>W.replace(/\\/g,"/"));return new Set(J)}async function cj($,f,J){let W;try{W=await BU(f,{withFileTypes:!0})}catch(Z){if(vj(Z))return;throw Z}for(let Z of W){let Q=FZ.join(f,Z.name);if(Z.isDirectory()){if(UU.has(Z.name))continue;try{await cj($,Q,J)}catch(j){if(vj(j))continue;throw j}continue}if(Z.isFile())J.add(LU($,Q))}}async function _U($){let f=new Set;return await cj($,$,f),f}async function t4($){try{return await OU($)}catch{return _U($)}}function zU(){if(uj||!gj)return;let $=gj;$.on("message",(f)=>{if(f.type!=="index")return;t4(f.cwd).then((J)=>{let W={type:"indexResult",requestId:f.requestId,files:Array.from(J)};$.postMessage(W)}).catch((J)=>{let W={type:"indexResult",requestId:f.requestId,error:J instanceof Error?J.message:"Failed to build file index"};$.postMessage(W)})})}class dj{worker=new KU(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let f=this.pending.get($.requestId);if(!f)return;if(this.pending.delete($.requestId),$.error){f.reject(Error($.error));return}f.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let f=++this.nextRequestId,J=new Promise((Z,Q)=>{let j=setTimeout(()=>{this.pending.delete(f),Z(null)},FU);j.unref(),this.pending.set(f,{resolve:(H)=>{clearTimeout(j),Z(H)},reject:(H)=>{clearTimeout(j),Q(H)}})}),W={type:"index",requestId:f,cwd:$};return this.worker.postMessage(W),J}flushPending($){for(let[f,J]of this.pending.entries())J.reject($),this.pending.delete(f)}}zU();var PZ;function TU(){if(!RU())return null;if(PZ===void 0)PZ=new dj;return PZ}async function NU($){let f=TU();if(!f)return t4($);try{let J=await f.requestIndex($);if(J===null)return t4($);return new Set(J)}catch{return t4($)}}async function C$($,f={}){let J=f.ttlMs??GU,W=Date.now();DU(W);let Z=xf.get($);if(Z&&J>0&&W-Z.lastBuiltAt<=J&&Z.files.size>0)return Z.lastAccessedAt=W,Z.files;if(Z?.pending)return Z.lastAccessedAt=W,Z.pending;let Q=NU($).then((j)=>{return xf.set($,{files:j,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),j});return xf.set($,{files:Z?.files??new Set,lastBuiltAt:Z?.lastBuiltAt??0,lastAccessedAt:W,pending:Q}),Q}async function s4($,f={}){await C$($,{...f,ttlMs:0})}import{stat as MU}from"node:fs/promises";import m1 from"node:path";var yU=/[),.:;!?`'"]+$/,qU=/^[(`'"]+/;function wU($){let f=$.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let W of f){let Z=(W[2]??"").trim();if(Z.length===0)continue;let Q=Z.replace(qU,"").replace(yU,"");if(Q.length===0||Q.includes("@"))continue;J.push(Q)}return Array.from(new Set(J))}function SU($,f){let J=$.replace(/\\/g,"/"),W=m1.isAbsolute(J)?m1.resolve(J):m1.resolve(f,J),Z=m1.relative(f,W);if(Z.startsWith("..")||m1.isAbsolute(Z))return;return Z.split(m1.sep).join("/")}async function mf($,f,J={}){let W=wU($);if(W.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:Z,maxFileBytes:Q,maxTotalBytes:j}=J,H=await C$(f,{ttlMs:J.ttlMs}),X=[],Y=[],A=[],V=0;for(let B of W){if(Z&&A.length>=Z){Y.push(B);continue}let K=SU(B,f);if(!K||!H.has(K)){Y.push(B);continue}if(!Q||!j){X.push(K);continue}let G=m1.join(f,K);try{if(!(await MU(G)).isFile()){Y.push(B);continue}let P=V+Q;if(P>j){Y.push(B);continue}V=P,X.push(K)}catch{Y.push(B)}}return{prompt:$,mentions:W,matchedFiles:X,ignoredMentions:Y}}var hU=["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"],CU=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],g1=null;function EU(){if(g1!==null)return Promise.resolve(g1);return new Promise(($)=>{let f=pj("rg",["--version"],{stdio:["ignore","pipe","pipe"]});f.on("close",(J)=>{g1=J===0,$(g1)}),f.on("error",()=>{g1=!1,$(!1)}),setTimeout(()=>{if(!f.killed)f.kill("SIGTERM");if(g1===null)g1=!1,$(!1)},1000)})}function bU($,f,J,W,Z=5000,Q){return new Promise((j)=>{let H=pj("rg",["--json",`--context=${W}`,"--max-count=1","-i",$],{cwd:f,stdio:["ignore","pipe","pipe"]}),X="",Y=!1,A=()=>{if(!H.killed)H.kill("SIGTERM")},V=setTimeout(()=>{if(!Y)Y=!0,A(),j(null)},Z),B=(K)=>{if(!Y)Y=!0,clearTimeout(V),A(),j(K)};if(Q?.aborted){A(),j(null);return}Q?.addEventListener("abort",()=>{B(null)}),H.stdout.on("data",(K)=>{X+=K.toString()}),H.stderr.on("data",()=>{}),H.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=X.split(`
|
|
387
|
+
`).filter((P)=>P.trim());for(let P of R){if(G.length>=J)break;let F=JSON.parse(P);if(F.type==="match"){let U=F.data,_=[];if(F.data.submatches&&F.data.submatches.length>0){let z=F.data.submatches[0];G.push({file:U.path.text,line:U.line_number,column:(z?.start??0)+1,match:z?.match?.text??"",context:_})}}else if(F.type==="context"&&G.length>0){let U=G[G.length-1],_=F.data.line_number===U.line?">":" ";U.context.push(`${_} ${F.data.line_number}: ${F.data.lines?.text??F.data.line?.text??""}`)}}B(G.length>0?G:null)}catch{B(null)}return}B(null)}),H.on("error",()=>{B(null)})})}function kU($,f,J,W){let Z=$.split("/"),Q=Z[Z.length-1]??"";if(Z.length-1>W)return!1;for(let X=0;X<Z.length-1;X++)if(f.has(Z[X]??""))return!1;let H=o4.posix.extname(Q).slice(1).toLowerCase();return J.has(H)||!H&&!Q.startsWith(".")}function k8($={}){let{includeExtensions:f=hU,excludeDirs:J=CU,maxResults:W=100,contextLines:Z=2,maxDepth:Q=20}=$,j=new Set(J),H=new Set(f.map((X)=>X.toLowerCase()));return async(X,Y,A)=>{if(A.signal?.aborted)throw Error("Search operation aborted");let V=await EU(),B=null;if(V)B=await bU(X,Y,W,Z,5000,A.signal);if(B){let U=[`Found ${B.length} result${B.length===1?"":"s"} for pattern: ${X}`,""];for(let _ of B)U.push(`${_.file}:${_.line}:${_.column}`),U.push(..._.context),U.push("");if(B.length>=W)U.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return U.join(`
|
|
388
|
+
`)}let K;try{K=new RegExp(X,"gim")}catch(U){throw Error(`Invalid regex pattern: ${X}. ${U instanceof Error?U.message:""}`)}let G=[],R=0,P=await C$(Y);for(let U of P){if(A.signal?.aborted)throw Error("Search operation aborted");if(!kU(U,j,H,Q))continue;if(G.length>=W)break;R++;let _=o4.join(Y,U);try{let D=(await rj.readFile(_,"utf-8")).split(`
|
|
389
|
+
`);for(let O=0;O<D.length;O++){let N=D[O];K.lastIndex=0;let q=K.exec(N);while(q!==null){if(G.length>=W)break;let $0=Math.max(0,O-Z),Y0=Math.min(D.length-1,O+Z),o=[];for(let A0=$0;A0<=Y0;A0++){let i=A0===O?">":" ";o.push(`${i} ${A0+1}: ${D[A0]}`)}if(G.push({file:U,line:O+1,column:q.index+1,match:q[0],context:o}),q.index===K.lastIndex)K.lastIndex++;q=K.exec(N)}}}catch{}}if(G.length===0)return`No results found for pattern: ${X}
|
|
390
|
+
Searched ${R} files.`;let F=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${X}`,`Searched ${R} files.`,""];for(let U of G)F.push(`${U.file}:${U.line}:${U.column}`),F.push(...U.context),F.push("");if(G.length>=W)F.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return F.join(`
|
|
391
|
+
`)}}function IU($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
|
|
392
392
|
`).replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&#(\d+);/g,(f,J)=>String.fromCharCode(parseInt(J,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
|
|
393
393
|
`).replace(/\n{3,}/g,`
|
|
394
394
|
|
|
395
|
-
`).trim()}function
|
|
396
|
-
[Content truncated: showing first 50000 of ${
|
|
397
|
-
`)}catch(G){if(clearTimeout(A),G instanceof Error){if(G.name==="AbortError")throw Error(`Request timed out after ${f}ms`);throw G}throw Error(`Fetch failed: ${String(G)}`)}finally{if(H.signal&&B)H.signal.removeEventListener("abort",B)}}}function y2($={}){return{readFile:P4($.fileRead),search:U4($.search),bash:G4($.bash),webFetch:D4($.webFetch),applyPatch:B4($.applyPatch),editor:K4($.editor)}}var mP={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion",submit_and_exit:"enableSubmitAndExit"},w2=[{name:"openai-native-use-apply-patch",mode:"act",providerIdIncludes:["openai-native"],enableTools:["apply_patch"],disableTools:["editor"]},{name:"codex-and-gpt-use-apply-patch",mode:"act",modelIdIncludes:["codex","gpt"],enableTools:["apply_patch"],disableTools:["editor"]}];function Hj($,f){if(!f||f.length===0)return!0;let J=$.toLowerCase();return f.some((Q)=>J.includes(Q.toLowerCase()))}function gP($,f,J,Q){if($.mode&&$.mode!=="any"&&$.mode!==Q)return!1;return Hj(f,$.providerIdIncludes)&&Hj(J,$.modelIdIncludes)}function S2($,f,J,Q){if(!Q||Q.length===0)return{};let Z=new Map;for(let j of Q){if(!gP(j,$,f,J))continue;for(let X of j.disableTools??[])Z.set(X,!1);for(let X of j.enableTools??[])Z.set(X,!0)}let W={};for(let[j,X]of Z.entries())W[mP[j]]=X;return W}var g0={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 M$($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function kf($){if($!=="yolo")return{};let f={enabled:!0,autoApprove:!0},J={"*":f};for(let Q of I$)J[Q]=f;return J}function If($,f){let J=g0[$],{enableSpawnAgent:Q,enableAgentTeams:Z,...W}=J;return a$({...W,...f})}import{createTool as bU,zodToJsonSchema as kU}from"@cline/shared";import{z as $7}from"zod";import{createAgentRuntime as TU}from"@cline/agents";import{createContributionRegistry as MU}from"@cline/shared";import{createGateway as vP,MODEL_COLLECTIONS_BY_PROVIDER_ID as uP}from"@cline/llms";function cP($){let f=Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0));return Object.keys(f).length>0?f:void 0}function dP($){let f={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if($.providerId==="bedrock")Object.assign(f,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let J=$.gcp?.region??$.region;Object.assign(f,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:J,region:J})}return cP(f)}function p9($){let f=$.providerConfig;if(f?.knownModels)return f.knownModels;if($.knownModels)return $.knownModels;return uP[$.providerId]?.models??void 0}function lP($){if(!$?.length)return;let f=new Set;for(let J of $)switch(J){case"tools":case"reasoning":case"prompt-cache":case"images":f.add(J);break;case"structured_output":f.add("structured-output");break;default:f.add("text")}return f.add("text"),[...f]}function pP($,f){return{id:$,name:f.name??$,description:f.description,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxOutputTokens:f.maxTokens,capabilities:lP(f.capabilities),metadata:{family:f.family,pricing:f.pricing,status:f.status,releaseDate:f.releaseDate}}}function Yj($,f,J){let Q=$.providerConfig,Z=Q?.providerId===$.providerId?Q:void 0,W={...Z??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Z?.apiKey,baseUrl:$.baseUrl??Z?.baseUrl,headers:$.headers??Z?.headers,knownModels:p9($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:f,extensionContext:$.extensionContext};return vP({providerConfigs:[{providerId:W.providerId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,options:dP(W),models:W.knownModels?Object.entries(W.knownModels).map(([j,X])=>pP(j,X)):void 0}],logger:f,telemetry:J??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:W.providerId,modelId:W.modelId},{maxTokens:W.maxOutputTokens})}import{normalizeUserInput as Vj}from"@cline/shared";var rP=50000,iP=6000000,Aj=8000,nP=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),aP=new Set(["read","read_files"]),y1="[outdated - see the latest file content]",Bj="Tool execution was interrupted before a result was produced.",tP=($)=>`
|
|
395
|
+
`).trim()}function I8($={}){let{timeoutMs:f=30000,maxResponseBytes:J=5000000,userAgent:W="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:Z={},followRedirects:Q=!0}=$;return async(j,H,X)=>{let Y;try{Y=new URL(j)}catch{throw Error(`Invalid URL: ${j}`)}if(!["http:","https:"].includes(Y.protocol))throw Error(`Invalid protocol: ${Y.protocol}. Only http and https are supported.`);let A=new AbortController,V=setTimeout(()=>A.abort(),f),B;if(X.signal)B=()=>A.abort(),X.signal.addEventListener("abort",B);try{let K=await fetch(j,{method:"GET",headers:{"User-Agent":W,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...Z},redirect:Q?"follow":"manual",signal:A.signal});if(clearTimeout(V),!Q&&K.status>=300&&K.status<400)return`Redirect to: ${K.headers.get("location")}`;if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let G=K.headers.get("content-type")||"",R=K.body?.getReader();if(!R)throw Error("Failed to read response body");let P=[],F=0;while(!0){let{done:N,value:q}=await R.read();if(N)break;if(F+=q.length,F>J)throw R.cancel(),Error(`Response too large: exceeded ${J} bytes`);P.push(q)}let U=new Uint8Array(F),_=0;for(let N of P)U.set(N,_),_+=N.length;let z=new TextDecoder("utf-8").decode(U),D;if(G.includes("text/html")||G.includes("application/xhtml"))D=IU(z);else if(G.includes("application/json"))try{let N=JSON.parse(z);D=JSON.stringify(N,null,2)}catch{D=z}else D=z;let O=[`URL: ${j}`,`Content-Type: ${G}`,`Size: ${F} bytes`,"","--- Content ---",D.slice(0,50000)];if(D.length>50000)O.push(`
|
|
396
|
+
[Content truncated: showing first 50000 of ${D.length} characters]`);return O.push("","--- Analysis Request ---",`Prompt: ${H}`),O.join(`
|
|
397
|
+
`)}catch(K){if(clearTimeout(V),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${f}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(X.signal&&B)X.signal.removeEventListener("abort",B)}}}function gf($={}){return{readFile:b8($.fileRead),search:k8($.search),bash:h8($.bash),webFetch:I8($.webFetch),applyPatch:S8($.applyPatch),editor:C8($.editor)}}var xU={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"},vf=[{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 ij($,f){if(!f||f.length===0)return!0;let J=$.toLowerCase();return f.some((W)=>J.includes(W.toLowerCase()))}function mU($,f,J,W){if($.mode&&$.mode!=="any"&&$.mode!==W)return!1;return ij(f,$.providerIdIncludes)&&ij(J,$.modelIdIncludes)}function uf($,f,J,W){if(!W||W.length===0)return{};let Z=new Map;for(let j of W){if(!mU(j,$,f,J))continue;for(let H of j.disableTools??[])Z.set(H,!1);for(let H of j.enableTools??[])Z.set(H,!0)}let Q={};for(let[j,H]of Z.entries())Q[xU[j]]=H;return Q}var m0={act:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},plan:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!1},yolo:{enableReadFiles:!0,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!0,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!0,enableSpawnAgent:!1,enableAgentTeams:!1}};function E$($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function e4($){if($!=="yolo")return{};let f={enabled:!0,autoApprove:!0},J={"*":f};for(let W of l$)J[W]=f;return J}function $6($,f){let J=m0[$],{enableSpawnAgent:W,enableAgentTeams:Z,...Q}=J;return J1({...Q,...f})}import{createTool as mR,zodToJsonSchema as gR}from"@cline/shared";import{z as MZ}from"zod";import{createAgentRuntime as wR}from"@cline/agents";import{createContributionRegistry as SR}from"@cline/shared";import{createGateway as iU,createHandlerAsync as nU,hasRegisteredHandler as aU,MODEL_COLLECTIONS_BY_PROVIDER_ID as tU,normalizeProviderId as sU}from"@cline/llms";function gU($){let f=uU($.content),J=[],W=$.id??lU(),Z=0,Q=[],j=()=>{if(Q.length===0)return;let H=Z===0?W:`${W}_part_${Z}`;Z+=1,J.push({id:H,role:$.role,content:Q.map(cU),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:nj($.metrics)}),Q=[]};if(f.length===0)return J.push({id:W,role:$.role,content:[],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:nj($.metrics)}),J;for(let H of f){if(H.type!=="tool_result"){Q.push(H);continue}j(),J.push({id:`${W}_tool_${H.tool_use_id}`,role:"tool",content:[tj(H)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return j(),J}function f6($){return $.flatMap(gU)}function vU($){let f=$.content.map(sj).filter((J)=>J!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:f,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:dU($.metrics)}}function cf($){return $.map(vU)}function J6($){let f=[];for(let J of $){let W=J.content.map(sj).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,Q=f[f.length-1];if(Z==="user"&&W.length>0&&W.every((j)=>j.type==="tool_result")&&Q?.role==="user"&&Array.isArray(Q.content)&&Q.content.every((j)=>j.type==="tool_result")){Q.content.push(...W);continue}f.push({role:Z,content:W})}return f}function uU($){if(typeof $==="string")return $.length>0?[{type:"text",text:$}]:[];return[...$]}function cU($){switch($.type){case"text":return{type:"text",text:$.text};case"thinking":return{type:"reasoning",text:$.thinking,metadata:$.signature?{signature:$.signature,details:$.details}:$.details?{details:$.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:$.data}};case"image":return{type:"image",image:$.data,mediaType:$.mediaType};case"file":return{type:"file",path:$.path,content:$.content};case"tool_use":return{type:"tool-call",toolCallId:$.id,toolName:$.name,input:$.input,metadata:$.signature?{signature:$.signature}:void 0};case"tool_result":return tj($)}}function tj($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function sj($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let f=$.metadata;return{type:"thinking",thinking:$.text,signature:f?.signature,details:f?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:$.metadata?.signature};case"tool-result":{let f=$.output,J=typeof f==="string"?f:Array.isArray(f)?f:JSON.stringify(f);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:J,is_error:$.isError}}}}function nj($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function dU($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var aj=0;function lU(){return aj+=1,`msg_${Date.now().toString(36)}_${aj.toString(36)}`}function pU($){switch($.type){case"text":return[{type:"text-delta",text:$.text}];case"reasoning":return[{type:"reasoning-delta",text:$.reasoning,metadata:$.signature?{thoughtSignature:$.signature,details:$.details}:{details:$.details}}];case"tool_calls":{let f=$.tool_call.function,J=f.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??f.id,toolName:f.name,inputText:typeof J==="string"?J:void 0,input:typeof J==="string"?void 0:J,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:rU($),error:$.error}];default:return[]}}function rU($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function oj($){return{async*stream(f){let J=!1,W=!1;try{let Z=typeof $==="function"?await $():$;Z.setAbortSignal?.(f.signal);let Q=J6(f.messages),j=f.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema}));for await(let H of Z.createMessage(f.systemPrompt??"",Q,j))for(let X of pU(H)){if(X.type==="finish")J=!0;else if(X.type==="tool-call-delta")W=!0;yield X}if(!J)yield{type:"finish",reason:W?"tool-calls":"stop"}}catch(Z){if(!J)yield{type:"finish",reason:f.signal?.aborted?"aborted":"error",error:Z instanceof Error?Z.message:String(Z)}}}}}function oU($){let f=Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0));return Object.keys(f).length>0?f:void 0}function eU($){let f={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if($.providerId==="bedrock")Object.assign(f,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let J=$.gcp?.region??$.region;Object.assign(f,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:J,region:J})}return oU(f)}function UZ($){let f=$.providerConfig;if(f?.knownModels)return f.knownModels;if($.knownModels)return $.knownModels;return tU[$.providerId]?.models??void 0}function $R($){if(!$?.length)return;let f=new Set;for(let J of $)switch(J){case"tools":case"reasoning":case"prompt-cache":case"images":f.add(J);break;case"structured_output":f.add("structured-output");break;default:f.add("text")}return f.add("text"),[...f]}function fR($,f){return{id:$,name:f.name??$,description:f.description,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxOutputTokens:f.maxTokens,capabilities:$R(f.capabilities),metadata:{family:f.family,pricing:f.pricing,status:f.status,releaseDate:f.releaseDate}}}function ej($,f,J){let W=$.providerConfig,Z=W?.providerId===$.providerId?W:void 0,Q={...Z??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Z?.apiKey,baseUrl:$.baseUrl??Z?.baseUrl,headers:$.headers??Z?.headers,knownModels:UZ($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:f,extensionContext:$.extensionContext};if(aU(sU(Q.providerId)))return oj(()=>nU(Q));return iU({providerConfigs:[{providerId:Q.providerId,apiKey:Q.apiKey,baseUrl:Q.baseUrl,headers:Q.headers,options:eU(Q),models:Q.knownModels?Object.entries(Q.knownModels).map(([j,H])=>fR(j,H)):void 0}],logger:f,telemetry:J??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:Q.providerId,modelId:Q.modelId},{maxTokens:Q.maxOutputTokens})}import{normalizeUserInput as $H}from"@cline/shared";var JR=50000,WR=6000000,fH=8000,ZR=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),QR=new Set(["read","read_files"]),v1="[outdated - see the latest file content]",JH="Tool execution was interrupted before a result was produced.",jR=($)=>`
|
|
398
398
|
|
|
399
399
|
...[truncated ${$} chars]...
|
|
400
400
|
|
|
401
|
-
`,
|
|
401
|
+
`,HR=($)=>`
|
|
402
402
|
|
|
403
403
|
...[truncated ${$} chars to fit provider request budget]...
|
|
404
404
|
|
|
405
|
-
`;class i9{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=rP,f=nP,J=iP){this.maxToolResultChars=$;this.targetToolNames=f;this.maxTotalTextBytes=J}buildForApi($){this.reindex($);let J=this.addMissingToolResults($).map((Q)=>{if(!Array.isArray(Q.content)){if(Q.role==="user"&&typeof Q.content==="string"){let j=Vj(Q.content);if(j!==Q.content)return{...Q,content:j}}return Q}let Z=!1,W=Q.content.map((j)=>{let X=this.transformBlock(j,Q.role);if(X!==j)Z=!0;return X});return Z?{...Q,content:W}:Q});return this.truncateToTotalTextBudget(J)}transformBlock($,f){if(f==="user"&&$.type==="text"&&typeof $.text==="string"){let Z=Vj($.text);if(Z!==$.text)return{...$,text:Z};return $}if($.type==="file"){let Z=this.truncateMiddle($.content);return Z===$.content?$:{...$,content:Z}}if($.type!=="tool_result")return $;let J=this.toolNameByIdCache.get($.tool_use_id),Q=$.content;if(this.isReadTool(J)&&$.is_error!==!0){let Z=this.getReadLocators($);if(Z.length>0){let W=Z.filter((j)=>this.isOutdatedReadLocator(j,$.tool_use_id));if(W.length>0)Q=this.replaceOutdatedReadContent(Q,W)}}if(this.shouldTruncateTool(J))Q=this.truncateToolResultContent(Q);return Q===$.content?$:{...$,content:Q}}reindex($){let f=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!f)this.resetIndexes();for(let J=this.indexedMessageCount;J<$.length;J++){let Q=$[J];if(!Array.isArray(Q.content))continue;for(let Z=0;Z<Q.content.length;Z++){let W=Q.content[Z];if(W.type==="file")this.latestFullContentOwnerByPathCache.set(W.path,`file:${J}:${Z}`);else if(W.type==="tool_use"){let j=W.name.toLowerCase();if(this.toolNameByIdCache.set(W.id,j),this.isReadTool(j)){let X=this.extractLocatorsFromReadToolInput(W.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(W.id,X)}}else if(W.type==="tool_result"){let j=this.toolNameByIdCache.get(W.tool_use_id);if(!this.isReadTool(j)||W.is_error===!0)continue;let X=this.getReadLocators(W);for(let H of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(H),W.tool_use_id),this.isFullFileRead(H))this.latestFullContentOwnerByPathCache.set(H.path,W.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let f=this.collectToolResultIds($),J=[],Q=new Map,Z=!1,W=()=>{if(Q.size===0)return;j(this.createMissingToolResultMessage(Q)),Q.clear(),Z=!0},j=(X)=>{let H=J.at(-1);if(this.shouldMergeUserAfterToolResults(H,X)){J[J.length-1]={...H,content:[...H.content,...this.contentBlocksForUserMerge(X.content)]},Z=!0;return}J.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(j(this.appendMissingToolResults(X,Q)),Q.size>0)Q.clear(),Z=!0;continue}if(Array.isArray(X.content)){let H=X.content.filter((V)=>V.type==="tool_result"),Y=X.content.filter((V)=>V.type!=="tool_result");if(H.length>0){let V=this.appendMissingToolResults({...X,role:"user",content:H},Q);if(j(V),Q.size>0)Q.clear();Z=!0}if(Y.length>0||H.length===0){if(H.length===0)W();let V=H.length>0?{...X,content:Y}:X;if(j(V),V.role==="assistant")this.trackMissingToolCalls(V,f,Q)}continue}W(),j(X)}return W(),Z?J:$}appendMissingToolResults($,f){if(f.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(f)]}}shouldMergeUserAfterToolResults($,f){return $?.role==="user"&&f.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(f.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let f=new Set;for(let J of $){if(!Array.isArray(J.content))continue;for(let Q of J.content)if(Q.type==="tool_result")f.add(Q.tool_use_id)}return f}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((f)=>f.type==="tool_result")}trackMissingToolCalls($,f,J){if(!Array.isArray($.content))return;for(let Q of $.content){if(Q.type!=="tool_use"||f.has(Q.id))continue;J.set(Q.id,Q.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([f,J])=>({type:"tool_result",tool_use_id:f,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText($){return $?`${Bj} Tool: ${$}.`:Bj}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let f=$,J=this.readResultLocatorCache.get(f);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(f,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let f=$,J=[],Q=this.extractLocatorFromReadRequest(f);if(Q)J.push(Q);if(Array.isArray(f.files))for(let Z of f.files){let W=this.extractLocatorFromReadRequest(Z);if(W)J.push(W)}if(Array.isArray(f.file_paths)){for(let Z of f.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let f of $){if(f.type!=="text")continue;let J=this.tryParseReadLocators(f.text);if(J.length>0)return J}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let J=[];for(let Q of $){let Z=this.extractLocatorFromResultEntry(Q);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let f=this.extractLocatorFromResultEntry($);return f?[f]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(!J)return;return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(J)return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)};if(typeof f.query==="string"&&f.query.length>0)return this.parseReadQuery(f.query);return}extractPath($){let f=[$.path,$.file_path,$.filePath];for(let J of f)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let f=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!f)return{path:$,startLine:null,endLine:null};return{path:f[1],startLine:Number(f[2]),endLine:f[3]==="EOF"?null:Number(f[3])}}dedupeReadLocators($){let f=new Map;for(let J of $)f.set(this.toReadLocatorKey(J),J);return Array.from(f.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,f){let J=this.latestFullContentOwnerByPathCache.get($.path);if(J&&J!==f)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==f}replaceOutdatedReadContent($,f){let J=new Set(f.map((W)=>this.toReadLocatorKey(W))),Q=new Set(f.map((W)=>W.path));if(typeof $==="string")return this.replaceOutdatedInString($,J)??y1;let Z=0;for(let W of $)if(W.type==="text")Z+=this.countOutdatedImageEntries(W.text,J);return $.map((W)=>{if(W.type==="file"){if(!Q.has(W.path))return W;return{...W,content:y1}}if(W.type==="image"){if(Z===0)return W;return Z-=1,{type:"text",text:y1}}if(W.type!=="text")return W;let j=this.replaceOutdatedInString(W.text,J);if(j===null)return{...W,text:y1};return j===W.text?W:{...W,text:j}})}countOutdatedImageEntries($,f){let J;try{J=JSON.parse($)}catch{return 0}let Q=Array.isArray(J)?J:[J],Z=0;for(let W of Q){if(!W||typeof W!=="object")continue;let j=W,X=this.extractLocatorFromResultEntry(j);if(!X)continue;if(!f.has(this.toReadLocatorKey(X)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString($,f){let J;try{J=JSON.parse($)}catch{return null}let Q=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,f)):this.replaceOutdatedReadEntry(J,f);return JSON.stringify(Q)}replaceOutdatedReadEntry($,f){if(!$||typeof $!=="object")return $;let J=this.extractLocatorFromResultEntry($);if(!J||!f.has(this.toReadLocatorKey(J)))return $;let Q={...$};if(typeof Q.result==="string")Q.result=y1;else if(typeof Q.content==="string")Q.content=y1;else Q.result=y1;return Q}isReadTool($){return!!$&&aP.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((f)=>{if(f.type==="file"){let Q=this.truncateMiddle(f.content);return Q===f.content?f:{...f,content:Q}}if(f.type!=="text")return f;let J=this.truncateMiddle(f.text);return J===f.text?f:{...f,text:J}})}truncateMiddle($){return r9($,this.maxToolResultChars,tP)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let f=this.countMessageTextBytes($);if(f<=this.maxTotalTextBytes)return $;let J=$.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((W)=>eP(W))}}),Q=this.collectTruncationCandidates(J);for(let Z of Q){if(f<=this.maxTotalTextBytes)break;let W=Z.byteLength;if(W<=Aj)continue;let j=f-this.maxTotalTextBytes,X=Math.max(Aj,W-j),H=oP(Z.get(),X,sP);Z.set(H),f-=W-M0(H)}return J}countMessageTextBytes($){let f=0;for(let J of $){if(typeof J.content==="string"){f+=M0(J.content);continue}for(let Q of J.content)if(Q.type==="text")f+=M0(Q.text);else if(Q.type==="thinking")f+=M0(Q.thinking);else if(Q.type==="file")f+=M0(Q.content);else if(Q.type==="tool_result"){if(typeof Q.content==="string")f+=M0(Q.content);else for(let Z of Q.content)if(Z.type==="text")f+=M0(Z.text);else if(Z.type==="file")f+=M0(Z.content)}}return f}collectTruncationCandidates($){let f=[];for(let J of $){if(!Array.isArray(J.content))continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof Q.content==="string"){f.push({byteLength:M0(Q.content),get:()=>Q.content,set:(W)=>{Q.content=W}});continue}for(let W of Q.content)if(W.type==="text")f.push({byteLength:M0(W.text),get:()=>W.text,set:(j)=>{W.text=j}});else if(W.type==="file")f.push({byteLength:M0(W.content),get:()=>W.content,set:(j)=>{W.content=j}})}}return f.sort((J,Q)=>Q.byteLength-J.byteLength)}}function M0($){return Buffer.byteLength($,"utf8")}function r9($,f,J){if($.length<=f)return $;let Q=J($.length-f),Z=Math.max(0,Math.floor((f-Q.length)/2)),W=Math.max(0,$.length-Z*2),j=J(W),X=Math.max(0,Math.floor((f-j.length)/2)),H=$.slice(0,X),Y=X>0?$.slice(-X):"";return`${H}${j}${Y}`}function oP($,f,J){if(M0($)<=f)return $;let Q=0,Z=$.length,W=r9($,0,J);while(Q<=Z){let j=Q+Z>>>1,X=r9($,j,J);if(M0(X)<=f)W=X,Q=j+1;else Z=j-1}return W}function eP($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((f)=>({...f}))}}function n9(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class a9{messages=[];conversationId=n9();sessionStarted=!1;constructor($){if(($?.length??0)>0)this.restore($??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage($){this.messages.push($)}appendMessages($){if($.length===0)return;this.messages.push(...$)}replaceMessages($){this.messages=[...$]}resetForRun(){this.messages=[],this.conversationId=n9(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=n9(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function $U($){let f=JU($.content),J=[],Q=$.id??WU(),Z=0,W=[],j=()=>{if(W.length===0)return;let X=Z===0?Q:`${Q}_part_${Z}`;Z+=1,J.push({id:X,role:$.role,content:W.map(QU),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:Gj($.metrics)}),W=[]};if(f.length===0)return J.push({id:Q,role:$.role,content:[],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:Gj($.metrics)}),J;for(let X of f){if(X.type!=="tool_result"){W.push(X);continue}j(),J.push({id:`${Q}_tool_${X.tool_use_id}`,role:"tool",content:[Pj(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return j(),J}function xf($){return $.flatMap($U)}function fU($){let f=$.content.map(Uj).filter((J)=>J!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:f,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:ZU($.metrics)}}function h2($){return $.map(fU)}function Fj($){let f=[];for(let J of $){let Q=J.content.map(Uj).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,W=f[f.length-1];if(Z==="user"&&Q.length>0&&Q.every((j)=>j.type==="tool_result")&&W?.role==="user"&&Array.isArray(W.content)&&W.content.every((j)=>j.type==="tool_result")){W.content.push(...Q);continue}f.push({role:Z,content:Q})}return f}function JU($){if(typeof $==="string")return $.length>0?[{type:"text",text:$}]:[];return[...$]}function QU($){switch($.type){case"text":return{type:"text",text:$.text};case"thinking":return{type:"reasoning",text:$.thinking,metadata:$.signature?{signature:$.signature,details:$.details}:$.details?{details:$.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:$.data}};case"image":return{type:"image",image:$.data,mediaType:$.mediaType};case"file":return{type:"file",path:$.path,content:$.content};case"tool_use":return{type:"tool-call",toolCallId:$.id,toolName:$.name,input:$.input,metadata:$.signature?{signature:$.signature}:void 0};case"tool_result":return Pj($)}}function Pj($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function Uj($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let f=$.metadata;return{type:"thinking",thinking:$.text,signature:f?.signature,details:f?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:$.metadata?.signature};case"tool-result":{let f=$.output,J=typeof f==="string"?f:Array.isArray(f)?f:JSON.stringify(f);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:J,is_error:$.isError}}}}function Gj($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function ZU($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var Kj=0;function WU(){return Kj+=1,`msg_${Date.now().toString(36)}_${Kj.toString(36)}`}function Dj($){let{agentConfig:f}=$,J=jU(f),Q=XU(f),Z=$.hooks,W=HU(f.maxParallelToolCalls);return{sessionId:$.sessionId??f.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??f.systemPrompt,messageModelInfo:Q,model:$.model,modelOptions:J,tools:$.tools,hooks:Z,prepareTurn:$.prepareTurn,consumePendingUserMessage:f.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??f.logger,telemetry:$.telemetry??f.telemetry,initialMessages:$.initialMessages,completionPolicy:f.completionPolicy,maxIterations:f.maxIterations,toolExecution:W,toolPolicies:f.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:f.requestToolApproval}}function jU($){let f={};if($.thinking!==void 0)f.thinking=$.thinking;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)f.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)f.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(f).length>0?f:void 0}function XU($){let f=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:f}}function HU($){if($===void 0)return;return $>=2?"parallel":"sequential"}function YU(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function VU($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function t9($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(t9);let f={};for(let J of Object.keys($).sort())f[J]=t9($[J]);return f}function AU($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(t9($))}catch{return String($)}}function BU($,f,J,Q){if(f===$.lastToolName&&J===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=f,$.lastToolSignature=J,{softWarning:$.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Q.hardThreshold}}var Rj={softThreshold:3,hardThreshold:5};class s9{config;state=YU();constructor($){this.config={softThreshold:$?.softThreshold??Rj.softThreshold,hardThreshold:$?.hardThreshold??Rj.hardThreshold}}inspect($){let f=AU($.input),J=BU(this.state,$.name,f,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){VU(this.state)}}class o9{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let f=this.options.maxConsecutiveMistakes,J=$.forceAtLimit&&f?f:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let Q=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!f||J<f)return{action:"continue"};let Z=await KU({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details},this.options.onLimitReached);if(Z.action==="continue"){let W=Z.guidance?.trim();if(W)this.options.appendRecoveryNotice(W,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:W}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:GU({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function GU($){let f=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],J=$.details?.trim();if(J)f.push(`Error: ${J}`);let Q=$.stopReason?.trim();if(Q)f.push(`Decision: ${Q}`);return f.push("Session state was preserved. Send a new prompt to resume from the latest state."),f.join(" ")}async function KU($,f){if(!f)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await f($)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function FU($){let f=$.content.filter((J)=>J.type==="text");if(f.length===0)return;return f.map((J)=>J.text).join("")}function PU($){let f=$.content.filter((J)=>J.type==="reasoning");if(f.length===0)return;return{reasoning:f.map((J)=>J.text).join(""),redacted:f.some((J)=>J.redacted===!0)}}function UU($){return $.content.find((f)=>f.type==="tool-result")}function DU($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function RU($){if(!$||$.isError!==!0)return;if(typeof $.output==="string")return $.output;if($.output instanceof Error)return $.output.message;try{return JSON.stringify($.output)}catch{return String($.output)}}class e9{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:$.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let f=[],J=FU($);if(J!==void 0)f.push({type:"content_end",contentType:"text",text:J});let Q=PU($);if(Q!==void 0)f.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return f}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let f=this.toolStartedAt.get($.toolCall.toolCallId),J=f===void 0?void 0:Date.now()-f;this.toolStartedAt.delete($.toolCall.toolCallId);let Q=UU($.message),Z=Q?.output,W=RU(Q);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:Z,error:W,durationMs:J}]}translateUsage($){let f=$.inputTokens-this.lastUsage.inputTokens,J=$.outputTokens-this.lastUsage.outputTokens,Q=$.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,W=this.lastUsage.totalCost??0,X=($.totalCost??0)-W;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,f),outputTokens:Math.max(0,J),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:X===0?void 0:X,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let f={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:DU($.status),text:$.outputText,iterations:$.iterations,usage:f}]}}function qU($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function yU($){let J=(typeof $.content==="function"?await $.content():$.content).trim();return J.length>0?J:void 0}function wU($,f){let J=$.trim(),Q=f.map((Z)=>Z.trim()).filter(Boolean).join(`
|
|
405
|
+
`;class DZ{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=JR,f=ZR,J=WR){this.maxToolResultChars=$;this.targetToolNames=f;this.maxTotalTextBytes=J}buildForApi($){this.reindex($);let J=this.addMissingToolResults($).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let j=$H(W.content);if(j!==W.content)return{...W,content:j}}return W}let Z=!1,Q=W.content.map((j)=>{let H=this.transformBlock(j,W.role);if(H!==j)Z=!0;return H});return Z?{...W,content:Q}:W});return this.truncateToTotalTextBudget(J)}transformBlock($,f){if(f==="user"&&$.type==="text"&&typeof $.text==="string"){let Z=$H($.text);if(Z!==$.text)return{...$,text:Z};return $}if($.type==="file"){let Z=this.truncateMiddle($.content);return Z===$.content?$:{...$,content:Z}}if($.type!=="tool_result")return $;let J=this.toolNameByIdCache.get($.tool_use_id),W=$.content;if(this.isReadTool(J)&&$.is_error!==!0){let Z=this.getReadLocators($);if(Z.length>0){let Q=Z.filter((j)=>this.isOutdatedReadLocator(j,$.tool_use_id));if(Q.length>0)W=this.replaceOutdatedReadContent(W,Q)}}if(this.shouldTruncateTool(J))W=this.truncateToolResultContent(W);return W===$.content?$:{...$,content:W}}reindex($){let f=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!f)this.resetIndexes();for(let J=this.indexedMessageCount;J<$.length;J++){let W=$[J];if(!Array.isArray(W.content))continue;for(let Z=0;Z<W.content.length;Z++){let Q=W.content[Z];if(Q.type==="file")this.latestFullContentOwnerByPathCache.set(Q.path,`file:${J}:${Z}`);else if(Q.type==="tool_use"){let j=Q.name.toLowerCase();if(this.toolNameByIdCache.set(Q.id,j),this.isReadTool(j)){let H=this.extractLocatorsFromReadToolInput(Q.input);if(H.length>0)this.readLocatorsByToolUseIdCache.set(Q.id,H)}}else if(Q.type==="tool_result"){let j=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.isReadTool(j)||Q.is_error===!0)continue;let H=this.getReadLocators(Q);for(let X of H)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(X),Q.tool_use_id),this.isFullFileRead(X))this.latestFullContentOwnerByPathCache.set(X.path,Q.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let f=this.collectToolResultIds($),J=[],W=new Map,Z=!1,Q=()=>{if(W.size===0)return;j(this.createMissingToolResultMessage(W)),W.clear(),Z=!0},j=(H)=>{let X=J.at(-1);if(this.shouldMergeUserAfterToolResults(X,H)){J[J.length-1]={...X,content:[...X.content,...this.contentBlocksForUserMerge(H.content)]},Z=!0;return}J.push(H)};for(let H of $){if(this.isToolResultOnlyMessage(H)){if(j(this.appendMissingToolResults(H,W)),W.size>0)W.clear(),Z=!0;continue}if(Array.isArray(H.content)){let X=H.content.filter((A)=>A.type==="tool_result"),Y=H.content.filter((A)=>A.type!=="tool_result");if(X.length>0){let A=this.appendMissingToolResults({...H,role:"user",content:X},W);if(j(A),W.size>0)W.clear();Z=!0}if(Y.length>0||X.length===0){if(X.length===0)Q();let A=X.length>0?{...H,content:Y}:H;if(j(A),A.role==="assistant")this.trackMissingToolCalls(A,f,W)}continue}Q(),j(H)}return Q(),Z?J:$}appendMissingToolResults($,f){if(f.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(f)]}}shouldMergeUserAfterToolResults($,f){return $?.role==="user"&&f.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(f.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let f=new Set;for(let J of $){if(!Array.isArray(J.content))continue;for(let W of J.content)if(W.type==="tool_result")f.add(W.tool_use_id)}return f}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((f)=>f.type==="tool_result")}trackMissingToolCalls($,f,J){if(!Array.isArray($.content))return;for(let W of $.content){if(W.type!=="tool_use"||f.has(W.id))continue;J.set(W.id,W.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([f,J])=>({type:"tool_result",tool_use_id:f,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText($){return $?`${JH} Tool: ${$}.`:JH}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let f=$,J=this.readResultLocatorCache.get(f);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(f,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let f=$,J=[],W=this.extractLocatorFromReadRequest(f);if(W)J.push(W);if(Array.isArray(f.files))for(let Z of f.files){let Q=this.extractLocatorFromReadRequest(Z);if(Q)J.push(Q)}if(Array.isArray(f.file_paths)){for(let Z of f.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let f of $){if(f.type!=="text")continue;let J=this.tryParseReadLocators(f.text);if(J.length>0)return J}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let J=[];for(let W of $){let Z=this.extractLocatorFromResultEntry(W);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let f=this.extractLocatorFromResultEntry($);return f?[f]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(!J)return;return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(J)return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)};if(typeof f.query==="string"&&f.query.length>0)return this.parseReadQuery(f.query);return}extractPath($){let f=[$.path,$.file_path,$.filePath];for(let J of f)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let f=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!f)return{path:$,startLine:null,endLine:null};return{path:f[1],startLine:Number(f[2]),endLine:f[3]==="EOF"?null:Number(f[3])}}dedupeReadLocators($){let f=new Map;for(let J of $)f.set(this.toReadLocatorKey(J),J);return Array.from(f.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,f){let J=this.latestFullContentOwnerByPathCache.get($.path);if(J&&J!==f)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==f}replaceOutdatedReadContent($,f){let J=new Set(f.map((Q)=>this.toReadLocatorKey(Q))),W=new Set(f.map((Q)=>Q.path));if(typeof $==="string")return this.replaceOutdatedInString($,J)??v1;let Z=0;for(let Q of $)if(Q.type==="text")Z+=this.countOutdatedImageEntries(Q.text,J);return $.map((Q)=>{if(Q.type==="file"){if(!W.has(Q.path))return Q;return{...Q,content:v1}}if(Q.type==="image"){if(Z===0)return Q;return Z-=1,{type:"text",text:v1}}if(Q.type!=="text")return Q;let j=this.replaceOutdatedInString(Q.text,J);if(j===null)return{...Q,text:v1};return j===Q.text?Q:{...Q,text:j}})}countOutdatedImageEntries($,f){let J;try{J=JSON.parse($)}catch{return 0}let W=Array.isArray(J)?J:[J],Z=0;for(let Q of W){if(!Q||typeof Q!=="object")continue;let j=Q,H=this.extractLocatorFromResultEntry(j);if(!H)continue;if(!f.has(this.toReadLocatorKey(H)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString($,f){let J;try{J=JSON.parse($)}catch{return null}let W=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,f)):this.replaceOutdatedReadEntry(J,f);return JSON.stringify(W)}replaceOutdatedReadEntry($,f){if(!$||typeof $!=="object")return $;let J=this.extractLocatorFromResultEntry($);if(!J||!f.has(this.toReadLocatorKey(J)))return $;let W={...$};if(typeof W.result==="string")W.result=v1;else if(typeof W.content==="string")W.content=v1;else W.result=v1;return W}isReadTool($){return!!$&&QR.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((f)=>{if(f.type==="file"){let W=this.truncateMiddle(f.content);return W===f.content?f:{...f,content:W}}if(f.type!=="text")return f;let J=this.truncateMiddle(f.text);return J===f.text?f:{...f,text:J}})}truncateMiddle($){return RZ($,this.maxToolResultChars,jR)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let f=this.countMessageTextBytes($);if(f<=this.maxTotalTextBytes)return $;let J=$.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((Q)=>YR(Q))}}),W=this.collectTruncationCandidates(J);for(let Z of W){if(f<=this.maxTotalTextBytes)break;let Q=Z.byteLength;if(Q<=fH)continue;let j=f-this.maxTotalTextBytes,H=Math.max(fH,Q-j),X=XR(Z.get(),H,HR);Z.set(X),f-=Q-N0(X)}return J}countMessageTextBytes($){let f=0;for(let J of $){if(typeof J.content==="string"){f+=N0(J.content);continue}for(let W of J.content)if(W.type==="text")f+=N0(W.text);else if(W.type==="thinking")f+=N0(W.thinking);else if(W.type==="file")f+=N0(W.content);else if(W.type==="tool_result"){if(typeof W.content==="string")f+=N0(W.content);else for(let Z of W.content)if(Z.type==="text")f+=N0(Z.text);else if(Z.type==="file")f+=N0(Z.content)}}return f}collectTruncationCandidates($){let f=[];for(let J of $){if(!Array.isArray(J.content))continue;for(let W of J.content){if(W.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(W.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof W.content==="string"){f.push({byteLength:N0(W.content),get:()=>W.content,set:(Q)=>{W.content=Q}});continue}for(let Q of W.content)if(Q.type==="text")f.push({byteLength:N0(Q.text),get:()=>Q.text,set:(j)=>{Q.text=j}});else if(Q.type==="file")f.push({byteLength:N0(Q.content),get:()=>Q.content,set:(j)=>{Q.content=j}})}}return f.sort((J,W)=>W.byteLength-J.byteLength)}}function N0($){return Buffer.byteLength($,"utf8")}function RZ($,f,J){if($.length<=f)return $;let W=J($.length-f),Z=Math.max(0,Math.floor((f-W.length)/2)),Q=Math.max(0,$.length-Z*2),j=J(Q),H=Math.max(0,Math.floor((f-j.length)/2)),X=$.slice(0,H),Y=H>0?$.slice(-H):"";return`${X}${j}${Y}`}function XR($,f,J){if(N0($)<=f)return $;let W=0,Z=$.length,Q=RZ($,0,J);while(W<=Z){let j=W+Z>>>1,H=RZ($,j,J);if(N0(H)<=f)Q=H,W=j+1;else Z=j-1}return Q}function YR($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((f)=>({...f}))}}function LZ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class OZ{messages=[];conversationId=LZ();sessionStarted=!1;constructor($){if(($?.length??0)>0)this.restore($??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage($){this.messages.push($)}appendMessages($){if($.length===0)return;this.messages.push(...$)}replaceMessages($){this.messages=[...$]}resetForRun(){this.messages=[],this.conversationId=LZ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=LZ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function WH($){let{agentConfig:f}=$,J=AR(f),W=VR(f),Z=$.hooks,Q=BR(f.maxParallelToolCalls);return{sessionId:$.sessionId??f.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??f.systemPrompt,messageModelInfo:W,model:$.model,modelOptions:J,tools:$.tools,hooks:Z,prepareTurn:$.prepareTurn,consumePendingUserMessage:f.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??f.logger,telemetry:$.telemetry??f.telemetry,initialMessages:$.initialMessages,completionPolicy:f.completionPolicy,maxIterations:f.maxIterations,toolExecution:Q,toolPolicies:f.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:f.requestToolApproval}}function AR($){let f={};if($.thinking!==void 0)f.thinking=$.thinking;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)f.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)f.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(f).length>0?f:void 0}function VR($){let f=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:f}}function BR($){if($===void 0)return;return $>=2?"parallel":"sequential"}function KR(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function GR($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function _Z($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(_Z);let f={};for(let J of Object.keys($).sort())f[J]=_Z($[J]);return f}function PR($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(_Z($))}catch{return String($)}}function FR($,f,J,W){if(f===$.lastToolName&&J===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=f,$.lastToolSignature=J,{softWarning:$.consecutiveIdenticalCount===W.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=W.hardThreshold}}var ZH={softThreshold:3,hardThreshold:5};class zZ{config;state=KR();constructor($){this.config={softThreshold:$?.softThreshold??ZH.softThreshold,hardThreshold:$?.hardThreshold??ZH.hardThreshold}}inspect($){let f=PR($.input),J=FR(this.state,$.name,f,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){GR(this.state)}}class TZ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let f=this.options.maxConsecutiveMistakes,J=$.forceAtLimit&&f?f:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let W=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(W),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!f||J<f)return{action:"continue"};let Z=await RR({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details},this.options.onLimitReached);if(Z.action==="continue"){let Q=Z.guidance?.trim();if(Q)this.options.appendRecoveryNotice(Q,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:Q}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:UR({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function UR($){let f=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],J=$.details?.trim();if(J)f.push(`Error: ${J}`);let W=$.stopReason?.trim();if(W)f.push(`Decision: ${W}`);return f.push("Session state was preserved. Send a new prompt to resume from the latest state."),f.join(" ")}async function RR($,f){if(!f)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await f($)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function DR($){let f=$.content.filter((J)=>J.type==="text");if(f.length===0)return;return f.map((J)=>J.text).join("")}function LR($){let f=$.content.filter((J)=>J.type==="reasoning");if(f.length===0)return;return{reasoning:f.map((J)=>J.text).join(""),redacted:f.some((J)=>J.redacted===!0)}}function OR($){return $.content.find((f)=>f.type==="tool-result")}function _R($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function zR($){if(!$||$.isError!==!0)return;if(typeof $.output==="string")return $.output;if($.output instanceof Error)return $.output.message;try{return JSON.stringify($.output)}catch{return String($.output)}}class NZ{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:$.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let f=[],J=DR($);if(J!==void 0)f.push({type:"content_end",contentType:"text",text:J});let W=LR($);if(W!==void 0)f.push({type:"content_end",contentType:"reasoning",reasoning:W.reasoning});return f}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let f=this.toolStartedAt.get($.toolCall.toolCallId),J=f===void 0?void 0:Date.now()-f;this.toolStartedAt.delete($.toolCall.toolCallId);let W=OR($.message),Z=W?.output,Q=zR(W);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:Z,error:Q,durationMs:J}]}translateUsage($){let f=$.inputTokens-this.lastUsage.inputTokens,J=$.outputTokens-this.lastUsage.outputTokens,W=$.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,Q=this.lastUsage.totalCost??0,H=($.totalCost??0)-Q;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,f),outputTokens:Math.max(0,J),cacheReadTokens:W===0?void 0:Math.max(0,W),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:H===0?void 0:H,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let f={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:_R($.status),text:$.outputText,iterations:$.iterations,usage:f}]}}function hR($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function CR($){let J=(typeof $.content==="function"?await $.content():$.content).trim();return J.length>0?J:void 0}function ER($,f){let J=$.trim(),W=f.map((Z)=>Z.trim()).filter(Boolean).join(`
|
|
406
406
|
|
|
407
|
-
`);if(J&&
|
|
407
|
+
`);if(J&&W)return`${J}
|
|
408
408
|
|
|
409
|
-
${Q}`;return J||Q}function SU($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return{};return{beforeRun:async(J)=>{for(let Q of f){let Z=await Q.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let Q of f)await Q.afterRun?.(J)},beforeModel:async(J)=>{let Q=J.request,Z;for(let W of f){let j=await W.beforeModel?.({...J,request:Q});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},Q={...Q,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...Q.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let Q of f){let Z=await Q.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let Q=J.input,Z;for(let W of f){let j=await W.beforeTool?.({...J,input:Q});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))Q=j.input}return Z},afterTool:async(J)=>{let Q=J.result,Z;for(let W of f){let j=await W.afterTool?.({...J,result:Q});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)Q=j.result}return Z},onEvent:async(J)=>{for(let Q of f)await Q.onEvent?.(J)}}}class s${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 e9;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,f={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=f.logger??$.logger,this.telemetry=f.telemetry??$.telemetry,this.createAgentRuntimeImpl=f.createAgentRuntimeImpl??TU,this.conversation=new a9($.initialMessages),this.messageBuilder=new i9,this.contributionRegistry=MU({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new o9({maxConsecutiveMistakes:J,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(W)=>this.emitLegacyEvent(W),log:(W,j,X)=>hU(this.logger,W,j,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(W,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:W}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let Z=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new s9(Z)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let f=new Set(this.config.tools.map((Q)=>Q.name)),J=[...this.config.tools];for(let Q of $)if(!f.has(Q.name))J.push(Q),f.add(Q.name);this.config={...this.config,tools:J}}updateConnection($){let f={...this.config};if($.providerId!==void 0)f.providerId=$.providerId;if($.modelId!==void 0)f.modelId=$.modelId;if($.apiKey!==void 0)f.apiKey=$.apiKey;if($.baseUrl!==void 0)f.baseUrl=$.baseUrl;if($.headers!==void 0)f.headers=$.headers;if($.providerConfig!==void 0)f.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)f.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=f}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let f=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=f,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(f)}async shutdown($,f){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,f,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!1})}continue($,f,J){return this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let f of this.contributionRegistry.getRegisteredRules()){let J=await yU(f);if(J)$.push(J)}return wU(this.config.systemPrompt,$)}executeRun($){let f;return f=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===f)this.activeRunPromise=null}),this.activeRunPromise=f,f}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let f=new Date,J=$.userMessage;if(J!==void 0){let P=await EU(J,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:P})}let Q=await this.composeSystemPrompt(),Z=Yj(this.config,this.logger,this.telemetry),W=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let P of W)j.set(P.name,P);for(let P of this.config.tools)j.set(P.name,P);let X=this.conversation.getConversationId(),H=Oj(this.config),Y=Array.from(j.values()),V=xf(this.conversation.getMessages()),A=Dj({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:X,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:Y,toolContextMetadata:{modelSupportsImages:H?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(H,Y),initialMessages:V,systemPrompt:Q}),B=this.createAgentRuntimeImpl(A);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let G=B.subscribe((P)=>{this.handleRuntimeEvent(P)}),K,D;try{if($.isContinue)K=await B.continue(void 0);else K=await B.run("")}catch(P){D=P instanceof Error?P:Error(String(P))}finally{G();try{await this.activeTrackerWork}catch(P){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:P})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(K&&K.messages.length>0){let P=h2(K.messages);this.conversation.replaceMessages(P)}let F=new Date;try{return this.buildLegacyResult({runResult:K,thrownError:D,startedAt:f,endedAt:F})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=SU([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((f)=>f.hooks)]);return{...$,beforeModel:async(f)=>{let J=await $.beforeModel?.(f);if(J?.stop)return J;let Q=J?.messages??f.request.messages,Z=await this.prepareMessagesForModelRequest(Q);return{...J,messages:Z}}}}createRuntimePrepareTurn($,f){let J=this.config.prepareTurn;if(!J)return;return async(Q)=>{let Z=h2(Q.messages),W=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:Z,apiMessages:W,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:f,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!j)return;return{...j.messages?{messages:xf(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let f=await this.prepareProviderMessagesForApi(Fj($));return xf(f)}async prepareProviderMessagesForApi($){let f=$,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of J)f=await Q.build(f);return this.messageBuilder.buildForApi(f)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let f=this.toolStartedAt.get($.toolCall.toolCallId),J=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let Z=$.message.content.find((H)=>H.type==="tool-result"),W=Z?.type==="tool-result"&&Z.isError===!0,j=W?qU(Z?.type==="tool-result"?Z.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:f===void 0?0:J.getTime()-f.getTime(),startedAt:f??J,endedAt:J};if(this.currentRunToolCalls.push(X),W){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let f=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if(f>0&&J===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${f} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let f of this.eventAdapter.translate($))this.emitLegacyEvent(f)}syncConversationFromRuntimeMessage($,f){if($.length>0){this.conversation.replaceMessages(h2($));return}if(f.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),Q=h2(f).filter((Z)=>!Z.id||!J.has(Z.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let f of this.listeners)try{f($)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall($,f,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:f});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let f=await this.mistakeTracker.record($);if(f.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:f.message}]}),this.activeRuntime?.abort(f.reason??f.message)})}buildLegacyResult($){let{runResult:f,thrownError:J,startedAt:Q,endedAt:Z}=$,W=Z.getTime()-Q.getTime(),j=J?"error":CU(f),X=f?.outputText||(f?.status==="failed"?f.error?.message:void 0)||"",H=f?{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost}:this.currentRunUsage,Y=f?h2(f.messages):this.conversation.getMessages(),V=Oj(this.config);if(J)throw J;return{text:X,usage:H,messages:Y,toolCalls:this.currentRunToolCalls,iterations:f?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:V},startedAt:Q,endedAt:Z,durationMs:W}}}function hU($,f,J,Q){if(!$)return;if(f==="debug"){$.debug(J,Q);return}if(f==="error"&&$.error){$.error(J,Q);return}let Z=f==="warn"?"warn":f==="error"?"error":"info";$.log(J,{...Q,severity:Z})}function CU($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function EU($,f,J,Q){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => Lj);return Z($,f,J,Q)}function Oj($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let f=p9($);if(f?.[$.modelId])return f[$.modelId];return}import{buildClineSystemPrompt as zj}from"@cline/shared";function _j($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return zj({ide:f.clineIdeName?.trim()||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,rules:`# Team Teammate Role
|
|
410
|
-
${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function Nj($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return zj({ide:f.clineIdeName||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,overridePrompt:J,metadata:f.workspaceMetadata,platform:f.clinePlatform})}function C2($){let f={...$};return{getRuntimeConfig:()=>f,getConnectionConfig:()=>({providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking}),updateConnectionDefaults:(J)=>{f={...f,...J}}}}function w1($){let f=$.configProvider.getRuntimeConfig(),J=$.kind==="teammate"?_j($.prompt,f):Nj($.prompt,f);return{...$.configProvider.getConnectionConfig(),systemPrompt:J,tools:$.tools,maxIterations:$.maxIterations??f.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:f.hooks,extensions:f.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:f.logger,role:$.role}}function E2($){let f=w1($),J=new s$(f);if(f.onEvent)J.subscribeEvents(f.onEvent);return J}var IU=$7.object({systemPrompt:$7.string().describe("System prompt defining the sub-agent's behavior"),task:$7.string().describe("Task for the sub-agent to complete")});function o$($){return bU({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:kU(IU),execute:async(f,J)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(f,J):$.subAgentTools??[],Z=E2({kind:"subagent",prompt:f.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),W=Z.getAgentId(),j=Z.getConversationId(),X=J.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:W,conversationId:j,parentAgentId:X,input:f})}catch{}try{let H=await Z.run(f.task),Y={text:H.text,iterations:H.iterations,finishReason:H.finishReason,usage:{inputTokens:H.usage.inputTokens,outputTokens:H.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:X,input:f,result:Y,agentResult:H})}catch{}return Y}catch(H){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:X,input:f,error:H instanceof Error?H:Error(String(H))})}catch{}throw H}},timeoutMs:300000,retryable:!1})}import{createTool as j0,TEAM_AWAIT_TIMEOUT_MS as xU,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as mU,TEAM_RUN_TEXT_PREVIEW_LIMIT as gU,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as vU,TeamAttachOutcomeFragmentInputSchema as Tj,TeamAwaitRunsInputSchema as Mj,TeamBroadcastInputSchema as qj,TeamBroadcastToolResultSchema as uU,TeamCancelRunInputSchema as yj,TeamCancelRunToolResultSchema as cU,TeamCleanupInputSchema as wj,TeamCleanupToolResultSchema as dU,TeamCreateOutcomeInputSchema as Sj,TeamCreateOutcomeToolResultSchema as lU,TeamFinalizeOutcomeInputSchema as hj,TeamFinalizeOutcomeToolResultSchema as pU,TeamListOutcomesInputSchema as Cj,TeamListRunsInputSchema as Ej,TeamMailboxMessageToolResultSchema as rU,TeamMissionLogInputSchema as bj,TeamMissionLogToolResultSchema as iU,TeamOutcomeFragmentToolResultSchema as kj,TeamOutcomeToolResultSchema as nU,TeamReadMailboxInputSchema as Ij,TeamReviewOutcomeFragmentInputSchema as xj,TeamRunTaskInputSchema as mj,TeamRunTaskToolResultSchema as f7,TeamRunToolSummarySchema as J7,TeamSendMessageInputSchema as gj,TeamSendMessageToolResultSchema as aU,TeamShutdownTeammateInputSchema as vj,TeamSimpleAgentStatusToolResultSchema as uj,TeamSpawnTeammateInputSchema as cj,TeamStatusInputSchema as dj,TeamStatusToolResultSchema as tU,TeamTaskInputSchema as lj,TeamTaskToolResultSchema as R4,validateWithZod as C,zodToJsonSchema as X0}from"@cline/shared";function pj($,f){let J=$.replace(/\s+/g," ").trim();if(J.length<=f)return J;return`${J.slice(0,Math.max(0,f-3)).trimEnd()}...`}function S1($,f){if($===void 0)throw Error(`Missing required field: ${f}`);return $}function sU($){let f=$.result;if(!f)return;return{textPreview:pj(f.text,gU),iterations:f.iterations,finishReason:f.finishReason,durationMs:f.durationMs,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost}}}function mf($){return $?.toISOString()}function Q7($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:pj($.message,mU),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:mf($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:mf($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:mf($.heartbeatAt),lastProgressAt:mf($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:sU($)}}function oU($){if($.status==="failed")throw Error(`Run "${$.id}" failed${$.error?`: ${$.error}`:""}`);if($.status==="cancelled")throw Error(`Run "${$.id}" was cancelled${$.error?`: ${$.error}`:""}`);if($.status==="interrupted")throw Error(`Run "${$.id}" was interrupted${$.error?`: ${$.error}`:""}`)}var b2=["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 rj($){let f=[];if($.createBaseTools)f.push(...$.createBaseTools());f.push(...h1({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:w1({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:f,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function k2($){let f=$.leadAgentId??"lead",J=$.restoredFromPersistence===!0,Q=h1({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),Z=[];for(let W of $.restoredTeammates??[]){if($.runtime.isTeammateActive(W.agentId))continue;rj({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:W}),Z.push(W.agentId)}return{tools:Q,restoredFromPersistence:J,restoredTeammates:Z}}function h1($){let f=$.allowSpawn??!0,J=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,Z=[];if(J)Z.push(j0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:X0(cj),execute:async(j)=>{let X=C(cj,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!f)throw Error("Spawning teammates is disabled in this context.");let H={agentId:X.agentId,rolePrompt:X.rolePrompt};if(rj({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:H}),!Q)$.onLeadToolsUnlocked?.(h1({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return C(uj,{agentId:X.agentId,status:"spawned"})}}));if(!Q)return Z;Z.push(j0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:X0(vj),execute:async(j)=>{let X=C(vj,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),C(uj,{agentId:X.agentId,status:"stopped"})}})),Z.push(j0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:X0(dj),execute:async(j)=>{return C(dj,j),C(tU,$.runtime.getSnapshot())}})),Z.push(j0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:X0(lj),execute:async(j)=>{let X=C(lj,j);switch(X.action){case"create":{let H=new Set(vU.create??[]),Y=Object.entries(j).filter(([A,B])=>H.has(A)&&B!=null).map(([A])=>A),V=$.runtime.createTask({title:S1(X.title,"title"),description:S1(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return C(R4,{action:"create",taskId:V.id,status:V.status,...Y.length>0?{ignoredFields:Y,note:`Ignored fields for action=create: ${Y.join(", ")}`}:{}})}case"list":return C(R4,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let H=$.runtime.claimTask(S1(X.taskId,"taskId"),$.requesterId);return C(R4,{action:"claim",taskId:H.id,status:H.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 H=$.runtime.completeTask(S1(X.taskId,"taskId"),$.requesterId,S1(X.summary,"summary"));return C(R4,{action:"complete",taskId:H.id,status:H.status})}case"block":{let H=$.runtime.blockTask(S1(X.taskId,"taskId"),$.requesterId,S1(X.reason,"reason"));return C(R4,{action:"block",taskId:H.id,status:H.status})}}}}));let W=new Map;return Z.push(j0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:X0(mj),execute:async(j)=>{let X=C(mj,j);if(X.runMode==="async"){let V=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return C(f7,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${V.id}.`,runId:V.id})}let H=W.get(X.agentId);if(H){let V=await H;return C(f7,{...V,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let Y=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((V)=>C(f7,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:V.text,iterations:V.iterations})).finally(()=>{W.delete(X.agentId)});return W.set(X.agentId,Y),await Y}})),Z.push(j0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:X0(yj),execute:async(j)=>{let X=C(yj,j),H=$.runtime.cancelRun(X.runId,X.reason);return C(cU,{runId:H.id,status:H.status})}})),Z.push(j0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:X0(Ej),execute:async(j)=>C(J7.array(),$.runtime.listRuns(C(Ej,j)).map(Q7))})),Z.push(j0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:X0(Mj),timeoutMs:xU,execute:async(j)=>{let X=C(Mj,j);if(X.runId){let V=await $.runtime.awaitRun(X.runId);return oU(V),C(J7,Q7(V))}let H=await $.runtime.awaitAllRuns(),Y=H.filter((V)=>["failed","cancelled","interrupted"].includes(V.status));if(Y.length>0){let V=Y.map((A)=>`${A.id}:${A.status}${A.error?`(${A.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${V}`)}return C(J7.array(),H.map(Q7))}})),Z.push(j0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:X0(gj),execute:async(j)=>{let X=C(gj,j),H=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return C(aU,{id:H.id,toAgentId:H.toAgentId})}})),Z.push(j0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:X0(qj),execute:async(j)=>{let X=C(qj,j),H=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return C(uU,{delivered:H.length})}})),Z.push(j0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:X0(Ij),execute:async(j)=>{let X=C(Ij,j);return C(rU.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),Z.push(j0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:X0(bj),execute:async(j)=>{let X=C(bj,j),H=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:X.taskId||void 0,kind:X.kind,summary:X.summary,evidence:X.evidence?.length?X.evidence:void 0,nextAction:X.nextAction||void 0});return C(iU,{id:H.id})}})),Z.push(j0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:X0(wj),execute:async(j)=>{if(C(wj,j),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),C(dU,{status:"cleaned"})}})),Z.push(j0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:X0(Sj),execute:async(j)=>{let X=C(Sj,j),H=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return C(lU,{outcomeId:H.id,status:H.status,requiredSections:H.requiredSections})}})),Z.push(j0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:X0(Tj),execute:async(j)=>{let X=C(Tj,j),H=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return C(kj,{fragmentId:H.id,status:H.status})}})),Z.push(j0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:X0(xj),execute:async(j)=>{let X=C(xj,j),H=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return C(kj,{fragmentId:H.id,status:H.status})}})),Z.push(j0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:X0(hj),execute:async(j)=>{let X=C(hj,j),H=$.runtime.finalizeOutcome(X.outcomeId);return C(pU,{outcomeId:H.id,status:H.status})}})),Z.push(j0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:X0(Cj),execute:async(j)=>{return C(Cj,j),C(nU.array(),$.runtime.listOutcomes())}})),Z}function gf($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}function ij($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var eU=[{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:o$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...b2]}],$D={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function fD($){return $==="plan"||$==="yolo"?$:"act"}function aj($){let f=fD($.mode),J=g0[M$({mode:f})],Q=S2($.providerId??"",$.modelId??"",f,w2);return{mode:f,flags:{...J,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function nj($,f){if(f.disabledToolIds?.has($))return!1;let{flags:J}=aj(f);if($==="spawn_agent")return J.enableSpawnAgent===!0;if($==="teams")return J.enableAgentTeams===!0;if($==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let Q=$D[$];return Q?J[Q]===!0:!1}function JD($,f){if($.id==="editor"){let{flags:J}=aj(f),Q=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...$,defaultEnabled:nj($.id,f),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:nj($.id,f)}}function C1($={}){return eU.map((f)=>JD(f,$))}function vf($={}){return C1($).filter((f)=>f.defaultEnabled).map((f)=>f.id)}function uf($){if(!$.enabled)return new Set;let f=C1($.availabilityContext),J=new Set(f.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(f.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!J.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${f.map((Z)=>Z.id).join(", ")}`);return new Set($.allowlist)}function L4($,f={}){return C1(f).filter((J)=>$.has(J.id)).flatMap((J)=>J.headlessToolNames)}function cf($,f={}){return L4($,f)}function E1($={}){let{executorOptions:f={},executors:J,...Q}=$,Z={...y2(f),...J??{}};return a$({...Q,executors:Z})}import{mkdirSync as HD,writeFileSync as YD}from"node:fs";import{dirname as VD}from"node:path";import{normalizeUserInput as AD}from"@cline/shared";import{nanoid as BD}from"nanoid";var sj={};y(sj,{sanitizeSessionToken:()=>b1,parseTeamTaskSubSessionId:()=>x2,parseSubSessionId:()=>z4,makeTeamTaskSubSessionId:()=>O4,makeSubSessionId:()=>I2,deriveSubsessionStatus:()=>_4});import{nanoid as WD}from"nanoid";function b1($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function I2($,f){let J=b1($),Q=b1(f),Z=`${J}__${Q}`;return Z.length>180?Z.slice(0,180):Z}function O4($,f){let J=b1($),Q=b1(f);return`${J}__teamtask__${Q}__${WD(6)}`}function x2($){let J=$.indexOf("__teamtask__");if(J<=0)return null;let Q=$.slice(0,J),Z=$.slice(J+12),W=Z.lastIndexOf("__");if(W<=0)return null;let j=Z.slice(0,W),X=Z.slice(W+2);if(!Q||!j||!X)return null;return{rootSessionId:Q,agentId:j,teamTaskId:X}}function z4($){if(x2($))return null;let f="__",J=$.indexOf(f);if(J<=0)return null;let Q=$.slice(0,J),Z=$.slice(J+f.length);if(!Q||!Z)return null;return{rootSessionId:Q,agentId:Z}}function _4($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let f=String($.reason??"").toLowerCase();if(f.includes("cancel")||f.includes("abort")||f.includes("interrupt"))return"cancelled";if(f.includes("fail")||f.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as t}from"zod";var $X={};y($X,{isTerminalSessionStatus:()=>ej,isNonTerminalSessionStatus:()=>J0,SessionSource:()=>F0,SESSION_STATUSES:()=>N4,NON_TERMINAL_SESSION_STATUSES:()=>oj});import{SESSION_STATUS_VALUES as jD}from"@cline/shared";var N4=jD,oj=["idle","running","pending"];function ej($){return!oj.includes($)}function J0($){return!ej($)}var F0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var XD=t.enum(N4),q0=t.object({version:t.literal(1),session_id:t.string().min(1),source:t.string().min(1),pid:t.number().int(),started_at:t.string().min(1),ended_at:t.string().min(1).optional(),exit_code:t.number().int().nullable().optional(),status:XD,interactive:t.boolean(),provider:t.string().min(1),model:t.string().min(1),cwd:t.string().min(1),workspace_root:t.string().min(1),team_name:t.string().min(1).optional(),enable_tools:t.boolean(),enable_spawn:t.boolean(),enable_teams:t.boolean(),prompt:t.string().optional(),metadata:t.record(t.string(),t.unknown()).optional(),messages_path:t.string().min(1).optional()});function fX($){if(!$)return!1;return Object.values($).some((f)=>typeof f==="function")}function W7($,f){let J=[...$??[],...f??[]];if(J.length===0)return;let Q=[],Z=new Set;for(let W of J){if(Z.has(W.name))continue;Z.add(W.name),Q.push(W)}return Q}function JX($){return JSON.stringify($,(f,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function q$($){return typeof $==="string"&&$.trim()?$.trim():void 0}function Z7($,f){let J={...$};J.id=q$(J.id)??BD();let Q=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:q$(Q?.id)??q$(J.modelId)??q$(f?.id),provider:q$(Q?.provider)??q$(J.providerId)??q$(f?.provider),family:q$(Q?.family)??q$(f?.family)};if(delete J.providerId,delete J.modelId,Z.id&&Z.provider)J.modelInfo={id:Z.id,provider:Z.provider,...Z.family?{family:Z.family}:{}};else delete J.modelInfo;return J}function df($){return $.map((f)=>Z7(f))}function lf($,f,J=[]){let Q=$.map((H,Y)=>{let V=J[Y],B=V?.role===H.role&&JSON.stringify(V.content)===JSON.stringify(H.content)?{...V,...H}:{...H};return Z7(B)}),Z=J.length,W=[];for(let H=Z;H<Q.length;H+=1)if(Q[H]?.role==="assistant")W.push(H);if(W.length===0){let H=[...Q].reverse().findIndex((Y)=>Y.role==="assistant");if(H===-1)return Q;W.push(Q.length-1-H)}let j=W[W.length-1],X=W.some((H)=>Q[H]?.metrics);for(let H of W){let Y=Q[H],V=Y.metrics;if(!V&&H===j&&!X){let A=f.usage;V={inputTokens:A.inputTokens,outputTokens:A.outputTokens,cacheReadTokens:A.cacheReadTokens??0,cacheWriteTokens:A.cacheWriteTokens??0,cost:A.totalCost}}Q[H]={...Z7(Y,{id:f.model.id,provider:f.model.provider,family:f.model.info?.family}),...V?{metrics:V}:{},ts:Y.ts??f.endedAt.getTime()}}return Q}function T4($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??void 0,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??void 0,parentAgentId:$.parentAgentId??void 0,agentId:$.agentId??void 0,conversationId:$.conversationId??void 0,isSubagent:$.isSubagent,prompt:$.prompt??void 0,metadata:$.metadata??void 0,messagesPath:$.messagesPath??void 0,updatedAt:$.updatedAt}}var GD=120;function k1($){let f=$?.trim();return f?f.slice(0,GD):void 0}function j7($){let f=AD($??"").trim();if(!f)return;return k1(f.split(`
|
|
411
|
-
`)[0]?.trim())}function
|
|
412
|
-
`,"utf8")}function ZX($,f){return q0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:f?.endedAt??$.endedAt??void 0,exit_code:f?.exitCode??$.exitCode??void 0,status:f?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:f?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function WX($,f,J){let Q=0;while(!0){let Z=await $();if(Z===void 0)return{updated:!1};let W=await f(Z);if(typeof W==="object"&&W!==null&&"updated"in W&&W.updated===!1){if(Q+=1,Q>=J)return W;continue}return W}}L0();var jX={};y(jX,{summarizeUsageFromMessages:()=>g2,sumUsageTotals:()=>q4,getCurrentContextSize:()=>Y7,createInitialAccumulatedUsage:()=>A0,accumulateUsageTotals:()=>H0});function A0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function H0($,f){return{inputTokens:$.inputTokens+Math.max(0,f.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,f.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,f.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,f.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,f.totalCost??0)}}function q4($){let f=A0();for(let J of $)f=H0(f,J);return f}function m2($){return typeof $==="number"&&Number.isFinite($)?$:0}function g2($){let f=A0();for(let J of $){let Q=J.metrics;if(!Q)continue;f=H0(f,{inputTokens:m2(Q.inputTokens),outputTokens:m2(Q.outputTokens),cacheReadTokens:m2(Q.cacheReadTokens),cacheWriteTokens:m2(Q.cacheWriteTokens),totalCost:m2(Q.cost)})}return f}function Y7($){for(let f=$.length-1;f>=0;f-=1){let J=$[f];if(J?.role!=="assistant")continue;let Q=m2(J.metrics?.inputTokens);return Q>0?Q:void 0}return}function KD($){if(!$||typeof $!=="object")return;let f=$,J=f.skill??f.skill_name??f.skillName;if(typeof J!=="string")return;let Q=J.trim();return Q.length>0?Q:void 0}function V7($){if(!$||typeof $!=="object")return{};let f=$;return{agentId:typeof f.agentId==="string"?f.agentId:void 0,conversationId:typeof f.conversationId==="string"?f.conversationId:void 0,parentAgentId:typeof f.parentAgentId==="string"?f.parentAgentId:void 0}}function y$($){let f=$.agentId?.trim();if(!f)return;let J=$.parentAgentId?.trim()||void 0,Q=$.teamRole,Z="root";if(Q==="teammate")Z="team_teammate";else if(Q==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:f,agentKind:Z,conversationId:$.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:$.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function FD($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function PD($){let f=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let J of f){let Q=J?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function A7($,f,J){let{sessionId:Q,config:Z,liveSession:W,emit:j}=$,X=Z.telemetry,H=W?.runtime.teamRuntime,Y=J?.isPrimaryAgentEvent??!0,V=V7(f),A=y$({agentId:J?.agentId??V.agentId,conversationId:J?.conversationId??V.conversationId,parentAgentId:J?.parentAgentId??V.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??H?.getTeamId(),teamName:J?.teamName??H?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if(f.type==="content_start"&&f.contentType==="tool"&&f.toolName==="skills"){let B=KD(f.input);if(B)Zf(X,{ulid:Q,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...A})}if(f.type==="content_end"&&f.contentType==="tool"){let B=f.toolName??"unknown",G=!f.error;if(Qf(X,{ulid:Q,tool:B,autoApproved:void 0,success:G,modelId:Z.modelId,provider:Z.providerId,...A}),!G&&(B==="editor"||B==="apply_patch"))Wf(X,{ulid:Q,modelId:Z.modelId,provider:Z.providerId,errorType:f.error,...A})}if(f.type==="notice"&&f.reason==="api_error")m8(X,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:f.message,...A});if(f.type==="error")m8(X,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:f.error?.message??"unknown error",...A});if(f.type==="usage"&&W?.turnUsageBaseline){let B=FD(f);if(Y){W.turnPrimaryUsage=H0(W.turnPrimaryUsage??A0(),B);let K=H0(W.turnUsageBaseline,W.turnPrimaryUsage);$.usageBySession.set(Q,K),U2(X,{ulid:Q,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...A}),ff(X,{ulid:Q,tokensIn:f.inputTokens,tokensOut:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost,model:Z.modelId,...A})}else{let K=PD({isPrimaryAgentEvent:Y,overrides:J,eventMetadata:V}),D=W.turnUsageByAgent??new Map;W.turnUsageByAgent=D,D.set(K,H0(D.get(K)??A0(),B))}let G=H0(W.turnPrimaryUsage??A0(),q4(W.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,H0(W.turnAggregateUsageBaseline??W.turnUsageBaseline,G))}if(f.type==="iteration_end"&&Y)$.persistMessages(Q,W?.agent.getMessages()??[],W?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:Q,event:f,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(Y?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:JX(f),ts:Date.now()}})}function $1($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as wL}from"@cline/shared";function XX($){let f="";for(let J=0;J<$.length;J+=1)f+=String.fromCharCode($[J]??0);return btoa(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function UD($){let J=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(Q)}function DD($=32){let f=new Uint8Array($);return crypto.getRandomValues(f),XX(f)}async function pf(){let $=DD(),f=XX(await UD($));return{verifier:$,challenge:f}}function rf($){return $.endsWith("/")?$.slice(0,-1):$}function I1($,f){return new URL(f,`${rf($)}/`).toString()}function v2($,f={}){let J=$.trim();if(!J)return{};try{let Q=new URL(J);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:f.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(f.allowHashCodeState&&J.includes("#")){let[Q,Z]=J.split("#",2);return{code:Q||void 0,state:Z||void 0}}if(J.includes("code=")){let Q=new URLSearchParams(J);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:f.includeProvider?Q.get("provider")??void 0:void 0}}return{code:J}}function RD($){if(typeof atob==="function")try{return atob($)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from($,"base64").toString("utf8")}catch{return null}return null}function z0($){if(!$)return null;try{let f=$.split(".");if(f.length!==3)return null;let J=f[1];if(!J)return null;let Q=J.replace(/-/g,"+").replace(/_/g,"/"),Z=Q.padEnd(Q.length+(4-Q.length%4)%4,"="),W=RD(Z);if(!W)return null;return JSON.parse(W)}catch{return null}}function u2($){try{let f=JSON.parse($),J=f.error,Q=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof f.error_description==="string"?f.error_description:typeof f.message==="string"?f.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:Q,message:Z}}catch{return{}}}function x1($,f){return Date.now()>=$.expires-f}async function c2($){if(!$.onManualCodeInput){let W=await $.waitForCallback();return{code:W?.code,state:W?.state,provider:W?.provider,error:W?.error}}let f,J,Q=$.onManualCodeInput().then((W)=>{f=W,$.cancelWait()}).catch((W)=>{J=W instanceof Error?W:Error(String(W)),$.cancelWait()}),Z=await $.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if(f)return v2(f,$.parseOptions);if(await Q,J)throw J;if(f)return v2(f,$.parseOptions);return{}}O$();import{existsSync as WR}from"node:fs";import{discoverPluginModulePaths as jR,resolveConfiguredPluginModulePaths as XR,resolvePluginConfigSearchPaths as HR}from"@cline/shared/storage";import{resolve as gD}from"node:path";import{normalizePluginManifest as vD}from"@cline/shared";import{existsSync as P0,readFileSync as l2}from"node:fs";import{builtinModules as LD,createRequire as F7}from"node:module";import{dirname as f1,extname as w4,isAbsolute as OD,resolve as c}from"node:path";import{fileURLToPath as YX}from"node:url";import{PLUGIN_FILE_EXTENSIONS as zD}from"@cline/shared";var VX=f1(YX(import.meta.url)),_D=F7(import.meta.url),ND=c(VX,"..","..","..","..",".."),B7=qD(ND),TD=["@cline/sdk","@cline/agents","@cline/core","@cline/core/hub","@cline/core/hub/daemon-entry","@cline/core/telemetry","@cline/llms","@cline/llms/browser","@cline/shared","@cline/shared/automation","@cline/shared/browser","@cline/shared/storage","@cline/shared/db","@cline/shared/types"],P7=new Set(LD.flatMap(($)=>[$,$.replace(/^node:/,"")])),y4=new Set(zD),MD=["development","node","import","require","default"];function qD($){let f={},J={"@cline/sdk":c($,"packages/sdk/src/index.ts"),"@cline/agents":c($,"packages/agents/src/index.ts"),"@cline/core":c($,"packages/core/src/index.ts"),"@cline/llms":c($,"packages/llms/src/index.ts"),"@cline/shared":c($,"packages/shared/src/index.ts"),"@cline/shared/storage":c($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":c($,"packages/shared/src/db/index.ts")};for(let[Q,Z]of Object.entries(J))if(P0(Z))f[Q]=Z;for(let Q of["agents","core","llms","shared"]){let Z=c($,"packages",Q),W=c(Z,"package.json");if(!P0(W))continue;try{let j=JSON.parse(l2(W,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let X=c(Z,j.exports);if(P0(X))f[j.name]=X;continue}if(typeof j.exports!=="object")continue;for(let[X,H]of Object.entries(j.exports)){let Y=yD(Z,H);if(!Y)continue;let V=X==="."?j.name:`${j.name}/${X.replace(/^\.\//,"")}`;f[V]=Y}}catch{}}return f}function yD($,f){let J=U7(f);if(!J)return null;let Q=AX($,J);for(let Z of Q)if(P0(Z))return Z;return null}function U7($,f=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(f.has($))return null;f.add($);let J=$;for(let Q of MD){let Z=U7(J[Q],f);if(Z)return Z}return null}function AX($,f){let J=f.replace(/^\.\//,""),Q=[c($,f)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[c($,`${Z}.ts`),c($,`${Z}.tsx`),c($,`${Z}.mts`),c($,`${Z}.cts`),...Q]}return Q}function wD($){return Object.fromEntries(Object.entries($).sort(([f],[J])=>J.length-f.length))}function nf($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function d2($){if($.startsWith("@")){let[f,J]=$.split("/",3);return J?`${f}/${J}`:$}return $.split("/",1)[0]??$}function SD($){let f=d2($);if($===f)return".";return`.${$.slice(f.length)}`}function BX($){return d2($).startsWith("@cline/")}function G7($,f){let J=d2(f),Q=f1($);while(!0){let Z=c(Q,"node_modules",J);if(P0(Z)||P0(c(Z,"package.json")))return!0;let W=c(Q,"..");if(W===Q)return!1;Q=W}}function HX($){return K7($)!==null}function K7($){try{return _D.resolve($)}catch{}return hD($)}function hD($){let f=d2($),J=GX(f);if(!J)return null;let Q=c(J,"package.json");try{let Z=JSON.parse(l2(Q,"utf8")),W=SD($),j=W==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,W)?Z.exports[W]:void 0,X=U7(j)??(W==="."&&typeof Z.main==="string"?Z.main:null);if(!X)return null;let H=c(J,X),Y=[H,...AX(J,X).filter((V)=>V!==H)];for(let V of Y)if(P0(V))return V;return null}catch{return null}}function CD(){let $=[VX],f=process.env.CLINE_WRAPPER_PATH?.trim();if(f)$.push(f1(f1(f)));let J=process.execPath?.trim();if(J)$.push(f1(J));return[...new Set($.map((Q)=>c(Q)))]}function ED($,f){let J=$;while(!0){let Q=c(J,"package.json");if(P0(Q))try{if(JSON.parse(l2(Q,"utf8")).name===f)return J}catch{}let Z=c(J,"node_modules",f,"package.json");if(P0(Z))return f1(Z);let W=c(J,"..");if(W===J)return null;J=W}}function GX($){for(let f of CD()){let J=ED(f,$);if(J)return J}return null}function bD($){let J=f1($);for(let Q=0;Q<4;Q++){let Z=c(J,"package.json");if(P0(Z))try{let j=JSON.parse(l2(Z,"utf8"));return j!=null&&typeof j==="object"&&"cline"in j}catch{return!1}let W=c(J,"..");if(W===J)return!1;J=W}return!1}function KX($,f){let J=f.startsWith("file:")?YX(f):OD(f)?f:c(f1($),f);if(P0(J)&&y4.has(w4(J)))return J;for(let Q of y4){let Z=`${J}${Q}`;if(P0(Z))return Z}for(let Q of y4){let Z=c(J,`index${Q}`);if(P0(Z))return Z}return null}function FX($){let f=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of J)for(let Z of $.matchAll(Q)){let W=Z[1];if(W)f.add(W)}return[...f]}function kD($){return w4($)!==".ts"}function PX($,f,J=new Set){if(J.has($)||!P0($))return;if(J.add($),!y4.has(w4($)))return;let Q=l2($,"utf8"),Z=kD($);for(let W of FX(Q)){if(W.startsWith("node:")||P7.has(W))continue;if(nf(W)){if(!Z)continue;if(Object.hasOwn(B7,W)||Object.hasOwn(B7,d2(W))||G7($,W)||BX(W)&&HX(W)||f&&HX(W))continue;throw Error(`Cannot find module '${d2(W)}'`)}let j=KX($,W);if(j)PX(j,f,J)}}function UX($,f=new Set,J=new Set){if(f.has($)||!P0($))return J;if(f.add($),!y4.has(w4($)))return J;let Q=l2($,"utf8");for(let Z of FX(Q)){if(J.add(Z),nf(Z))continue;let W=KX($,Z);if(W)UX(W,f,J)}return J}function ID($,f){let J=F7($),Q={},Z=UX($),W=new Set(TD);for(let[j,X]of Object.entries(B7)){try{J.resolve(j);continue}catch{}Q[j]=X}for(let j of Z)if(nf(j)&&(BX(j)||f))W.add(j);for(let j of W){if(Object.hasOwn(Q,j)||G7($,j))continue;let X=K7(j);if(X)Q[j]=X}if(!f)return Q;for(let j of Z){if(!nf(j)||Object.hasOwn(Q,j)||G7($,j)||j.startsWith("node:")||P7.has(j))continue;let X=K7(j);if(X)Q[j]=X}return Q}function xD($){let f=w4($);return f===".ts"||f===".tsx"||f===".mts"||f===".cts"}var m1;function mD(){if(m1!==void 0)return m1;let $=GX("jiti");if(!$)return m1=null,null;let f=c($,"dist","babel.cjs");if(!P0(f))return m1=null,null;try{let Q=F7(f)(f);m1=typeof Q==="function"?Q:null}catch{m1=null}return m1}async function DX($,f={}){let J=!bD($);PX($,J);let Q=ID($,J),Z=wD(Q),W=await import("jiti"),j=typeof W==="function"?W:typeof W.default==="function"?W.default:void 0;if(!j)throw Error("Unable to load jiti");let X=Object.entries(Z).filter(([,A])=>xD(A)).map(([A])=>A),H=mD(),Y=H?(A)=>H({...A,interopDefault:!0}):void 0;return await j($,{alias:Z,cache:f.useCache,requireCache:f.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...P7],transformModules:X,tryNative:!1,...Y?{transform:Y}:{}}).import($,{})}function RX($,f){if(!$)return!0;if($.providerIds?.length){if(!f?.providerId||!$.providerIds.includes(f.providerId))return!1}if($.modelIds?.length){if(!f?.modelId||!$.modelIds.includes(f.modelId))return!1}return!0}function LX($){return typeof $==="object"&&$!==null}function D7($){return Array.isArray($)&&$.every((f)=>typeof f==="string")}function uD($,f){if(!LX($.manifest))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);if(!D7($.manifest.capabilities))throw Error(`Invalid plugin module at ${f}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${f}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!D7($.manifest.providerIds))throw Error(`Invalid plugin module at ${f}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!D7($.manifest.modelIds))throw Error(`Invalid plugin module at ${f}: manifest.modelIds must be a string array when provided`)}function cD($,f){if(!LX($))throw Error(`Invalid plugin module at ${f}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${f}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);uD($,f)}async function S4($,f={}){let J=gD(f.cwd??process.cwd(),$),Q=await DX(J,{useCache:f.useCache}),Z=f.exportName??"plugin",W=Q.default??Q[Z];cD(W,J);let j=W,X=j.setup,H=X?(Y,V)=>{let A={...f.session,...V.session},B={...V,session:Object.keys(A).length>0?A:void 0,client:f.client??V.client,user:f.user??V.user,workspaceInfo:f.workspaceInfo??V.workspaceInfo,automation:f.automation??V.automation,logger:f.logger??V.logger,telemetry:f.telemetry??V.telemetry};return X(Y,B)}:void 0;return{...j,manifest:vD(j.manifest),setup:H}}async function af($,f={}){return(await g1($,f)).plugins}async function g1($,f={}){let J=[],Q=[],Z=new Map,W=0;for(let j of $)try{let X=await S4(j,f);if(!RX(X.manifest,f))continue;let H=Z.get(X.name);if(H)Q.push({type:"duplicate_plugin_override",pluginName:X.name,pluginPath:j,overriddenPluginPath:H.pluginPath,message:`Plugin "${X.name}" from ${j} overrides ${H.pluginPath}`});Z.set(X.name,{plugin:X,pluginPath:j,order:W++})}catch(X){let H=X instanceof Error?X.message:String(X);J.push({pluginPath:j,phase:"load",message:H,stack:X instanceof Error?X.stack:void 0})}return{plugins:[...Z.values()].sort((j,X)=>j.order-X.order).map((j)=>j.plugin),failures:J,warnings:Q}}import{existsSync as z7}from"node:fs";import{createRequire as qX}from"node:module";import{dirname as tf,join as r2}from"node:path";import{fileURLToPath as iD}from"node:url";var TX={};y(TX,{resolveSubprocessRuntimeExecutable:()=>R7,buildSubprocessSandboxCommand:()=>NX,SubprocessSandbox:()=>p2,CLINE_JS_RUNTIME_PATH_ENV:()=>_X});import{spawn as dD}from"node:child_process";import{basename as lD}from"node:path";import{augmentNodeCommandForDebug as pD,withResolvedClineBuildEnv as rD}from"@cline/shared";function OX($){if($ instanceof Error)return $;return Error(String($))}var _X="CLINE_JS_RUNTIME_PATH";function zX($){let f=$?.trim();if(!f)return!1;let J=lD(f).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function R7($={}){let f=$.env??process.env,J=$.runtimeExecutable?.trim()||f[_X]?.trim();if(J)return J;let Q=$.execPath?.trim()||process.execPath;if(zX(Q))return Q;for(let Z of[f.BUN_EXEC_PATH,f.npm_node_execpath,f.NODE]){let W=Z?.trim();if(W&&zX(W))return W}return"node"}function NX($,f={}){let J=R7({env:f.env,execPath:f.execPath,runtimeExecutable:f.runtimeExecutable});return pD([J,...$],{env:f.env,execArgv:f.execArgv,debugRole:f.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class p2{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let f=this.pending.get($);if(!f)return;if(this.pending.delete($),f.timeout)clearTimeout(f.timeout);return f}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],f=NX($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=dD(f[0]??R7(this.options),f.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:rD(process.env)});this.process=J;let Q="",Z=(W)=>{let j=Q+W;Q=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(W)=>{Z(W)}),J.on("message",(W)=>{this.onMessage(W)}),J.on("error",(W)=>{this.failPending(Error(`${this.processLabel} process error: ${OX(W).message}`))}),J.on("exit",(W,j)=>{this.process=null;let X=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(W)}, signal=${String(j)})${X?`: ${X}`:""}`))})}async call($,f,J={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,W={type:"call",id:Z,method:$,args:f};return await new Promise((j,X)=>{let H={resolve:(Y)=>j(Y),reject:X};if((J.timeoutMs??0)>0)H.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${$}`))},J.timeoutMs);this.pending.set(Z,H),Q.send(W,(Y)=>{if(!Y)return;let V=this.clearPendingRequest(Z);if(!V)return;V.reject(Error(`${this.processLabel} failed to send call "${$}": ${OX(Y).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((f)=>{let J=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}f()},300);$.once("exit",()=>{clearTimeout(J),f()});try{$.kill("SIGTERM")}catch{clearTimeout(J),f()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let f=this.clearPendingRequest($.id);if(!f)return;if($.ok){f.resolve($.result);return}f.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[f,J]of this.pending.entries()){if(this.pending.delete(f),J.timeout)clearTimeout(J.timeout);J.reject($)}}}function nD($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function sf($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function aD(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function tD(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let J=qX($).resolve(`${aD()}/package.json`),Q=r2(tf(J),"extensions","plugin-sandbox-bootstrap.js");return z7(Q)?Q:void 0}catch{return}}function sD(){let $=process.execPath?.trim();if(!$)return;let f=r2(tf(tf($)),"extensions","plugin-sandbox-bootstrap.js");return z7(f)?f:void 0}function oD(){let $=tf(iD(import.meta.url)),f=qX(import.meta.url),J=[r2($,"plugin-sandbox-bootstrap.js"),r2($,"extensions","plugin-sandbox-bootstrap.js"),r2($,"agents","plugin-sandbox-bootstrap.js"),tD(),sD()];for(let W of J.filter((j)=>typeof j==="string"))if(z7(W))return{file:W};let Q=r2($,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=f.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
|
|
413
|
-
`)}}var
|
|
414
|
-
`).filter(Boolean);await Promise.allSettled(Z.map((
|
|
415
|
-
`),
|
|
416
|
-
`).map((
|
|
417
|
-
`,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??
|
|
409
|
+
${W}`;return J||W}function bR($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return{};return{beforeRun:async(J)=>{for(let W of f){let Z=await W.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let W of f)await W.afterRun?.(J)},beforeModel:async(J)=>{let W=J.request,Z;for(let Q of f){let j=await Q.beforeModel?.({...J,request:W});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},W={...W,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...W.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let W of f){let Z=await W.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let W=J.input,Z;for(let Q of f){let j=await Q.beforeTool?.({...J,input:W});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))W=j.input}return Z},afterTool:async(J)=>{let W=J.result,Z;for(let Q of f){let j=await Q.afterTool?.({...J,result:W});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)W=j.result}return Z},onEvent:async(J)=>{for(let W of f)await W.onEvent?.(J)}}}class Z1{config;agentId;parentAgentId;logger;telemetry;conversation;mistakeTracker;loopTracker;loopDetectionDisabled;messageBuilder;contributionRegistry;extensionsInitialized=!1;listeners=new Set;createAgentRuntimeImpl;activeRunId=null;running=!1;abortRequested=!1;abortReason;activeRuntime=null;activeRunPromise=null;eventAdapter=new NZ;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,f={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=f.logger??$.logger,this.telemetry=f.telemetry??$.telemetry,this.createAgentRuntimeImpl=f.createAgentRuntimeImpl??wR,this.conversation=new OZ($.initialMessages),this.messageBuilder=new DZ,this.contributionRegistry=SR({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new TZ({maxConsecutiveMistakes:J,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,j,H)=>kR(this.logger,Q,j,H),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(Q,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q}]})}});let W=$.execution?.loopDetection;this.loopDetectionDisabled=W===!1;let Z=W===!1||W===void 0?void 0:W;this.loopTracker=new zZ(Z)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let f=new Set(this.config.tools.map((W)=>W.name)),J=[...this.config.tools];for(let W of $)if(!f.has(W.name))J.push(W),f.add(W.name);this.config={...this.config,tools:J}}updateConnection($){let f={...this.config};if($.providerId!==void 0)f.providerId=$.providerId;if($.modelId!==void 0)f.modelId=$.modelId;if($.apiKey!==void 0)f.apiKey=$.apiKey;if($.baseUrl!==void 0)f.baseUrl=$.baseUrl;if($.headers!==void 0)f.headers=$.headers;if($.providerConfig!==void 0)f.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)f.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=f}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let f=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=f,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(f)}async shutdown($,f){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,f,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!1})}continue($,f,J){return this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let f of this.contributionRegistry.getRegisteredRules()){let J=await CR(f);if(J)$.push(J)}return ER(this.config.systemPrompt,$)}executeRun($){let f;return f=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===f)this.activeRunPromise=null}),this.activeRunPromise=f,f}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let f=new Date,J=$.userMessage;if(J!==void 0){let F=await xR(J,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let W=await this.composeSystemPrompt(),Z=ej(this.config,this.logger,this.telemetry),Q=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let F of Q)j.set(F.name,F);for(let F of this.config.tools)j.set(F.name,F);let H=this.conversation.getConversationId(),X=jH(this.config),Y=Array.from(j.values()),A=f6(this.conversation.getMessages()),V=WH({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:H,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:Y,toolContextMetadata:{modelSupportsImages:X?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[Oj]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(X,Y),initialMessages:A,systemPrompt:W}),B=this.createAgentRuntimeImpl(V);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let K=B.subscribe((F)=>{this.handleRuntimeEvent(F)}),G,R;try{if($.isContinue)G=await B.continue(void 0);else G=await B.run("")}catch(F){R=F instanceof Error?F:Error(String(F))}finally{K();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(G&&G.messages.length>0){let F=cf(G.messages);this.conversation.replaceMessages(F)}let P=new Date;try{return this.buildLegacyResult({runResult:G,thrownError:R,startedAt:f,endedAt:P})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=bR([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((f)=>f.hooks)]);return{...$,beforeModel:async(f)=>{let J=await $.beforeModel?.(f);if(J?.stop)return J;let W=J?.messages??f.request.messages,Z=await this.prepareMessagesForModelRequest(W);return{...J,messages:Z}}}}createRuntimePrepareTurn($,f){let J=this.config.prepareTurn;if(!J)return;return async(W)=>{let Z=cf(W.messages),Q=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:W.agentId,conversationId:W.conversationId??this.conversation.getConversationId(),parentAgentId:W.parentAgentId??null,iteration:W.iteration,messages:Z,apiMessages:Q,abortSignal:W.signal??new AbortController().signal,systemPrompt:W.systemPrompt??"",tools:f,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:W.emitStatusNotice});if(!j)return;return{...j.messages?{messages:f6(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let f=await this.prepareProviderMessagesForApi(J6($));return f6(f)}async prepareProviderMessagesForApi($){let f=$,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let W of J)f=await W.build(f);return this.messageBuilder.buildForApi(f)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let f=this.toolStartedAt.get($.toolCall.toolCallId),J=new Date,W=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let Z=$.message.content.find((X)=>X.type==="tool-result"),Q=Z?.type==="tool-result"&&Z.isError===!0,j=Q?hR(Z?.type==="tool-result"?Z.output:void 0):void 0,H={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:W,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:f===void 0?0:J.getTime()-f.getTime(),startedAt:f??J,endedAt:J};if(this.currentRunToolCalls.push(H),Q){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let f=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if(f>0&&J===0){let W=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${f} tool call(s) failed${W?`: ${W}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let f of this.eventAdapter.translate($))this.emitLegacyEvent(f)}syncConversationFromRuntimeMessage($,f){if($.length>0){this.conversation.replaceMessages(cf($));return}if(f.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),W=cf(f).filter((Z)=>!Z.id||!J.has(Z.id));if(W.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...W])}emitLegacyEvent($){for(let f of this.listeners)try{f($)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall($,f,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let W=this.loopTracker.inspect({name:$,input:f});if(W.kind==="ok")return;if(W.kind==="soft"){if(W.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:W.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let f=await this.mistakeTracker.record($);if(f.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:f.message}]}),this.activeRuntime?.abort(f.reason??f.message)})}buildLegacyResult($){let{runResult:f,thrownError:J,startedAt:W,endedAt:Z}=$,Q=Z.getTime()-W.getTime(),j=J?"error":IR(f),H=f?.outputText||(f?.status==="failed"?f.error?.message:void 0)||"",X=f?{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost}:this.currentRunUsage,Y=f?cf(f.messages):this.conversation.getMessages(),A=jH(this.config);if(J)throw J;return{text:H,usage:X,messages:Y,toolCalls:this.currentRunToolCalls,iterations:f?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:A},startedAt:W,endedAt:Z,durationMs:Q}}}function kR($,f,J,W){if(!$)return;if(f==="debug"){$.debug(J,W);return}if(f==="error"&&$.error){$.error(J,W);return}let Z=f==="warn"?"warn":f==="error"?"error":"info";$.log(J,{...W,severity:Z})}function IR($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function xR($,f,J,W){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => QH);return Z($,f,J,W)}function jH($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let f=UZ($);if(f?.[$.modelId])return f[$.modelId];return}import{buildClineSystemPrompt as HH}from"@cline/shared";function XH($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return HH({ide:f.clineIdeName?.trim()||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,rules:`# Team Teammate Role
|
|
410
|
+
${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function YH($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return HH({ide:f.clineIdeName||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,overridePrompt:J,metadata:f.workspaceMetadata,platform:f.clinePlatform})}function df($){let f={...$};return{getRuntimeConfig:()=>f,getConnectionConfig:()=>({providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking}),updateConnectionDefaults:(J)=>{f={...f,...J}}}}function u1($){let f=$.configProvider.getRuntimeConfig(),J=$.kind==="teammate"?XH($.prompt,f):YH($.prompt,f);return{...$.configProvider.getConnectionConfig(),systemPrompt:J,tools:$.tools,maxIterations:$.maxIterations??f.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:f.hooks,extensions:f.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:f.logger,role:$.role}}function lf($){let f=u1($),J=new Z1(f);if(f.onEvent)J.subscribeEvents(f.onEvent);return J}var vR=MZ.object({systemPrompt:MZ.string().describe("System prompt defining the sub-agent's behavior"),task:MZ.string().describe("Task for the sub-agent to complete")});function Q1($){return mR({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:gR(vR),execute:async(f,J)=>{let W=$.createSubAgentTools?await $.createSubAgentTools(f,J):$.subAgentTools??[],Z=lf({kind:"subagent",prompt:f.systemPrompt,configProvider:$.configProvider,tools:W,maxIterations:$.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),Q=Z.getAgentId(),j=Z.getConversationId(),H=J.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:Q,conversationId:j,parentAgentId:H,input:f})}catch{}try{let X=await Z.run(f.task),Y={text:X.text,iterations:X.iterations,finishReason:X.finishReason,usage:{inputTokens:X.usage.inputTokens,outputTokens:X.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:Q,conversationId:j,parentAgentId:H,input:f,result:Y,agentResult:X})}catch{}return Y}catch(X){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:Q,conversationId:j,parentAgentId:H,input:f,error:X instanceof Error?X:Error(String(X))})}catch{}throw X}},timeoutMs:300000,retryable:!1})}import{createTool as Q0,TEAM_AWAIT_TIMEOUT_MS as uR,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as cR,TEAM_RUN_TEXT_PREVIEW_LIMIT as dR,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as lR,TeamAttachOutcomeFragmentInputSchema as AH,TeamAwaitRunsInputSchema as VH,TeamBroadcastInputSchema as BH,TeamBroadcastToolResultSchema as pR,TeamCancelRunInputSchema as KH,TeamCancelRunToolResultSchema as rR,TeamCleanupInputSchema as GH,TeamCleanupToolResultSchema as iR,TeamCreateOutcomeInputSchema as PH,TeamCreateOutcomeToolResultSchema as nR,TeamFinalizeOutcomeInputSchema as FH,TeamFinalizeOutcomeToolResultSchema as aR,TeamListOutcomesInputSchema as UH,TeamListRunsInputSchema as RH,TeamMailboxMessageToolResultSchema as tR,TeamMissionLogInputSchema as DH,TeamMissionLogToolResultSchema as sR,TeamOutcomeFragmentToolResultSchema as LH,TeamOutcomeToolResultSchema as oR,TeamReadMailboxInputSchema as OH,TeamReviewOutcomeFragmentInputSchema as _H,TeamRunTaskInputSchema as zH,TeamRunTaskToolResultSchema as yZ,TeamRunToolSummarySchema as qZ,TeamSendMessageInputSchema as TH,TeamSendMessageToolResultSchema as eR,TeamShutdownTeammateInputSchema as NH,TeamSimpleAgentStatusToolResultSchema as MH,TeamSpawnTeammateInputSchema as yH,TeamStatusInputSchema as qH,TeamStatusToolResultSchema as $D,TeamTaskInputSchema as wH,TeamTaskToolResultSchema as x8,validateWithZod as E,zodToJsonSchema as j0}from"@cline/shared";function SH($,f){let J=$.replace(/\s+/g," ").trim();if(J.length<=f)return J;return`${J.slice(0,Math.max(0,f-3)).trimEnd()}...`}function c1($,f){if($===void 0)throw Error(`Missing required field: ${f}`);return $}function fD($){let f=$.result;if(!f)return;return{textPreview:SH(f.text,dR),iterations:f.iterations,finishReason:f.finishReason,durationMs:f.durationMs,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost}}}function W6($){return $?.toISOString()}function wZ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:SH($.message,cR),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:W6($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:W6($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:W6($.heartbeatAt),lastProgressAt:W6($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:fD($)}}function JD($){if($.status==="failed")throw Error(`Run "${$.id}" failed${$.error?`: ${$.error}`:""}`);if($.status==="cancelled")throw Error(`Run "${$.id}" was cancelled${$.error?`: ${$.error}`:""}`);if($.status==="interrupted")throw Error(`Run "${$.id}" was interrupted${$.error?`: ${$.error}`:""}`)}var pf=["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 hH($){let f=[];if($.createBaseTools)f.push(...$.createBaseTools());f.push(...d1({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:u1({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:f,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function rf($){let f=$.leadAgentId??"lead",J=$.restoredFromPersistence===!0,W=d1({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),Z=[];for(let Q of $.restoredTeammates??[]){if($.runtime.isTeammateActive(Q.agentId))continue;hH({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Q}),Z.push(Q.agentId)}return{tools:W,restoredFromPersistence:J,restoredTeammates:Z}}function d1($){let f=$.allowSpawn??!0,J=$.includeSpawnTool??!0,W=$.includeManagementTools??!0,Z=[];if(J)Z.push(Q0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:j0(yH),execute:async(j)=>{let H=E(yH,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!f)throw Error("Spawning teammates is disabled in this context.");let X={agentId:H.agentId,rolePrompt:H.rolePrompt};if(hH({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:X}),!W)$.onLeadToolsUnlocked?.(d1({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return E(MH,{agentId:H.agentId,status:"spawned"})}}));if(!W)return Z;Z.push(Q0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:j0(NH),execute:async(j)=>{let H=E(NH,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(H.agentId,H.reason),E(MH,{agentId:H.agentId,status:"stopped"})}})),Z.push(Q0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:j0(qH),execute:async(j)=>{return E(qH,j),E($D,$.runtime.getSnapshot())}})),Z.push(Q0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:j0(wH),execute:async(j)=>{let H=E(wH,j);switch(H.action){case"create":{let X=new Set(lR.create??[]),Y=Object.entries(j).filter(([V,B])=>X.has(V)&&B!=null).map(([V])=>V),A=$.runtime.createTask({title:c1(H.title,"title"),description:c1(H.description,"description"),dependsOn:H.dependsOn,assignee:H.assignee,createdBy:$.requesterId});return E(x8,{action:"create",taskId:A.id,status:A.status,...Y.length>0?{ignoredFields:Y,note:`Ignored fields for action=create: ${Y.join(", ")}`}:{}})}case"list":return E(x8,{action:"list",tasks:$.runtime.listTaskItems({status:H.status,assignee:H.assignee})});case"claim":{let X=$.runtime.claimTask(c1(H.taskId,"taskId"),$.requesterId);return E(x8,{action:"claim",taskId:X.id,status:X.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let X=$.runtime.completeTask(c1(H.taskId,"taskId"),$.requesterId,c1(H.summary,"summary"));return E(x8,{action:"complete",taskId:X.id,status:X.status})}case"block":{let X=$.runtime.blockTask(c1(H.taskId,"taskId"),$.requesterId,c1(H.reason,"reason"));return E(x8,{action:"block",taskId:X.id,status:X.status})}}}}));let Q=new Map;return Z.push(Q0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:j0(zH),execute:async(j)=>{let H=E(zH,j);if(H.runMode==="async"){let A=$.runtime.startTeammateRun(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:$.requesterId,continueConversation:H.continueConversation||void 0});return E(yZ,{agentId:H.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${H.agentId} and queued as ${A.id}.`,runId:A.id})}let X=Q.get(H.agentId);if(X){let A=await X;return E(yZ,{...A,status:"joined",deduped:!0,message:`Task for ${H.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let Y=$.runtime.routeToTeammate(H.agentId,H.task,{taskId:H.taskId||void 0,fromAgentId:$.requesterId,continueConversation:H.continueConversation||void 0}).then((A)=>E(yZ,{agentId:H.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${H.agentId} and completed in sync mode.`,text:A.text,iterations:A.iterations})).finally(()=>{Q.delete(H.agentId)});return Q.set(H.agentId,Y),await Y}})),Z.push(Q0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:j0(KH),execute:async(j)=>{let H=E(KH,j),X=$.runtime.cancelRun(H.runId,H.reason);return E(rR,{runId:X.id,status:X.status})}})),Z.push(Q0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:j0(RH),execute:async(j)=>E(qZ.array(),$.runtime.listRuns(E(RH,j)).map(wZ))})),Z.push(Q0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:j0(VH),timeoutMs:uR,execute:async(j)=>{let H=E(VH,j);if(H.runId){let A=await $.runtime.awaitRun(H.runId);return JD(A),E(qZ,wZ(A))}let X=await $.runtime.awaitAllRuns(),Y=X.filter((A)=>["failed","cancelled","interrupted"].includes(A.status));if(Y.length>0){let A=Y.map((V)=>`${V.id}:${V.status}${V.error?`(${V.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${A}`)}return E(qZ.array(),X.map(wZ))}})),Z.push(Q0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:j0(TH),execute:async(j)=>{let H=E(TH,j),X=$.runtime.sendMessage($.requesterId,H.toAgentId,H.subject,H.body,H.taskId??void 0);return E(eR,{id:X.id,toAgentId:X.toAgentId})}})),Z.push(Q0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:j0(BH),execute:async(j)=>{let H=E(BH,j),X=$.runtime.broadcast($.requesterId,H.subject,H.body,{taskId:H.taskId??void 0});return E(pR,{delivered:X.length})}})),Z.push(Q0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:j0(OH),execute:async(j)=>{let H=E(OH,j);return E(tR.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:H.unreadOnly,markRead:!0}))}})),Z.push(Q0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:j0(DH),execute:async(j)=>{let H=E(DH,j),X=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:H.taskId||void 0,kind:H.kind,summary:H.summary,evidence:H.evidence?.length?H.evidence:void 0,nextAction:H.nextAction||void 0});return E(sR,{id:X.id})}})),Z.push(Q0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:j0(GH),execute:async(j)=>{if(E(GH,j),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),E(iR,{status:"cleaned"})}})),Z.push(Q0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:j0(PH),execute:async(j)=>{let H=E(PH,j),X=$.runtime.createOutcome({title:H.title,requiredSections:H.requiredSections,createdBy:$.requesterId});return E(nR,{outcomeId:X.id,status:X.status,requiredSections:X.requiredSections})}})),Z.push(Q0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:j0(AH),execute:async(j)=>{let H=E(AH,j),X=$.runtime.attachOutcomeFragment({outcomeId:H.outcomeId,section:H.section,sourceAgentId:$.requesterId,sourceRunId:H.sourceRunId||void 0,content:H.content});return E(LH,{fragmentId:X.id,status:X.status})}})),Z.push(Q0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:j0(_H),execute:async(j)=>{let H=E(_H,j),X=$.runtime.reviewOutcomeFragment({fragmentId:H.fragmentId,reviewedBy:$.requesterId,approved:H.approved});return E(LH,{fragmentId:X.id,status:X.status})}})),Z.push(Q0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:j0(FH),execute:async(j)=>{let H=E(FH,j),X=$.runtime.finalizeOutcome(H.outcomeId);return E(aR,{outcomeId:X.id,status:X.status})}})),Z.push(Q0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:j0(UH),execute:async(j)=>{return E(UH,j),E(oR.array(),$.runtime.listOutcomes())}})),Z}function Z6($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}function CH($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var WD=[{id:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:Q1({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...pf]}],ZD={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function QD($){return $==="plan"||$==="yolo"?$:"act"}function bH($){let f=QD($.mode),J=m0[E$({mode:f})],W=uf($.providerId??"",$.modelId??"",f,vf);return{mode:f,flags:{...J,...W,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function EH($,f){if(f.disabledToolIds?.has($))return!1;let{flags:J}=bH(f);if($==="spawn_agent")return J.enableSpawnAgent===!0;if($==="teams")return J.enableAgentTeams===!0;if($==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let W=ZD[$];return W?J[W]===!0:!1}function jD($,f){if($.id==="editor"){let{flags:J}=bH(f),W=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...$,defaultEnabled:EH($.id,f),headlessToolNames:[W?"apply_patch":"editor"]}}return{...$,defaultEnabled:EH($.id,f)}}function l1($={}){return WD.map((f)=>jD(f,$))}function Q6($={}){return l1($).filter((f)=>f.defaultEnabled).map((f)=>f.id)}function j6($){if(!$.enabled)return new Set;let f=l1($.availabilityContext),J=new Set(f.map((W)=>W.id));if(!$.allowlist||$.allowlist.length===0)return new Set(f.filter((W)=>W.defaultEnabled).map((W)=>W.id));for(let W of $.allowlist)if(!J.has(W))throw Error(`Unknown tool "${W}". Available tools: ${f.map((Z)=>Z.id).join(", ")}`);return new Set($.allowlist)}function m8($,f={}){return l1(f).filter((J)=>$.has(J.id)).flatMap((J)=>J.headlessToolNames)}function H6($,f={}){return m8($,f)}function p1($={}){let{executorOptions:f={},executors:J,...W}=$,Z={...gf(f),...J??{}};return J1({...W,executors:Z})}import{mkdirSync as BD,writeFileSync as KD}from"node:fs";import{dirname as GD}from"node:path";import{normalizeUserInput as PD}from"@cline/shared";import{nanoid as FD}from"nanoid";var IH={};w(IH,{sanitizeSessionToken:()=>r1,parseTeamTaskSubSessionId:()=>af,parseSubSessionId:()=>v8,makeTeamTaskSubSessionId:()=>g8,makeSubSessionId:()=>nf,deriveSubsessionStatus:()=>u8});import{nanoid as YD}from"nanoid";function r1($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function nf($,f){let J=r1($),W=r1(f),Z=`${J}__${W}`;return Z.length>180?Z.slice(0,180):Z}function g8($,f){let J=r1($),W=r1(f);return`${J}__teamtask__${W}__${YD(6)}`}function af($){let J=$.indexOf("__teamtask__");if(J<=0)return null;let W=$.slice(0,J),Z=$.slice(J+12),Q=Z.lastIndexOf("__");if(Q<=0)return null;let j=Z.slice(0,Q),H=Z.slice(Q+2);if(!W||!j||!H)return null;return{rootSessionId:W,agentId:j,teamTaskId:H}}function v8($){if(af($))return null;let f="__",J=$.indexOf(f);if(J<=0)return null;let W=$.slice(0,J),Z=$.slice(J+f.length);if(!W||!Z)return null;return{rootSessionId:W,agentId:Z}}function u8($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let f=String($.reason??"").toLowerCase();if(f.includes("cancel")||f.includes("abort")||f.includes("interrupt"))return"cancelled";if(f.includes("fail")||f.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as t}from"zod";var gH={};w(gH,{isTerminalSessionStatus:()=>mH,isNonTerminalSessionStatus:()=>W0,SessionSource:()=>P0,SESSION_STATUSES:()=>c8,NON_TERMINAL_SESSION_STATUSES:()=>xH});import{SESSION_STATUS_VALUES as AD}from"@cline/shared";var c8=AD,xH=["idle","running","pending"];function mH($){return!xH.includes($)}function W0($){return!mH($)}var P0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var VD=t.enum(c8),M0=t.object({version:t.literal(1),session_id:t.string().min(1),source:t.string().min(1),pid:t.number().int(),started_at:t.string().min(1),ended_at:t.string().min(1).optional(),exit_code:t.number().int().nullable().optional(),status:VD,interactive:t.boolean(),provider:t.string().min(1),model:t.string().min(1),cwd:t.string().min(1),workspace_root:t.string().min(1),team_name:t.string().min(1).optional(),enable_tools:t.boolean(),enable_spawn:t.boolean(),enable_teams:t.boolean(),prompt:t.string().optional(),metadata:t.record(t.string(),t.unknown()).optional(),messages_path:t.string().min(1).optional()});function vH($){if(!$)return!1;return Object.values($).some((f)=>typeof f==="function")}function hZ($,f){let J=[...$??[],...f??[]];if(J.length===0)return;let W=[],Z=new Set;for(let Q of J){if(Z.has(Q.name))continue;Z.add(Q.name),W.push(Q)}return W}function uH($){return JSON.stringify($,(f,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function b$($){return typeof $==="string"&&$.trim()?$.trim():void 0}function SZ($,f){let J={...$};J.id=b$(J.id)??FD();let W=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:b$(W?.id)??b$(J.modelId)??b$(f?.id),provider:b$(W?.provider)??b$(J.providerId)??b$(f?.provider),family:b$(W?.family)??b$(f?.family)};if(delete J.providerId,delete J.modelId,Z.id&&Z.provider)J.modelInfo={id:Z.id,provider:Z.provider,...Z.family?{family:Z.family}:{}};else delete J.modelInfo;return J}function X6($){return $.map((f)=>SZ(f))}function Y6($,f,J=[]){let W=$.map((X,Y)=>{let A=J[Y],B=A?.role===X.role&&JSON.stringify(A.content)===JSON.stringify(X.content)?{...A,...X}:{...X};return SZ(B)}),Z=J.length,Q=[];for(let X=Z;X<W.length;X+=1)if(W[X]?.role==="assistant")Q.push(X);if(Q.length===0){let X=[...W].reverse().findIndex((Y)=>Y.role==="assistant");if(X===-1)return W;Q.push(W.length-1-X)}let j=Q[Q.length-1],H=Q.some((X)=>W[X]?.metrics);for(let X of Q){let Y=W[X],A=Y.metrics;if(!A&&X===j&&!H){let V=f.usage;A={inputTokens:V.inputTokens,outputTokens:V.outputTokens,cacheReadTokens:V.cacheReadTokens??0,cacheWriteTokens:V.cacheWriteTokens??0,cost:V.totalCost}}W[X]={...SZ(Y,{id:f.model.id,provider:f.model.provider,family:f.model.info?.family}),...A?{metrics:A}:{},ts:Y.ts??f.endedAt.getTime()}}return W}function d8($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??void 0,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??void 0,parentAgentId:$.parentAgentId??void 0,agentId:$.agentId??void 0,conversationId:$.conversationId??void 0,isSubagent:$.isSubagent,prompt:$.prompt??void 0,metadata:$.metadata??void 0,messagesPath:$.messagesPath??void 0,updatedAt:$.updatedAt}}var UD=120;function i1($){let f=$?.trim();return f?f.slice(0,UD):void 0}function CZ($){let f=PD($??"").trim();if(!f)return;return i1(f.split(`
|
|
411
|
+
`)[0]?.trim())}function j1($){if(!$)return;let f={...$},J=i1(typeof f.title==="string"?f.title:void 0);if(J)f.title=J;else delete f.title;return Object.keys(f).length>0?f:void 0}function l8($){let f=j1($.metadata)??{},J=$.title!==void 0?i1($.title):CZ($.prompt);if(J)f.title=J;return Object.keys(f).length>0?f:void 0}function EZ($){let f=af($);if(f)return{agent:"teammate",sessionId:f.rootSessionId,taskType:"team"};let J=v8($);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function bZ($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:X6($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function cH($,f,J){BD(GD($),{recursive:!0}),KD($,`${JSON.stringify(bZ({updatedAt:f,context:J,messages:[]}),null,2)}
|
|
412
|
+
`,"utf8")}function dH($,f){return M0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:f?.endedAt??$.endedAt??void 0,exit_code:f?.exitCode??$.exitCode??void 0,status:f?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:f?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function lH($,f,J){let W=0;while(!0){let Z=await $();if(Z===void 0)return{updated:!1};let Q=await f(Z);if(typeof Q==="object"&&Q!==null&&"updated"in Q&&Q.updated===!1){if(W+=1,W>=J)return Q;continue}return Q}}L0();var pH={};w(pH,{summarizeUsageFromMessages:()=>sf,sumUsageTotals:()=>p8,getCurrentContextSize:()=>kZ,createInitialAccumulatedUsage:()=>B0,accumulateUsageTotals:()=>H0});function B0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function H0($,f){return{inputTokens:$.inputTokens+Math.max(0,f.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,f.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,f.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,f.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,f.totalCost??0)}}function p8($){let f=B0();for(let J of $)f=H0(f,J);return f}function tf($){return typeof $==="number"&&Number.isFinite($)?$:0}function sf($){let f=B0();for(let J of $){let W=J.metrics;if(!W)continue;f=H0(f,{inputTokens:tf(W.inputTokens),outputTokens:tf(W.outputTokens),cacheReadTokens:tf(W.cacheReadTokens),cacheWriteTokens:tf(W.cacheWriteTokens),totalCost:tf(W.cost)})}return f}function kZ($){for(let f=$.length-1;f>=0;f-=1){let J=$[f];if(J?.role!=="assistant")continue;let W=tf(J.metrics?.inputTokens);return W>0?W:void 0}return}function RD($){if(!$||typeof $!=="object")return;let f=$,J=f.skill??f.skill_name??f.skillName;if(typeof J!=="string")return;let W=J.trim();return W.length>0?W:void 0}function IZ($){if(!$||typeof $!=="object")return{};let f=$;return{agentId:typeof f.agentId==="string"?f.agentId:void 0,conversationId:typeof f.conversationId==="string"?f.conversationId:void 0,parentAgentId:typeof f.parentAgentId==="string"?f.parentAgentId:void 0}}function k$($){let f=$.agentId?.trim();if(!f)return;let J=$.parentAgentId?.trim()||void 0,W=$.teamRole,Z="root";if(W==="teammate")Z="team_teammate";else if(W==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:f,agentKind:Z,conversationId:$.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:$.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:W,teamAgentId:$.teamAgentId?.trim()||void 0}}function DD($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function LD($){let f=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let J of f){let W=J?.trim();if(W)return W}return $.isPrimaryAgentEvent?"root":"unknown"}function xZ($,f,J){let{sessionId:W,config:Z,liveSession:Q,emit:j}=$,H=Z.telemetry,X=Q?.runtime.teamRuntime,Y=J?.isPrimaryAgentEvent??!0,A=IZ(f),V=k$({agentId:J?.agentId??A.agentId,conversationId:J?.conversationId??A.conversationId,parentAgentId:J?.parentAgentId??A.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??X?.getTeamId(),teamName:J?.teamName??X?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if(f.type==="content_start"&&f.contentType==="tool"&&f.toolName==="skills"){let B=RD(f.input);if(B)_4(H,{ulid:W,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...V})}if(f.type==="content_end"&&f.contentType==="tool"){let B=f.toolName??"unknown",K=!f.error;if(O4(H,{ulid:W,tool:B,autoApproved:void 0,success:K,modelId:Z.modelId,provider:Z.providerId,...V}),!K&&(B==="editor"||B==="apply_patch"))z4(H,{ulid:W,modelId:Z.modelId,provider:Z.providerId,errorType:f.error,...V})}if(f.type==="notice"&&f.reason==="api_error")e2(H,{ulid:W,model:Z.modelId,provider:Z.providerId,errorMessage:f.message,...V});if(f.type==="error")e2(H,{ulid:W,model:Z.modelId,provider:Z.providerId,errorMessage:f.error?.message??"unknown error",...V});if(f.type==="usage"&&Q?.turnUsageBaseline){let B=DD(f);if(Y){Q.turnPrimaryUsage=H0(Q.turnPrimaryUsage??B0(),B);let G=H0(Q.turnUsageBaseline,Q.turnPrimaryUsage);$.usageBySession.set(W,G),wf(H,{ulid:W,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...V}),D4(H,{ulid:W,tokensIn:f.inputTokens,tokensOut:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost,model:Z.modelId,...V})}else{let G=LD({isPrimaryAgentEvent:Y,overrides:J,eventMetadata:A}),R=Q.turnUsageByAgent??new Map;Q.turnUsageByAgent=R,R.set(G,H0(R.get(G)??B0(),B))}let K=H0(Q.turnPrimaryUsage??B0(),p8(Q.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(W,H0(Q.turnAggregateUsageBaseline??Q.turnUsageBaseline,K))}if(f.type==="iteration_end"&&Y)$.persistMessages(W,Q?.agent.getMessages()??[],Q?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:W,event:f,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(Y?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:W,stream:"agent",chunk:uH(f),ts:Date.now()}})}function H1($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as dO}from"@cline/shared";function rH($){let f="";for(let J=0;J<$.length;J+=1)f+=String.fromCharCode($[J]??0);return btoa(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function OD($){let J=new TextEncoder().encode($),W=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(W)}function _D($=32){let f=new Uint8Array($);return crypto.getRandomValues(f),rH(f)}async function A6(){let $=_D(),f=rH(await OD($));return{verifier:$,challenge:f}}function V6($){return $.endsWith("/")?$.slice(0,-1):$}function n1($,f){return new URL(f,`${V6($)}/`).toString()}function of($,f={}){let J=$.trim();if(!J)return{};try{let W=new URL(J);return{code:W.searchParams.get("code")??void 0,state:W.searchParams.get("state")??void 0,provider:f.includeProvider?W.searchParams.get("provider")??void 0:void 0}}catch{}if(f.allowHashCodeState&&J.includes("#")){let[W,Z]=J.split("#",2);return{code:W||void 0,state:Z||void 0}}if(J.includes("code=")){let W=new URLSearchParams(J);return{code:W.get("code")??void 0,state:W.get("state")??void 0,provider:f.includeProvider?W.get("provider")??void 0:void 0}}return{code:J}}function zD($){if(typeof atob==="function")try{return atob($)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from($,"base64").toString("utf8")}catch{return null}return null}function _0($){if(!$)return null;try{let f=$.split(".");if(f.length!==3)return null;let J=f[1];if(!J)return null;let W=J.replace(/-/g,"+").replace(/_/g,"/"),Z=W.padEnd(W.length+(4-W.length%4)%4,"="),Q=zD(Z);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function ef($){try{let f=JSON.parse($),J=f.error,W=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof f.error_description==="string"?f.error_description:typeof f.message==="string"?f.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:W,message:Z}}catch{return{}}}function a1($,f){return Date.now()>=$.expires-f}async function $2($){if(!$.onManualCodeInput){let Q=await $.waitForCallback();return{code:Q?.code,state:Q?.state,provider:Q?.provider,error:Q?.error}}let f,J,W=$.onManualCodeInput().then((Q)=>{f=Q,$.cancelWait()}).catch((Q)=>{J=Q instanceof Error?Q:Error(String(Q)),$.cancelWait()}),Z=await $.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if(f)return of(f,$.parseOptions);if(await W,J)throw J;if(f)return of(f,$.parseOptions);return{}}Z$();import{existsSync as R6,readFileSync as AL,statSync as VL}from"node:fs";import{basename as BL,dirname as F6,join as D6,resolve as U6}from"node:path";import{discoverPluginModulePaths as KL,resolveConfiguredPluginModulePaths as KX,resolvePluginConfigSearchPaths as GL,SKILLS_CONFIG_DIRECTORY_NAME as PL}from"@cline/shared/storage";import{resolve as dD}from"node:path";import{normalizePluginManifest as lD}from"@cline/shared";import{existsSync as F0,readFileSync as J2}from"node:fs";import{builtinModules as TD,createRequire as uZ}from"node:module";import{dirname as X1,extname as i8,isAbsolute as ND,resolve as c}from"node:path";import{fileURLToPath as nH}from"node:url";import{PLUGIN_FILE_EXTENSIONS as MD}from"@cline/shared";var aH=X1(nH(import.meta.url)),yD=uZ(import.meta.url),qD=c(aH,"..","..","..","..",".."),mZ=hD(qD),wD=["@cline/sdk","@cline/agents","@cline/core","@cline/core/hub","@cline/core/hub/daemon-entry","@cline/core/telemetry","@cline/llms","@cline/llms/browser","@cline/shared","@cline/shared/automation","@cline/shared/browser","@cline/shared/storage","@cline/shared/db","@cline/shared/types"],cZ=new Set(TD.flatMap(($)=>[$,$.replace(/^node:/,"")])),r8=new Set(MD),SD=["development","node","import","require","default"];function hD($){let f={},J={"@cline/sdk":c($,"packages/sdk/src/index.ts"),"@cline/agents":c($,"packages/agents/src/index.ts"),"@cline/core":c($,"packages/core/src/index.ts"),"@cline/llms":c($,"packages/llms/src/index.ts"),"@cline/shared":c($,"packages/shared/src/index.ts"),"@cline/shared/storage":c($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":c($,"packages/shared/src/db/index.ts")};for(let[W,Z]of Object.entries(J))if(F0(Z))f[W]=Z;for(let W of["agents","core","llms","shared"]){let Z=c($,"packages",W),Q=c(Z,"package.json");if(!F0(Q))continue;try{let j=JSON.parse(J2(Q,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let H=c(Z,j.exports);if(F0(H))f[j.name]=H;continue}if(typeof j.exports!=="object")continue;for(let[H,X]of Object.entries(j.exports)){let Y=CD(Z,X);if(!Y)continue;let A=H==="."?j.name:`${j.name}/${H.replace(/^\.\//,"")}`;f[A]=Y}}catch{}}return f}function CD($,f){let J=dZ(f);if(!J)return null;let W=tH($,J);for(let Z of W)if(F0(Z))return Z;return null}function dZ($,f=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(f.has($))return null;f.add($);let J=$;for(let W of SD){let Z=dZ(J[W],f);if(Z)return Z}return null}function tH($,f){let J=f.replace(/^\.\//,""),W=[c($,f)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[c($,`${Z}.ts`),c($,`${Z}.tsx`),c($,`${Z}.mts`),c($,`${Z}.cts`),...W]}return W}function ED($){return Object.fromEntries(Object.entries($).sort(([f],[J])=>J.length-f.length))}function B6($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function f2($){if($.startsWith("@")){let[f,J]=$.split("/",3);return J?`${f}/${J}`:$}return $.split("/",1)[0]??$}function bD($){let f=f2($);if($===f)return".";return`.${$.slice(f.length)}`}function sH($){return f2($).startsWith("@cline/")}function gZ($,f){let J=f2(f),W=X1($);while(!0){let Z=c(W,"node_modules",J);if(F0(Z)||F0(c(Z,"package.json")))return!0;let Q=c(W,"..");if(Q===W)return!1;W=Q}}function iH($){return vZ($)!==null}function vZ($){try{return yD.resolve($)}catch{}return kD($)}function kD($){let f=f2($),J=oH(f);if(!J)return null;let W=c(J,"package.json");try{let Z=JSON.parse(J2(W,"utf8")),Q=bD($),j=Q==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,Q)?Z.exports[Q]:void 0,H=dZ(j)??(Q==="."&&typeof Z.main==="string"?Z.main:null);if(!H)return null;let X=c(J,H),Y=[X,...tH(J,H).filter((A)=>A!==X)];for(let A of Y)if(F0(A))return A;return null}catch{return null}}function ID(){let $=[aH],f=process.env.CLINE_WRAPPER_PATH?.trim();if(f)$.push(X1(X1(f)));let J=process.execPath?.trim();if(J)$.push(X1(J));return[...new Set($.map((W)=>c(W)))]}function xD($,f){let J=$;while(!0){let W=c(J,"package.json");if(F0(W))try{if(JSON.parse(J2(W,"utf8")).name===f)return J}catch{}let Z=c(J,"node_modules",f,"package.json");if(F0(Z))return X1(Z);let Q=c(J,"..");if(Q===J)return null;J=Q}}function oH($){for(let f of ID()){let J=xD(f,$);if(J)return J}return null}function mD($){let J=X1($);for(let W=0;W<4;W++){let Z=c(J,"package.json");if(F0(Z))try{let j=JSON.parse(J2(Z,"utf8"));return j!=null&&typeof j==="object"&&"cline"in j}catch{return!1}let Q=c(J,"..");if(Q===J)return!1;J=Q}return!1}function eH($,f){let J=f.startsWith("file:")?nH(f):ND(f)?f:c(X1($),f);if(F0(J)&&r8.has(i8(J)))return J;for(let W of r8){let Z=`${J}${W}`;if(F0(Z))return Z}for(let W of r8){let Z=c(J,`index${W}`);if(F0(Z))return Z}return null}function $X($){let f=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let W of J)for(let Z of $.matchAll(W)){let Q=Z[1];if(Q)f.add(Q)}return[...f]}function gD($){return i8($)!==".ts"}function fX($,f,J=new Set){if(J.has($)||!F0($))return;if(J.add($),!r8.has(i8($)))return;let W=J2($,"utf8"),Z=gD($);for(let Q of $X(W)){if(Q.startsWith("node:")||cZ.has(Q))continue;if(B6(Q)){if(!Z)continue;if(Object.hasOwn(mZ,Q)||Object.hasOwn(mZ,f2(Q))||gZ($,Q)||sH(Q)&&iH(Q)||f&&iH(Q))continue;throw Error(`Cannot find module '${f2(Q)}'`)}let j=eH($,Q);if(j)fX(j,f,J)}}function JX($,f=new Set,J=new Set){if(f.has($)||!F0($))return J;if(f.add($),!r8.has(i8($)))return J;let W=J2($,"utf8");for(let Z of $X(W)){if(J.add(Z),B6(Z))continue;let Q=eH($,Z);if(Q)JX(Q,f,J)}return J}function vD($,f){let J=uZ($),W={},Z=JX($),Q=new Set(wD);for(let[j,H]of Object.entries(mZ)){try{J.resolve(j);continue}catch{}W[j]=H}for(let j of Z)if(B6(j)&&(sH(j)||f))Q.add(j);for(let j of Q){if(Object.hasOwn(W,j)||gZ($,j))continue;let H=vZ(j);if(H)W[j]=H}if(!f)return W;for(let j of Z){if(!B6(j)||Object.hasOwn(W,j)||gZ($,j)||j.startsWith("node:")||cZ.has(j))continue;let H=vZ(j);if(H)W[j]=H}return W}function uD($){let f=i8($);return f===".ts"||f===".tsx"||f===".mts"||f===".cts"}var t1;function cD(){if(t1!==void 0)return t1;let $=oH("jiti");if(!$)return t1=null,null;let f=c($,"dist","babel.cjs");if(!F0(f))return t1=null,null;try{let W=uZ(f)(f);t1=typeof W==="function"?W:null}catch{t1=null}return t1}async function WX($,f={}){let J=!mD($);fX($,J);let W=vD($,J),Z=ED(W),Q=await import("jiti"),j=typeof Q==="function"?Q:typeof Q.default==="function"?Q.default:void 0;if(!j)throw Error("Unable to load jiti");let H=Object.entries(Z).filter(([,V])=>uD(V)).map(([V])=>V),X=cD(),Y=X?(V)=>X({...V,interopDefault:!0}):void 0;return await j($,{alias:Z,cache:f.useCache,requireCache:f.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...cZ],transformModules:H,tryNative:!1,...Y?{transform:Y}:{}}).import($,{})}function ZX($,f){if(!$)return!0;if($.providerIds?.length){if(!f?.providerId||!$.providerIds.includes(f.providerId))return!1}if($.modelIds?.length){if(!f?.modelId||!$.modelIds.includes(f.modelId))return!1}return!0}function QX($){return typeof $==="object"&&$!==null}function lZ($){return Array.isArray($)&&$.every((f)=>typeof f==="string")}function pD($,f){if(!QX($.manifest))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);if(!lZ($.manifest.capabilities))throw Error(`Invalid plugin module at ${f}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${f}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!lZ($.manifest.providerIds))throw Error(`Invalid plugin module at ${f}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!lZ($.manifest.modelIds))throw Error(`Invalid plugin module at ${f}: manifest.modelIds must be a string array when provided`)}function rD($,f){if(!QX($))throw Error(`Invalid plugin module at ${f}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${f}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);pD($,f)}async function n8($,f={}){let J=dD(f.cwd??process.cwd(),$),W=await WX(J,{useCache:f.useCache}),Z=f.exportName??"plugin",Q=W.default??W[Z];rD(Q,J);let j=Q,H=j.setup,X=H?(Y,A)=>{let V={...f.session,...A.session},B={...A,session:Object.keys(V).length>0?V:void 0,client:f.client??A.client,user:f.user??A.user,workspaceInfo:f.workspaceInfo??A.workspaceInfo,automation:f.automation??A.automation,logger:f.logger??A.logger,telemetry:f.telemetry??A.telemetry};return H(Y,B)}:void 0;return{...j,manifest:lD(j.manifest),setup:X}}async function K6($,f={}){return(await s1($,f)).plugins}async function s1($,f={}){let J=[],W=[],Z=new Map,Q=0;for(let H of $)try{let X=await n8(H,f);if(!ZX(X.manifest,f))continue;let Y=Z.get(X.name);if(Y)W.push({type:"duplicate_plugin_override",pluginName:X.name,pluginPath:H,overriddenPluginPath:Y.pluginPath,message:`Plugin "${X.name}" from ${H} overrides ${Y.pluginPath}`});Z.set(X.name,{plugin:X,pluginPath:H,order:Q++})}catch(X){let Y=X instanceof Error?X.message:String(X);J.push({pluginPath:H,phase:"load",message:Y,stack:X instanceof Error?X.stack:void 0})}let j=[...Z.values()].sort((H,X)=>H.order-X.order);return{plugins:j.map((H)=>H.plugin),pluginPaths:j.map((H)=>H.pluginPath),failures:J,warnings:W}}import{existsSync as nZ}from"node:fs";import{createRequire as BX}from"node:module";import{dirname as G6,join as Z2}from"node:path";import{fileURLToPath as sD}from"node:url";var AX={};w(AX,{resolveSubprocessRuntimeExecutable:()=>pZ,buildSubprocessSandboxCommand:()=>YX,SubprocessSandbox:()=>W2,CLINE_JS_RUNTIME_PATH_ENV:()=>XX});import{spawn as iD}from"node:child_process";import{basename as nD}from"node:path";import{augmentNodeCommandForDebug as aD,withResolvedClineBuildEnv as tD}from"@cline/shared";function jX($){if($ instanceof Error)return $;return Error(String($))}var XX="CLINE_JS_RUNTIME_PATH";function HX($){let f=$?.trim();if(!f)return!1;let J=nD(f).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function pZ($={}){let f=$.env??process.env,J=$.runtimeExecutable?.trim()||f[XX]?.trim();if(J)return J;let W=$.execPath?.trim()||process.execPath;if(HX(W))return W;for(let Z of[f.BUN_EXEC_PATH,f.npm_node_execpath,f.NODE]){let Q=Z?.trim();if(Q&&HX(Q))return Q}return"node"}function YX($,f={}){let J=pZ({env:f.env,execPath:f.execPath,runtimeExecutable:f.runtimeExecutable});return aD([J,...$],{env:f.env,execArgv:f.execArgv,debugRole:f.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class W2{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let f=this.pending.get($);if(!f)return;if(this.pending.delete($),f.timeout)clearTimeout(f.timeout);return f}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],f=YX($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=iD(f[0]??pZ(this.options),f.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:tD(process.env)});this.process=J;let W="",Z=(Q)=>{let j=W+Q;W=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(Q)=>{Z(Q)}),J.on("message",(Q)=>{this.onMessage(Q)}),J.on("error",(Q)=>{this.failPending(Error(`${this.processLabel} process error: ${jX(Q).message}`))}),J.on("exit",(Q,j)=>{this.process=null;let H=W.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Q)}, signal=${String(j)})${H?`: ${H}`:""}`))})}async call($,f,J={}){this.start();let W=this.process;if(!W||W.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,Q={type:"call",id:Z,method:$,args:f};return await new Promise((j,H)=>{let X={resolve:(Y)=>j(Y),reject:H};if((J.timeoutMs??0)>0)X.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),H(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${$}`))},J.timeoutMs);this.pending.set(Z,X),W.send(Q,(Y)=>{if(!Y)return;let A=this.clearPendingRequest(Z);if(!A)return;A.reject(Error(`${this.processLabel} failed to send call "${$}": ${jX(Y).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((f)=>{let J=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}f()},300);$.once("exit",()=>{clearTimeout(J),f()});try{$.kill("SIGTERM")}catch{clearTimeout(J),f()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let f=this.clearPendingRequest($.id);if(!f)return;if($.ok){f.resolve($.result);return}f.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[f,J]of this.pending.entries()){if(this.pending.delete(f),J.timeout)clearTimeout(J.timeout);J.reject($)}}}function oD($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function a8($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function eD(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function $L(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let J=BX($).resolve(`${eD()}/package.json`),W=Z2(G6(J),"extensions","plugin-sandbox-bootstrap.js");return nZ(W)?W:void 0}catch{return}}function fL(){let $=process.execPath?.trim();if(!$)return;let f=Z2(G6(G6($)),"extensions","plugin-sandbox-bootstrap.js");return nZ(f)?f:void 0}function JL(){let $=G6(sD(import.meta.url)),f=BX(import.meta.url),J=[Z2($,"plugin-sandbox-bootstrap.js"),Z2($,"extensions","plugin-sandbox-bootstrap.js"),Z2($,"agents","plugin-sandbox-bootstrap.js"),$L(),fL()];for(let Q of J.filter((j)=>typeof j==="string"))if(nZ(Q))return{file:Q};let W=Z2($,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=f.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`const jiti = createJiti(${JSON.stringify(W)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(W)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
|
|
413
|
+
`)}}var rZ=JL();function iZ($,f,J){if(typeof $==="number"&&$>0)return $;if(J){let W=process.env[J];if(W){let Z=Number(W);if(Number.isInteger(Z)&&Z>0)return Z}}return f}async function P6($){let f=new W2({name:"plugin-sandbox",..."file"in rZ?{bootstrapFile:rZ.file}:{bootstrapScript:rZ.script},onEvent:$.onEvent}),J=iZ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),W=iZ($.hookTimeoutMs,3000),Z=iZ($.contributionTimeoutMs,60000),Q={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},j,H=()=>{return j??=f.call("initialize",Q,{timeoutMs:J}).finally(()=>{j=void 0}),j},X;try{X=await f.call("initialize",Q,{timeoutMs:J})}catch(V){throw await f.shutdown().catch(()=>{}),V}let Y=X.plugins.map(oD);return{extensions:Y.map((V)=>{let B={name:V.name,__clinePluginPath:V.pluginPath,manifest:V.manifest,setup:(K)=>{WL(K,f,V,Z,H),ZL(K,f,V,Z,H),QL(K,f,V,Z,H),HL(K,f,V,Z,H),jL(K,V)}};return B.hooks=YL(f,V,W,H),B}),failures:X.failures,pluginPaths:Y.map((V)=>V.pluginPath),shutdown:async()=>{await f.shutdown()},warnings:X.warnings}}function WL($,f,J,W,Z){for(let Q of J.contributions?.tools??[]){let j={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema??{type:"object",properties:{}},timeoutMs:Q.timeoutMs,retryable:Q.retryable,execute:async(H,X)=>{try{return await f.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:H,context:X},{timeoutMs:W})}catch(Y){if(!a8(Y))throw Y;return await Z(),await f.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:H,context:X},{timeoutMs:W})}}};$.registerTool(j)}}function ZL($,f,J,W,Z){for(let Q of J.contributions?.commands??[])$.registerCommand({name:Q.name,description:Q.description,handler:async(j)=>{try{return await f.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:j},{timeoutMs:W})}catch(H){if(!a8(H))throw H;return await Z(),await f.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:j},{timeoutMs:W})}}})}function QL($,f,J,W,Z){for(let Q of J.contributions?.rules??[])$.registerRule({id:Q.ruleId,source:Q.source,content:Q.hasContentHandler===!0?async()=>{try{return await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:Q.id},{timeoutMs:W})}catch(j){if(!a8(j))throw j;return await Z(),await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:Q.id},{timeoutMs:W})}}:Q.content??""})}function jL($,f){for(let J of f.contributions?.providers??[])$.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of f.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function HL($,f,J,W,Z){for(let Q of J.contributions?.messageBuilders??[])$.registerMessageBuilder({name:Q.name,async build(j){try{let H=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:j},{timeoutMs:W});return VX(H)?H:j}catch(H){if(!a8(H))throw H;await Z();let X=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:j},{timeoutMs:W});return VX(X)?X:j}}})}function VX($){return Array.isArray($)&&$.every((f)=>typeof f==="object"&&f!==null&&("role"in f)&&("content"in f))}function XL($,f,J,W,Z){return async(Q)=>{try{return await $.call("invokeHook",{pluginId:f,hookName:J,payload:Q},{timeoutMs:W})}catch(j){if(!a8(j))throw j;return await Z(),await $.call("invokeHook",{pluginId:f,hookName:J,payload:Q},{timeoutMs:W})}}}function YL($,f,J,W){let Z={};for(let Q of f.hooks??[])Z[Q]=XL($,f.pluginId,Q,J,W);return Object.keys(Z).length>0?Z:void 0}var tZ="package.json",FL="package";function t8($){return GL($)}function s8($){return KL($)}function UL($){try{return R6($)&&VL($).isDirectory()}catch{return!1}}function sZ($){let f=[],J=new Set;for(let W of $){let Z=U6(W);if(J.has(Z))continue;J.add(Z),f.push(Z)}return f}function GX($){let f=sZ($);return k4(f)}function PX($){return t8($).flatMap((f)=>s8(f)).filter((f)=>R6(f))}function RL($,f){let J=[];for(let W of $)try{J.push(...KX([W],f))}catch{}return J}function aZ($){return typeof $==="object"&&$!==null}function DL($){try{let f=JSON.parse(AL(D6($,tZ),"utf8"));if(!aZ(f)||!aZ(f.cline))return[];let J=f.cline.plugins;if(!Array.isArray(J))return[];let W=[];for(let Z of J){if(typeof Z==="string"){W.push(Z);continue}if(!aZ(Z)||!Array.isArray(Z.paths))continue;for(let Q of Z.paths)if(typeof Q==="string")W.push(Q)}return W}catch{return[]}}function FX($,f){let J=U6(f);return DL($).some((W)=>U6($,W)===J)}function LL($,f){return BL($)===FL&&R6(D6(F6($),tZ))&&FX(F6($),f)}function OL($){let f=U6($),J=[],W=F6(f);while(!0){if(LL(W,f)){J.push(W);break}if(R6(D6(W,tZ))){if(FX(W,f))J.push(W);break}let Z=F6(W);if(Z===W)break;W=Z}return sZ(J)}function o1($={}){let f=$.cwd??process.cwd(),J=PX($.workspacePath),W=KX($.pluginPaths??[],f);return GX([...W,...J])}function _L($={}){let f=$.cwd??process.cwd(),J=PX($.workspacePath),W=RL($.pluginPaths??[],f);return GX([...W,...J])}function e1($){let f=[];for(let J of $)for(let W of OL(J)){let Z=D6(W,PL);if(UL(Z))f.push(Z)}return sZ(f)}function UX($={}){return e1(_L($))}async function Q2($={}){let f=o1($);if(f.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let W=await s1(f,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:W.plugins,failures:W.failures,pluginPaths:W.pluginPaths,warnings:W.warnings}}let J=await P6({pluginPaths:f,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,pluginPaths:J.pluginPaths,warnings:J.warnings}}import{execFile as zL}from"node:child_process";import{promisify as TL}from"node:util";var NL=TL(zL);function oZ($,f){$?.log(f,{severity:"warn"})}function ML($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))return;let J=f;if(!J.latest||!Array.isArray(J.history))return;let W=J.latest,Z=J.history.filter((Q)=>!!Q&&typeof Q==="object"&&typeof Q.ref==="string"&&typeof Q.createdAt==="number"&&typeof Q.runCount==="number");if(typeof W.ref!=="string"||typeof W.createdAt!=="number"||typeof W.runCount!=="number")return;return{latest:W,history:Z}}async function $f($,f){let J=await NL("git",["-C",$,...f],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function eZ($,f){if(!$)return;let J=`refs/cline/checkpoints/${f}/`;try{let{stdout:W}=await $f($,["for-each-ref","--format=%(refname)",J]),Z=W.trim().split(`
|
|
414
|
+
`).filter(Boolean);await Promise.allSettled(Z.map((Q)=>$f($,["update-ref","-d",Q])))}catch{}}async function RX($,f,J){if(!$||J.length===0)return;await Promise.allSettled(J.map((W)=>$f($,["update-ref",`refs/cline/checkpoints/${f}/${W.runCount}`,W.ref])))}function yL($,f){let J=$.findIndex((W)=>W.runCount===f.runCount);if(J<0)return[...$,f];return $.map((W,Z)=>Z===J?f:W)}function DX($){let f=$.initialRunCount??0,J,W=async()=>{if(J!==void 0)return J;try{J=(await $f($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},Z=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:f});if(!await W())return;let Q=async(Y)=>{try{let V=(await $f($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!V)return;return{ref:V,createdAt:Date.now(),runCount:f,kind:"commit"}}catch(A){oZ($.logger,`${Y}: ${A instanceof Error?A.message:String(A)}`);return}},j=`cline checkpoint session=${$.sessionId} run=${f}`,H="";try{H=(await $f($.cwd,["stash","create",j])).stdout.trim()}catch(Y){return oZ($.logger,`Checkpoint snapshot failed: ${Y instanceof Error?Y.message:String(Y)}`),Q("Checkpoint HEAD fallback failed")}if(!H)return Q("Checkpoint HEAD fallback failed");let X=`refs/cline/checkpoints/${$.sessionId}/${f}`;try{await $f($.cwd,["update-ref",X,H])}catch(Y){oZ($.logger,`Checkpoint store failed: ${Y instanceof Error?Y.message:String(Y)}`);return}return{ref:H,createdAt:Date.now(),runCount:f,kind:"stash"}};return{beforeRun:async({snapshot:Q})=>{if(Q.parentAgentId!=null)return;f+=1;return},beforeModel:async({snapshot:Q})=>{if(Q.parentAgentId!=null||Q.iteration!==1||f<1)return;let j=await Z();if(!j)return;let H=await $.readSessionMetadata(),X=ML(H);if(X?.latest.ref===j.ref)return;let Y=yL(X?.history??[],j);await $.writeSessionMetadata({...H??{},checkpoint:{latest:j,history:Y}});return}}}import{spawn as IL}from"node:child_process";import{appendFileSync as xL,readFileSync as mL}from"node:fs";import{join as gL}from"node:path";import{augmentNodeCommandForDebug as _X,withResolvedClineBuildEnv as J9}from"@cline/shared";import{ensureHookLogDir as LX}from"@cline/shared/storage";function j2($,f){if(!f)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:f}}import{existsSync as qL,readdirSync as wL}from"node:fs";import{basename as SL,extname as hL,join as CL}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as L6,resolveHooksConfigSearchPaths as EL}from"@cline/shared/storage";function o8($){return EL($)}var H2;((A)=>{A.TaskStart="TaskStart";A.TaskResume="TaskResume";A.TaskCancel="TaskCancel";A.TaskComplete="TaskComplete";A.TaskError="TaskError";A.PreToolUse="PreToolUse";A.PostToolUse="PostToolUse";A.UserPromptSubmit="UserPromptSubmit";A.PreCompact="PreCompact";A.SessionShutdown="SessionShutdown"})(H2||={});var e8={["TaskStart"]:"agent_start",["TaskResume"]:"agent_resume",["TaskCancel"]:"agent_abort",["TaskComplete"]:"agent_end",["TaskError"]:"agent_error",["PreToolUse"]:"tool_call",["PostToolUse"]:"tool_result",["UserPromptSubmit"]:"prompt_submit",["PreCompact"]:void 0,["SessionShutdown"]:"session_shutdown"},bL=new Map(Object.values(H2).map(($)=>[$.toLowerCase(),$])),kL=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function $J($){let f=hL($).toLowerCase();if(!kL.has(f))return;let J=SL($,f).trim().toLowerCase();return bL.get(J)}function Y1($){let f=[],J=new Set,W=o8($).filter((Z)=>qL(Z));for(let Z of W)try{for(let Q of wL(Z,{withFileTypes:!0})){if(!Q.isFile())continue;let j=$J(Q.name);if(!j)continue;let H=CL(Z,Q.name);if(J.has(H))continue;J.add(H),f.push({fileName:j,hookEventName:e8[j],path:H})}}catch{}return f.sort((Z,Q)=>Z.path.localeCompare(Q.path))}function _6($){if(!$||typeof $!=="object")return{};let f={};for(let[J,W]of Object.entries($))f[J]=typeof W==="string"?W:JSON.stringify(W);return f}function O6($,f,J){let W=J instanceof Error?`: ${J.message}`:"",Z=`${f}${W}`;if($){try{$.log(Z,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(Z)}function vL($,f){if(!f)return $;if(!$)return{...f};let J=[$.context,f.context].filter((Z)=>typeof Z==="string"&&Z.length>0).join(`
|
|
415
|
+
`),W=[...$.appendMessages??[],...f.appendMessages??[]];return{cancel:$.cancel===!0||f.cancel===!0?!0:void 0,review:$.review===!0||f.review===!0?!0:void 0,context:J||void 0,overrideInput:f.overrideInput!==void 0?f.overrideInput:$.overrideInput,systemPrompt:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,appendMessages:W.length>0?W:void 0}}function uL($){if(!$||typeof $!=="object")return;let f=$,J=typeof f.context==="string"?f.context:typeof f.contextModification==="string"?f.contextModification:typeof f.errorMessage==="string"?f.errorMessage:void 0;return{cancel:typeof f.cancel==="boolean"?f.cancel:void 0,review:typeof f.review==="boolean"?f.review:void 0,context:J,overrideInput:Object.hasOwn(f,"overrideInput")?f.overrideInput:void 0}}function $9($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function U0($,f){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",W={rootSessionId:f.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:W,workspaceRoots:f.workspacePath?[f.workspacePath]:[],workspaceInfo:f.workspaceInfo,userId:J,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function cL($){let f=$.trim();if(!f)return{};let W=f.split(`
|
|
416
|
+
`).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),Z=W.length>0?W[W.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse hook stdout JSON"}}}async function dL($,f){let J=$.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((W,Z)=>{let Q=!1,j=()=>{J.off("error",X),J.off("finish",Y),$.off("close",A)},H=(V)=>{if(Q)return;if(Q=!0,j(),V){let B=V.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){W();return}Z(V);return}W()},X=(V)=>H(V),Y=()=>H(),A=()=>H();J.on("error",X),J.once("finish",Y),$.once("close",A);try{J.end(f)}catch(V){H(V)}})}async function zX($,f){if(f.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await OX($,f)}catch(J){let W=rL(f.command,process.platform,J);if(!W)throw J;return await OX($,{...f,command:W})}}async function OX($,f){let J=_X(f.command,{env:f.env,debugRole:"hook"}),W=IL(J[0],J.slice(1),{cwd:f.cwd,env:J9(f.env),stdio:f.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:f.detached}),Z=new Promise((B)=>{W.once("spawn",()=>B())}),Q=new Promise((B,K)=>{W.once("error",(G)=>K(G))}),j=JSON.stringify($);if(await Promise.race([Z,Q]),await dL(W,j),f.detached){W.unref();return}if(!W.stdout||!W.stderr)throw Error("hook command failed to create stdout/stderr");let H="",X="",Y=!1,A;W.stdout.on("data",(B)=>{H+=B.toString()}),W.stderr.on("data",(B)=>{X+=B.toString()});let V=new Promise((B)=>{if((f.timeoutMs??0)>0)A=setTimeout(()=>{Y=!0,W.kill("SIGKILL")},f.timeoutMs);W.once("close",(K)=>{if(A)clearTimeout(A);let{parsedJson:G,parseError:R}=cL(H);B({exitCode:K,stdout:H,stderr:X,parsedJson:G,parseError:R,timedOut:Y})})});return await Promise.race([V,Q])}function lL($){try{let J=mL($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let W=J.slice(2).trim();if(!W)return;let Z=W.split(/\s+/).filter(Boolean);return Z.length>0?Z:void 0}catch{return}}function pL($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function rL($,f=process.platform,J){if(f!=="win32"||!pL(J))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function TX($){if($.length===0)return;let[f,...J]=$,W=f.replace(/\\/g,"/").toLowerCase(),Z=W.split("/").at(-1)??W;if(Z==="env")return TX(J);if(Z==="bash"||Z==="sh"||Z==="zsh")return[Z,...J];if(Z==="python3"||Z==="python")return process.platform==="win32"?["py","-3",...J]:[Z,...J];return $}function iL($){let f=lL($);if(f&&f.length>0)return[...TX(f)??f,$];let J=$.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",$];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return _X(["node",$],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",$];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function nL($){let f={};for(let J of Y1($)){if(!J.hookEventName)continue;let W=J.hookEventName,Z=f[W]??[];Z.push(iL(J.path)),f[W]=Z}return f}async function aL($){let f;for(let J of $.commands){let W=J.join(" ");try{let Z=await zX($.payload,{command:J,cwd:$.cwd,env:J9(process.env),detached:!1,timeoutMs:$.timeoutMs});if(Z?.timedOut){O6($.logger,`hook command timed out: ${W}`);continue}if(Z?.parseError){O6($.logger,`hook command returned invalid JSON control output: ${W} (${Z.parseError})`);continue}f=vL(f,uL(Z?.parsedJson))}catch(Z){O6($.logger,`hook command failed: ${W}`,Z)}}return f}function ff($){for(let f of $.commands){let J=f.join(" ");zX($.payload,{command:f,cwd:$.cwd,env:J9(process.env),detached:!0}).catch((W)=>{O6($.logger,`hook command failed: ${J}`,W)})}}function A1($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function f9($,f){return{...A1($.snapshot),userMessage:f}}function NX($){return{...A1($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function MX($){return{...A1($.snapshot),iteration:$.snapshot.iteration,record:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}}function yX($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function tL($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}function X2($){let f={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},J=(W)=>{let Z=`${JSON.stringify({ts:new Date().toISOString(),...W})}
|
|
417
|
+
`,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??gL(LX(),"hooks.jsonl");LX(j),xL(j,Z,"utf8")};return{beforeRun:async(W)=>{let Z=f9(W,"");J({...U0(Z,f),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(W)=>{let Z=NX(W);J({...U0(Z,f),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:_6(Z.call.input)}});return},afterTool:async(W)=>{let Z=MX(W);J({...U0(Z,f),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:_6(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}});return},afterRun:async({snapshot:W,result:Z})=>{let Q=A1(W);if(Z.status==="completed"){J({...U0(Q,f),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||$9(Z.error?.message)){J({...U0(Q,f),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...U0(Q,f),hookName:"agent_error",iteration:Z.iterations,error:{name:Z.error.name,message:Z.error.message,stack:Z.error.stack}})},onEvent:async(W)=>{if(W.type!=="message-added"||W.message.role!=="user")return;let Z=f9({snapshot:W.snapshot},yX(W.message.content));J({...U0(Z,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function fJ($){let f=nL($.workspacePath);if(!Object.values(f).some((V)=>V.length>0))return;let W=async(V,B)=>{let K=f[B]??[];if(K.length===0)return;ff({commands:K,cwd:$.cwd,logger:$.logger,payload:B==="agent_resume"?{...U0(V,$),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...U0(V,$),hookName:B,taskStart:{taskMetadata:{}}}})},Z=async(V)=>{let B=f.prompt_submit??[];if(B.length>0)ff({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:V.userMessage,attachments:[]}}})},Q=async(V)=>{let B=f.tool_call??[];if(B.length===0)return;return aL({commands:B,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...U0(V,$),hookName:"tool_call",iteration:V.iteration,tool_call:{id:V.call.id,name:V.call.name,input:V.call.input},preToolUse:{toolName:V.call.name,parameters:_6(V.call.input)}}})},j=async(V)=>{let B=f.tool_result??[];if(B.length===0)return;ff({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"tool_result",iteration:V.iteration,tool_result:V.record,postToolUse:{toolName:V.record.name,parameters:_6(V.record.input),result:typeof V.record.output==="string"?V.record.output:JSON.stringify(V.record.output),success:!V.record.error,executionTimeMs:V.record.durationMs}}})},H=async(V)=>{let B=f.agent_end??[];if(B.length===0)return;ff({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"agent_end",iteration:V.iteration,turn:V.turn,taskComplete:{taskMetadata:{}}}})},X=async(V)=>{let B=f.agent_error??[];if(B.length===0)return;ff({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"agent_error",iteration:V.iteration,error:{name:V.error.name,message:V.error.message,stack:V.error.stack}}})},Y=async(V)=>{if($9(V.reason)){let K=f.agent_abort??[];if(K.length>0)ff({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"agent_abort",reason:V.reason,taskCancel:{taskMetadata:{}}}})}let B=f.session_shutdown??[];if(B.length===0)return;ff({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"session_shutdown",reason:V.reason}})},A={};if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0||(f.prompt_submit?.length??0)>0){if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0)A.beforeRun=async(V)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await W(A1(V.snapshot),B);return};if((f.prompt_submit?.length??0)>0)A.onEvent=async(V)=>{if(V.type!=="message-added"||V.message.role!=="user")return;await Z(f9({snapshot:V.snapshot},yX(V.message.content)))}}if((f.tool_call?.length??0)>0)A.beforeTool=async(V)=>{let B=await Q(NX(V));return tL(B)};if((f.tool_result?.length??0)>0)A.afterTool=async(V)=>{await j(MX(V));return};if((f.agent_end?.length??0)>0)A.afterRun=async({snapshot:V,result:B})=>{if(B.status!=="completed")return;await H({...A1(V),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if((f.agent_error?.length??0)>0||(f.agent_abort?.length??0)>0||(f.session_shutdown?.length??0)>0){let V=A.afterRun;A.afterRun=async(B)=>{await V?.(B);let{snapshot:K,result:G}=B;if(G.status==="aborted"||$9(G.error?.message)){await Y({...A1(K),reason:G.error?.message});return}if(G.error)await X({...A1(K),iteration:G.iterations,error:G.error})}}return A}function Y2($){return j2("core.hook_config_files",fJ($))}function Jf($,f){let J=$.map((W)=>W[f]).filter((W)=>typeof W==="function");if(J.length===0)return;return async(W)=>{let Z;for(let Q of J){let j=await Q(W);if(!j||typeof j!=="object")continue;let H=j;Z={...Z??{},...H,stop:Z?.stop===!0||H.stop===!0?!0:H.stop,options:Z?.options||H.options?{...Z?.options??{},...H.options??{}}:void 0}}return Z}}function Wf($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return;return{beforeRun:Jf(f,"beforeRun"),afterRun:Jf(f,"afterRun"),beforeModel:Jf(f,"beforeModel"),afterModel:Jf(f,"afterModel"),beforeTool:Jf(f,"beforeTool"),afterTool:Jf(f,"afterTool"),onEvent:Jf(f,"onEvent")}}var qX={};w(qX,{normalizeRuntimeCapabilities:()=>R0});function R0(...$){let f,J;for(let Z of $){if(!Z)continue;if(Z.toolExecutors)f={...f??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let W=f&&Object.keys(f).length>0;if(!W&&!J)return;return{...W?{toolExecutors:f}:{},...J?{requestToolApproval:J}:{}}}var eX={};w(eX,{toProviderConfig:()=>v0,emptyStoredProviderSettings:()=>G1,StoredProviderSettingsSchema:()=>K2,StoredProviderSettingsEntrySchema:()=>a6,ProviderSettingsSchemaTyped:()=>AJ});import{z as K1}from"zod";var oX={};w(oX,{toProviderConfig:()=>v0,safeParseSettings:()=>n6,safeCreateProviderConfig:()=>F9,parseSettings:()=>i6,normalizeProviderId:()=>B2,isBuiltInProviderId:()=>G9,createProviderConfig:()=>P9,SapSettingsSchema:()=>l6,ReasoningSettingsSchema:()=>v6,ProviderSettingsSchema:()=>B1,ProviderProtocolSchema:()=>x6,ProviderIdSchema:()=>YJ,ProviderClientSchema:()=>m6,OcaSettingsSchema:()=>p6,ModelCatalogSettingsSchema:()=>r6,GcpSettingsSchema:()=>c6,BUILT_IN_PROVIDER_IDS:()=>K9,BUILT_IN_PROVIDER:()=>XJ,AzureSettingsSchema:()=>d6,AwsSettingsSchema:()=>u6,AuthSettingsSchema:()=>g6});import*as g0 from"@cline/llms";import{z as y}from"zod";L0();var lX={};w(lX,{refreshOcaToken:()=>WJ,loginOcaOAuth:()=>A2,getValidOcaCredentials:()=>ZJ,generateOcaOpcRequestId:()=>M6,createOcaRequestHeaders:()=>j9,createOcaOAuthProvider:()=>Q9,OCI_HEADER_OPC_REQUEST_ID:()=>xX,DEFAULT_INTERNAL_OCA_BASE_URL:()=>z6,DEFAULT_INTERNAL_IDCS_URL:()=>CX,DEFAULT_INTERNAL_IDCS_SCOPES:()=>EX,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>hX,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>T6,DEFAULT_EXTERNAL_IDCS_URL:()=>kX,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>IX,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>bX});import{nanoid as SX}from"nanoid";class W9{ttlMs;maxEntries;entries=new Map;constructor($,f){this.ttlMs=$;this.maxEntries=f}get($,f=Date.now()){this.pruneExpired(f);let J=this.entries.get($);if(!J)return;return this.entries.delete($),this.entries.set($,J),J.value}set($,f,J=Date.now(),W=this.ttlMs){this.pruneExpired(J),this.entries.delete($);while(this.entries.size>=this.maxEntries){let Z=this.entries.keys().next().value;if(Z===void 0)break;this.entries.delete(Z)}this.entries.set($,{value:f,expiresAt:J+W})}pruneExpired($){for(let[f,J]of this.entries)if(J.expiresAt<=$)this.entries.delete(f)}}var wX={};w(wX,{startLocalOAuthServer:()=>$$});function sL(){let $;return{promise:new Promise((J)=>{$=J}),resolve:$}}async function $$($){let f=await import("node:http"),J=$.host??"127.0.0.1",W=$.timeoutMs??300000,Z=$.successHtml??oL,Q=sL(),j=!1,H=null,X=null,Y=null,A=(K)=>{if(j)return;j=!0,Q.resolve(K)},V=()=>{if(H)clearTimeout(H),H=null;let K=Y;if(Y=null,X)X.close(),X=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:J,port:K})).catch(()=>{})},B=async()=>{return H=setTimeout(()=>{V(),A(null)},W),Q.promise};for(let K of $.ports){let G=f.createServer((P,F)=>{try{let U=new URL(P.url||"",`http://${J}:${K}`);if(U.pathname!==$.callbackPath){F.statusCode=404,F.end("Not found");return}let _={url:U,code:U.searchParams.get("code")??void 0,state:U.searchParams.get("state")??void 0,provider:U.searchParams.get("provider")??void 0,error:U.searchParams.get("error")??void 0};if(_.error){F.statusCode=400,F.end(`Authentication failed: ${_.error}`),V(),A(_);return}if(!_.code){F.statusCode=400,F.end("Missing authorization code");return}if($.expectedState&&_.state!==$.expectedState){F.statusCode=400,F.end("State mismatch");return}F.statusCode=200,F.setHeader("Content-Type","text/html; charset=utf-8"),F.end(Z),V(),A(_)}catch{F.statusCode=500,F.end("Internal error")}}),R=await new Promise((P)=>{let F=(U)=>{G.off("error",F),P({bound:!1,error:U})};G.once("error",F),G.listen(K,J,()=>{G.off("error",F),X=G,P({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw V(),R.error}if(R.bound){Y=K;let P=`http://${J}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:J,port:K,callbackUrl:P})).catch(()=>{});return{callbackUrl:P,waitForCallback:B,cancelWait:()=>{V(),A(null)},close:()=>{V(),A(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var oL=`<!DOCTYPE html>
|
|
418
418
|
<html lang="en">
|
|
419
419
|
<head>
|
|
420
420
|
<meta charset="utf-8">
|
|
@@ -455,60 +455,60 @@ ${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function Nj($,f){l
|
|
|
455
455
|
</div>
|
|
456
456
|
<script>setTimeout(() => window.close(), 3000);</script>
|
|
457
457
|
</body>
|
|
458
|
-
</html>`;var uX="a8331954c0cf48ba99b5dd223a14c6ea",cX="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",dX="openid offline_access",JJ="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",lX="c1aba3deed5740659981a752714eba33",pX="https://login-ext.identity.oraclecloud.com",rX="openid offline_access",QJ="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",iX="opc-request-id",gR="/auth/oca",vR=Array.from({length:11},($,f)=>48801+f),uR=300000,cR=30000,nX=30000,dR=600000;class ZJ extends Error{status;errorCode;constructor($,f){super($);this.name="OcaOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var Z1={internal:{clientId:uX,idcsUrl:cX,scopes:dX,baseUrl:JJ},external:{clientId:lX,idcsUrl:pX,scopes:rX,baseUrl:QJ}},x4=new Map,lR=86400000,pR=300000,rR=32,w7=new y7(lR,rR);function aX($){if(typeof $==="function")return $();return $??"internal"}function tX($){return{internal:{clientId:$?.internal?.clientId??Z1.internal.clientId,idcsUrl:$?.internal?.idcsUrl??Z1.internal.idcsUrl,scopes:$?.internal?.scopes??Z1.internal.scopes,baseUrl:$?.internal?.baseUrl??Z1.internal.baseUrl},external:{clientId:$?.external?.clientId??Z1.external.clientId,idcsUrl:$?.external?.idcsUrl??Z1.external.idcsUrl,scopes:$?.external?.scopes??Z1.external.scopes,baseUrl:$?.external?.baseUrl??Z1.external.baseUrl}}}function iR($=Date.now()){let f=$-dR;for(let[J,Q]of x4.entries())if(Q.createdAt<f)x4.delete(J)}function nR($,f,J){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let Z=z0(f)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=z0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function sX($,f,J){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let Z=$.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let W=z0($.id_token),j=z0(Q),X=W?.sub??j?.sub,H=W?.email??j?.email;return{access:Q,refresh:Z,expires:nR($,Q,$.id_token),accountId:X??J?.accountId,email:H??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:f,subject:X,idToken:$.id_token}}}async function oX($,f){let J=rf($),Q=w7.get(J);if(Q)return Q;let Z=`${J}/.well-known/openid-configuration`,W=await fetch(Z,{method:"GET",signal:AbortSignal.timeout(f)});if(!W.ok){let H=`${J}/oauth2/v1/token`;return w7.set(J,H,Date.now(),pR),H}let X=(await W.json()).token_endpoint||`${J}/oauth2/v1/token`;return w7.set(J,X),X}function eX($){return{code:$.error,message:$.error_description}}async function aR($){let f=x4.get($.state);if(!f)throw Error("No PKCE verifier found for this state");x4.delete($.state);let J=$.mode==="external"?$.config.external:$.config.internal,Q=await oX(J.idcsUrl,$.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:f.redirectUri,client_id:J.clientId,code_verifier:f.verifier}),W=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout($.requestTimeoutMs)}),j=await W.json();if(!W.ok){let H=eX(j);throw new ZJ(`Token exchange failed: ${W.status}${H.message?` - ${H.message}`:""}`,{status:W.status,errorCode:H.code})}let X=z0(j.id_token);if(!j.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==f.nonce)throw Error("OIDC nonce verification failed");return sX(j,$.mode)}function tR($){let f=$.mode==="external"?$.config.external:$.config.internal,J=new URL(`${rf(f.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",f.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",f.scopes),J.searchParams.set("code_challenge",$.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",$.callbackUrl),J.searchParams.set("state",$.state),J.searchParams.set("nonce",$.nonce),J.toString()}async function o2($){U$($.telemetry,"oca");let f=tX($.config),J=aX($.mode),Q=$.callbackPorts?.length?$.callbackPorts:vR,Z=$.callbackPath??gR,W=$.requestTimeoutMs??nX,j=await o0({ports:Q,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=j.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let H=vX(16),Y=vX(16),{verifier:V,challenge:A}=await pf();iR(),x4.set(H,{verifier:V,nonce:Y,mode:J,redirectUri:X,createdAt:Date.now()});let B=tR({callbackUrl:X,mode:J,state:H,nonce:Y,challenge:A,config:f});$.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let G=await c2({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),K=G.code,D=G.state;if(G.error)throw Error(`OAuth error: ${G.error}`);if(!K){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!D||D!==H)throw Error("State mismatch");let F=await aR({code:K,state:D,mode:J,config:f,requestTimeoutMs:W});return D$($.telemetry,"oca"),L$($.telemetry,{id:F.accountId,email:F.email,provider:"oca"}),F}catch(G){throw R$($.telemetry,"oca",G instanceof Error?G.message:String(G)),G}finally{j.close()}}async function m4($,f={}){let J=tX(f.config),Q=f.requestTimeoutMs??nX,Z=$.metadata?.mode,W=Z==="internal"||Z==="external"?Z:aX(f.mode),j=W==="external"?J.external:J.internal,X=await oX(j.idcsUrl,Q),H=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:j.clientId}),Y=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H,signal:AbortSignal.timeout(Q)}),V=await Y.json();if(!Y.ok){let A=eX(V);throw new ZJ(`Token refresh failed: ${Y.status}${A.message?` - ${A.message}`:""}`,{status:Y.status,errorCode:A.code})}return sX(V,W,$)}async function g4($,f,J){if(!$)return null;let Q=f?.refreshBufferMs??J?.refreshBufferMs??uR,Z=f?.retryableTokenGraceMs??J?.retryableTokenGraceMs??cR;if(f?.forceRefresh!==!0&&!x1($,Q))return $;try{return await m4($,J)}catch(j){if(j instanceof ZJ&&j.isLikelyInvalidGrant())return g$(J?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function S7($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(f){return o2({...$,callbacks:f})},async refreshToken(f){return m4(f,$)},getApiKey(f){return f.access}}}async function WJ($,f){let J=new TextEncoder,Q=async(Y)=>{let V=await crypto.subtle.digest("SHA-256",J.encode(Y));return Array.from(new Uint8Array(V).slice(0,4),(A)=>A.toString(16).padStart(2,"0")).join("")},[Z,W]=await Promise.all([Q(f),Q($)]),j=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),X=new Uint32Array(1);crypto.getRandomValues(X);let H=(X[0]??0).toString(16).padStart(8,"0");return Z+W+j+H}async function h7($){let f=await WJ($.taskId,$.accessToken);return{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",client:$.metadata?.client??"Cline","client-version":$.metadata?.clientVersion??"unknown","client-ide":$.metadata?.clientIde??"unknown","client-ide-version":$.metadata?.clientIdeVersion??"unknown",[iX]:f}}var XH={};y(XH,{resolveProviderConfig:()=>c4,getProviderConfig:()=>FJ,getLiveModelsCatalog:()=>e2,clearPublicModelsCatalogCache:()=>UL,clearPrivateModelsCatalogCache:()=>x7,clearLiveModelsCatalogCache:()=>I7,OPENAI_COMPATIBLE_PROVIDERS:()=>u4,DEFAULT_MODELS_CATALOG_URL:()=>AJ});import*as Y0 from"@cline/llms";function C7($){if(!Array.isArray($))return[];return $.map((f)=>{if(typeof f==="string")return f.trim();if(f&&typeof f==="object"){let J=f;for(let Q of[J.id,J.name,J.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter((f)=>f.length>0)}function sR($,f){let J=C7($);if(J.length>0)return J;if(!$||typeof $!=="object")return[];let Q=$,Z=C7(Q.data??Q.models);if(Z.length>0)return Z;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let j=Object.keys(Q.models).filter((X)=>X.trim().length>0);if(j.length>0)return j}let W=Q.providers?.[f];if(W&&typeof W==="object"){let X=C7(W.models??W);if(X.length>0)return X}return[]}async function jJ($,f){let J=await fetch($,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${$}: HTTP ${J.status}`);return sR(await J.json(),f)}function fH($){return $.replace(/\/+$/,"")}function XJ($,f,J){let Q=J?.trim();if(!Q)return;let Z=$?.trim();if(!Z||!f?.trim())return Q;try{let W=new URL(Q),j=new URL(f),X=new URL(Z);if(W.origin!==j.origin)return Q;let H=fH(j.pathname),Y=fH(X.pathname);if(H&&W.pathname.startsWith(`${H}/`)){let V=W.pathname.slice(H.length);X.pathname=`${Y}${V}`}else X.pathname=W.pathname;return X.search=W.search,X.hash=W.hash,X.toString()}catch{return Q}}function oR($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{...J}]))}function eR($){if($.baseUrl.length===0)return!1;switch($.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return $.protocol==="openai-chat"}}var $L=Object.values(Y0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:oR($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),QH=Object.fromEntries($L.map(($)=>[$.id,$]));function fL($){return QH[$]}function JL(){return Object.fromEntries(Object.entries(QH).filter(([,$])=>eR($)))}function ZH($=[]){let f=$.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return f.length>0?f:void 0}var AJ="https://models.dev/api.json",QL=600000,WH=300000,ZL=5000,VJ=new Map,v4=new Map,E7=new Map,HJ=new Map;async function WL(){return Y0.getGeneratedProviderModels()}async function jL($,f={},J={},Q={},Z={},W={}){let j=await WL(),X=Y0.resolveProviderModelCatalogKeys($),H=Object.assign({},...X.map((A)=>j[A]??{})),Y=Boolean(Y0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),V=Object.keys(Z).length>0;if(Y&&V)return Y0.sortModelsByReleaseDate({...Z,...W});if($==="openai-codex")return Y0.sortModelsByReleaseDate({...f,...Y0.filterOpenAICodexModels(J),...Z,...W});return Y0.sortModelsByReleaseDate({...H,...f,...J,...Q,...Z,...W})}function XL($,f){let J=Y0.resolveProviderModelCatalogKeys($);return Object.assign({},...J.map((Q)=>f[Q]??{}))}function BJ($){let f=$?.trim();return f&&f.length>0?f:""}function k7($){let f=$.apiKey?.trim()||$.accessToken?.trim();return f&&f.length>0?f:void 0}function HL($){let f=2166136261;for(let J=0;J<$.length;J+=1)f^=$.charCodeAt(J),f+=(f<<1)+(f<<4)+(f<<7)+(f<<8)+(f<<24);return(f>>>0).toString(16)}function YL($,f){return`${$}:${BJ(f.baseUrl)}:${HL(k7(f)??"")}`}async function GJ($,f,J=ZL){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await fetch($,{...f,signal:Q.signal})}finally{clearTimeout(Z)}}function p1($,f,J){if(J&&!$.includes(f))$.push(f)}function KJ($,f){let J=["streaming","tools"];return p1(J,"images",Boolean(f.supportsImages)),p1(J,"prompt-cache",Boolean(f.supportsPromptCache)),p1(J,"reasoning",Boolean(f.supportsReasoning)),{id:$,name:f.name??$,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxTokens:f.maxTokens,capabilities:J,releaseDate:f.releaseDate,status:"active"}}async function VL($,f){let J=await GJ("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let X=j.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let H=j.supported_features??[];W[X]=KJ(X,{name:X,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:H.includes("reasoning")||H.includes("reasoning_effort"),supportsImages:!1})}return W}function JH($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let f=Number($);return Number.isFinite(f)?f:void 0}return}async function AL($,f){let J=await GJ("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":f}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let X=j.id?.trim();if(!X)continue;W[X]=KJ(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return W}async function BL($,f){let Q=`${(BJ($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await GJ(Q,{method:"GET",headers:{Authorization:`Bearer ${f}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],X={};for(let H of j){let Y=H.id?.trim();if(!Y)continue;let V=H.supported_features??[],A=H.supported_sampling_parameters??[],B=H.input_modalities??[],G=["streaming"];p1(G,"tools",V.includes("tools")),p1(G,"reasoning",V.includes("reasoning")),p1(G,"temperature",A.includes("temperature")),p1(G,"images",B.includes("image"));let K={input:JH(H.pricing?.prompt),output:JH(H.pricing?.completion)};X[Y]={id:Y,name:H.name??Y,description:H.description,contextWindow:H.context_length,maxInputTokens:H.context_length,maxTokens:H.max_completion_tokens,capabilities:G,pricing:K.input!==void 0||K.output!==void 0?K:void 0,status:"active"}}return X}function GL($){let f=BJ($);if(!f)return"http://localhost:4000";return f.endsWith("/v1")?f.slice(0,-3):f}async function KL($,f){let Q=`${GL($.baseUrl)}/v1/model/info`,Z=async(Y)=>GJ(Q,{method:"GET",headers:{accept:"application/json",...Y}}),W=await Z({"x-litellm-api-key":f});if(!W.ok)W=await Z({Authorization:`Bearer ${f}`});if(!W.ok)throw Error(`LiteLLM model refresh failed: HTTP ${W.status}`);let X=(await W.json())?.data??[],H={};for(let Y of X){let V=Y.model_name?.trim(),B=Y.litellm_params?.model?.trim()||V;if(!B)continue;let G=Y.model_info,K=KJ(B,{name:V??B,maxTokens:G?.max_output_tokens??G?.max_tokens,maxInputTokens:G?.max_input_tokens??G?.max_tokens,supportsImages:G?.supports_vision,supportsPromptCache:G?.supports_prompt_caching,supportsReasoning:G?.supports_reasoning});if(H[B]=K,V)H[V]={...K,id:V,name:V}}return H}var jH={baseten:VL,hicap:AL,litellm:KL,poolside:BL},b7=new Map,YJ=new Map;function FL($,f){return`${$}:${BJ(f.baseUrl)}`}async function PL($,f,J){let Q=Y0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=XJ(J.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!Z)return{};let W=f?.cacheTtlMs??WH,j=FL($,J),X=Date.now(),H=b7.get(j);if(H&&H.expiresAt>X)return H.data;let Y=YJ.get(j);if(Y)return Y;let V=jJ(Z,$).then((A)=>{let B=Object.fromEntries(A.map((G)=>[G,KJ(G,{name:G})]));return b7.set(j,{data:B,expiresAt:X+W}),B}).finally(()=>{YJ.delete(j)});return YJ.set(j,V),V}function UL(){b7.clear(),YJ.clear()}async function DL($,f){let J=k7(f);if(!J)return{};let Q=jH[$];if(!Q)return{};return Q(f,J)}function RL($,f,J){if(!J)return!1;if(!jH[$])return!1;if(f?.loadPrivateOnAuth===!1)return!1;return Boolean(k7(J))}async function LL($,f,J){let Q=f?.cacheTtlMs??WH,Z=YL($,J),W=Date.now(),j=E7.get(Z);if(j&&j.expiresAt>W)return j.data;let X=HJ.get(Z);if(X)return X;let H=DL($,J).then((Y)=>{return E7.set(Z,{data:Y,expiresAt:W+Q}),Y}).finally(()=>{HJ.delete(Z)});return HJ.set(Z,H),H}async function OL($){return Y0.fetchModelsDevProviderModels($,globalThis.fetch)}async function e2($={}){let f=$.url??AJ,J=$.cacheTtlMs??QL,Q=Date.now(),Z=VJ.get(f);if(Z&&Z.expiresAt>Q)return Z.data;let W=v4.get(f);if(W)return W;let j=OL(f).then((X)=>{return VJ.set(f,{data:X,expiresAt:Q+J}),X}).finally(()=>{v4.delete(f)});return v4.set(f,j),j}function I7($){if($){VJ.delete($),v4.delete($);return}VJ.clear(),v4.clear()}function x7(){E7.clear(),HJ.clear()}function zL($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:ZH(J.capabilities)}]))}var u4=zL(JL());function FJ($){let f=fL($);if(!f)return;return{baseUrl:f.baseUrl||void 0,modelId:f.modelId,knownModels:f.knownModels,capabilities:ZH(f.capabilities)}}async function c4($,f,J){let Q=FJ($);if(!Q)return;try{let Z=f?.loadLatestOnInit?await e2(f):void 0,W=Z?XL($,Z):{},j=J&&RL($,f,J)?await LL($,f,J):{},H=Boolean(Y0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?J??{providerId:$,modelId:Q.modelId,baseUrl:Q.baseUrl}:J,Y=H?await PL($,f,H).catch(()=>({})):{},V=await jL($,Q.knownModels,W,j,Y,J?.knownModels);return{...Q,knownModels:V}}catch(Z){if(f?.failOnError)throw Z;return Q}}var d4=v0.BUILT_IN_PROVIDER,m7=v0.BUILT_IN_PROVIDER_IDS,g7=v0.isBuiltInProviderId,$8=v0.normalizeProviderId,l4=q.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),PJ=q.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),UJ=q.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),DJ=q.object({apiKey:q.string().optional(),accessToken:q.string().optional(),refreshToken:q.string().optional(),expiresAt:q.number().int().positive().optional(),accountId:q.string().optional()}),_L=q.enum(["none","low","medium","high","xhigh"]),RJ=q.object({enabled:q.boolean().optional(),effort:_L.optional(),budgetTokens:q.number().int().positive().optional()}),LJ=q.object({accessKey:q.string().optional(),secretKey:q.string().optional(),sessionToken:q.string().optional(),region:q.string().optional(),profile:q.string().optional(),authentication:q.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:q.boolean().optional(),useCrossRegionInference:q.boolean().optional(),useGlobalInference:q.boolean().optional(),endpoint:q.string().url().optional(),customModelBaseId:q.string().optional()}),OJ=q.object({projectId:q.string().optional(),region:q.string().optional()}),zJ=q.object({apiVersion:q.string().optional(),useIdentity:q.boolean().optional()}),_J=q.object({clientId:q.string().optional(),clientSecret:q.string().optional(),tokenUrl:q.string().url().optional(),resourceGroup:q.string().optional(),deploymentId:q.string().optional(),useOrchestrationMode:q.boolean().optional(),api:q.enum(["orchestration","foundation-models"]).optional(),defaultSettings:q.record(q.string(),q.unknown()).optional()}),NJ=q.object({mode:q.enum(["internal","external"]).optional(),usePromptCache:q.boolean().optional()}),TJ=q.object({loadLatestOnInit:q.boolean().optional(),loadPrivateOnAuth:q.boolean().optional(),url:q.string().url().optional(),cacheTtlMs:q.number().int().positive().optional(),failOnError:q.boolean().optional()}),W1=q.object({provider:l4,apiKey:q.string().optional(),auth:DJ.optional(),model:q.string().optional(),protocol:PJ.optional(),client:UJ.optional(),routingProviderId:l4.optional(),maxTokens:q.number().int().positive().optional(),contextWindow:q.number().int().positive().optional(),baseUrl:q.string().url().optional(),headers:q.record(q.string(),q.string()).optional(),timeout:q.number().int().positive().optional(),reasoning:RJ.optional(),aws:LJ.optional(),gcp:OJ.optional(),azure:zJ.optional(),sap:_J.optional(),oca:NJ.optional(),region:q.string().optional(),apiLine:q.enum(["china","international"]).optional(),capabilities:q.array(q.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:TJ.optional()});function MJ($){return W1.parse($)}function qJ($){return W1.safeParse($)}function NL($){return $.protocol==="openai-responses"||$.client==="openai"}function u0($,f={}){let J=$.provider,Q=$8(J),Z=f.includeKnownModels!==!1,W=$.reasoning?.effort||"none",j=W==="none"?void 0:W,X=u4[Q],H=Object.assign({},...v0.resolveProviderModelCatalogKeys(Q).map((D)=>v0.getGeneratedModelsForProvider(D))),Y=Object.keys(H)[0],V=$.auth?.accessToken??$.apiKey??$.auth?.apiKey,A=$.baseUrl??(Q==="oca"?$.oca?.mode==="internal"?JJ:QJ:X?.baseUrl),B=$.routingProviderId??(NL($)&&Q!==d4.OPENAI_NATIVE?d4.OPENAI_NATIVE:void 0),G=Z?X?.knownModels??(Object.keys(H).length>0?H:void 0):void 0,K={providerId:J,clientType:$.client,routingProviderId:B,modelId:$.model??X?.modelId??Y??"default",...Z?{knownModels:G}:{},apiKey:V,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:A,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:j,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??X?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(K).filter(([D,F])=>F!==void 0))}function v7($){let f=MJ($);return u0(f)}function u7($){let f=qJ($);if(f.success)return{success:!0,config:u0(f.data)};return{success:!1,error:f.error}}var p4=W1;var yJ=j1.object({settings:W1,updatedAt:j1.string().datetime(),tokenSource:j1.enum(["manual","oauth","migration"]).default("manual")}),f8=j1.object({version:j1.literal(1),lastUsedProvider:j1.string().min(1).optional(),providers:j1.record(j1.string(),yJ)});function X1(){return{version:1,providers:{}}}O$();var VH={};y(VH,{InMemoryWorkspaceManager:()=>J8});import{upsertWorkspaceInfo as TL,WorkspaceManifestSchema as c7}from"@cline/shared";class J8{manifest;listeners=new Set;constructor($){this.manifest=c7.parse($??{workspaces:{}})}async addWorkspacePath($){let f=await F2($);return this.manifest=TL(this.manifest,f),this.emit({type:"workspace_added",workspace:f}),f}async switchWorkspace($){let f=P$($),J=this.manifest.workspaces[f];if(J)return this.manifest=c7.parse({...this.manifest,currentWorkspacePath:f}),this.emit({type:"workspace_switched",workspace:J}),J;let Q=await this.addWorkspacePath(f);return this.manifest=c7.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let f=P$($);return this.manifest.workspaces[f]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let f of this.listeners)f($)}}L0();import{createHash as ML}from"node:crypto";var AH=new Set,BH=new Set;function qL($){return ML("sha256").update($).digest("hex")}function yL($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function GH($){if(!$.telemetry)return;let f=qL($.rootPath),J=$.rootCount??1;if(!AH.has(f))AH.add(f),s6($.telemetry,{root_count:J,vcs_types:yL($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!BH.has(f)){BH.add(f);let Q=Error($.initError.message);Q.name=$.initError.errorType||"Error",o6($.telemetry,Q,{fallback_to_single_root:!0,workspace_count:J})}}function SL($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function hL($,f,J){if(f.length>0)for(let W of f)J?.log(W.message,{severity:"warn"});if($.length===0)return;let Q=$.slice(0,3).map(SL).join("; "),Z=$.length>3?`; and ${$.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${Q}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let W of $)J?.log(`Plugin initialization failed (${W.phase}) for ${W.pluginPath}`,{severity:"warn",stack:W.stack,pluginPath:W.pluginPath,pluginName:W.pluginName})}function CL($,f){let J=typeof $.thinking==="boolean",Q=typeof $.reasoningEffort==="string";if(!J&&!Q)return f;return{...f??{},...J?{enabled:$.thinking}:{},...Q?{effort:$.reasoningEffort}:{}}}function EL($,f){return wL($,f)}function bL($){let f=0;for(let J of $??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;f+=1}return f}function kL($){let f={...$.storedHeaders??{},...$.configHeaders??{}},J=$.accountId?.trim()||IL($.accessToken);if(f.originator="cline",f.session_id=$.sessionId,f["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)f["ChatGPT-Account-Id"]=J;return f}function IL($){let f=$?.trim();if(!f)return;let J=z0(f),Q=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let W=J?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;return}function xL($,f,J,Q,Z){let W=J.getProviderSettings($.providerId),j=Q||W?.modelCatalog?{...Q??{},...W?.modelCatalog??{}}:void 0,X={...W??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??W?.apiKey,baseUrl:$.baseUrl??W?.baseUrl,headers:$.providerId==="openai-codex"?kL({sessionId:f,configHeaders:$.headers,storedHeaders:W?.headers,accountId:W?.auth?.accountId,accessToken:$.apiKey??W?.auth?.accessToken??W?.apiKey}):$.headers??W?.headers,reasoning:CL($,W?.reasoning),modelCatalog:j},H=u0(X);if($.knownModels)H.knownModels=$.knownModels;if($.extensionContext)H.extensionContext=$.extensionContext;let V=$.fetch??H.fetch??Z;if(V)H.fetch=V;return H}async function KH($){let{input:f,sessionId:J,providerSettingsManager:Q,defaultTelemetry:Z,defaultCapabilities:W,defaultToolPolicies:j,defaultFetch:X,onPluginEvent:H,onTeamEvent:Y,createSpawnTool:V,localRuntime:A,readSessionMetadata:B,writeSessionMetadata:G}=$,K=$1(f.config),{modelCatalogDefaults:D,userInstructionService:F,configExtensions:P,onTeamRestored:U,...z}=A??{},_=Object.keys(z).length>0?z:void 0,{workspaceInfo:R,workspaceMetadata:L,durationMs:N,vcsType:w,initError:Q0}=await c5(K),Z0=_?.extensionContext,o={...Z0??{},workspace:{...R,...Z0?.workspace??{}},session:{...Z0?.session??{},sessionId:J},logger:Z0?.logger??_?.logger,telemetry:Z0?.telemetry??_?.telemetry??Z};GH({telemetry:o.telemetry,rootPath:R.rootPath,workspaceInfo:R,rootCount:1,vcsType:w,durationMs:N,initError:Q0,featureFlagEnabled:!0});let d=s2({cwd:f.config.cwd,workspacePath:K,rootSessionId:J,logger:_?.logger,workspaceInfo:R}),R0=fX(_?.hooks)?void 0:t2({rootSessionId:J,workspacePath:K,workspaceInfo:R}),b$=l1([_?.hooks,R0]),l;if(EL(P,"plugins"))try{l=await i2({pluginPaths:_?.pluginPaths,workspacePath:K,cwd:f.config.cwd,onEvent:H,providerId:f.config.providerId,modelId:f.config.modelId,workspaceInfo:R,session:o.session,client:o.client,user:o.user,logger:o.logger,telemetry:o.telemetry,automation:o.automation}),hL(l.failures,l.warnings,_?.logger)}catch(y8){let n=y8 instanceof Error?y8.message:String(y8);_?.logger?.log?.(`plugin loading failed; continuing without plugins (${n})`)}let b=W7(d?[d]:void 0,W7(_?.extensions,Df(l?.extensions))),i={...f.config,..._??{},sessionId:J,hooks:b$,extensions:b,extensionContext:o,telemetry:o.telemetry},C0=xL(i,J,Q,D,X),T0=l1([i.hooks,i.checkpoint?.enabled===!0?wX({cwd:i.cwd,sessionId:J,logger:i.logger,createCheckpoint:i.checkpoint?.createCheckpoint,initialRunCount:bL(f.initialMessages),readSessionMetadata:B,writeSessionMetadata:G}):void 0]),P1={...i,providerConfig:C0,workspaceMetadata:L,hooks:T0},V2=f.toolPolicies??i.toolPolicies??j,q8=D0(W,f.capabilities),l6=q8?.requestToolApproval,m5=q8?.toolExecutors,A2=new J8({currentWorkspacePath:R.rootPath,workspaces:{[R.rootPath]:R}});return{effectiveInput:f,config:P1,providerConfig:C0,workspaceMetadata:L,workspaceInfo:R,extensions:b,hooks:T0,toolPolicies:V2,requestToolApproval:l6,pluginSandboxShutdown:l?.shutdown,runtimeBuilderInput:{config:P1,hooks:T0,extensions:b,onTeamEvent:Y,createSpawnTool:V,onTeamRestored:U,userInstructionService:F,configExtensions:P,toolExecutors:m5,workspaceManager:A2,logger:P1.logger,telemetry:P1.telemetry}}}import{existsSync as SJ,mkdirSync as mL,readdirSync as gL,rmdirSync as vL,rmSync as uL,unlinkSync as cL}from"node:fs";import{dirname as FH,join as wJ}from"node:path";function s(){return new Date().toISOString()}function r4($){if(!$||!SJ($))return;try{cL($)}catch{}}function dL($){let f=x2($);if(f)return{rootSessionId:f.rootSessionId,fileStem:`${f.agentId}__${f.teamTaskId}`};let J=z4($);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:$,fileStem:$}}class d7{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return wJ(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let f=this.sessionArtifactsDir($);if(!SJ(f))mL(f,{recursive:!0});return f}sessionMessagesPath($){return wJ(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,f=!1){let J=f?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return wJ(J,`${$}.json`)}removeSessionDirIfEmpty($){let f=this.sessionArtifactsDir($),J=this.ensureSessionsDir();while(f.startsWith(J)&&f!==J){if(!SJ(f)){f=FH(f);continue}try{if(gL(f).length>0)break;vL(f)}catch{break}f=FH(f)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!SJ($))return;try{uL($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,f,J){let{rootSessionId:Q,fileStem:Z}=dL($),W=this.sessionArtifactsDir(Q);return{messagesPath:wJ(W,`${Z}.messages.json`)}}}import{resolveDocumentsExtensionPath as lL}from"@cline/shared/storage";L0();function PH($,f,J,Q,Z){if(J)$f($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});else e6($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});pL($.telemetry,{workspacePath:Q})}function pL($,f){let J=lL("Hooks"),Q=J1(f.workspacePath),Z=new Map;for(let W of Q){let j=W.hookEventName??"unknown",X=Z.get(j)??{global:0,workspace:0};if(W.path===J||W.path.startsWith(`${J}/`))X.global+=1;else X.workspace+=1;Z.set(j,X)}for(let[W,j]of Z.entries())Vf($,W,j.global,j.workspace)}function UH($,f){for(let J of f.mentions)Hf($,J,f.matchedFiles.includes(J)?1:0,"file",!f.matchedFiles.includes(J));for(let J of f.matchedFiles)jf($,"file",J.length);for(let J of f.ignoredMentions)Xf($,"file","not_found",J)}var TA={};y(TA,{ProviderSettingsManager:()=>G$});import{chmodSync as hA,existsSync as CZ,mkdirSync as Lq,readFileSync as Oq,writeFileSync as zq}from"node:fs";import{basename as CA,dirname as EZ}from"node:path";import{resolveProviderSettingsPath as _q}from"@cline/shared/storage";var T={};y(T,{writeHubDiscovery:()=>zf,writeGlobalSettings:()=>D2,withHubStartupLock:()=>_f,verifyHubConnection:()=>J$,updateMcpServerOAuthState:()=>s1,updateLocalProvider:()=>R5,truncateNotificationBody:()=>x6,toggleDisabledTool:()=>Pf,toTeamProgressLifecycleEvent:()=>K8,toProviderConfig:()=>u0,toHubHealthUrl:()=>W9,toHookConfigFileName:()=>k4,summarizeUsageFromMessages:()=>g2,stopLocalHubServerGracefully:()=>U9,startLocalOAuthServer:()=>o0,startHubWebSocketServer:()=>v6,startHubServer:()=>yA,startClineDeviceAuth:()=>a7,splitCoreSessionConfig:()=>R6,spawnDetachedHubServerWithRetry:()=>_2,spawnDetachedHubServer:()=>A9,setTelemetryOptOutGlobally:()=>C3,setMcpServerDisabled:()=>a1,setDisabledTools:()=>o5,setDisabledPlugin:()=>I3,sendHubCommand:()=>YW,saveLocalProviderSettings:()=>VZ,saveLocalProviderOAuthCredentials:()=>KZ,sanitizeSessionToken:()=>b1,safeParseSettings:()=>qJ,safeCreateProviderConfig:()=>u7,runSubprocessEvent:()=>D8,runHook:()=>L8,reviveTeamStateDates:()=>gf,restartLocalHubIfIdleAfterStartupTimeout:()=>Mf,resolveWorkspaceHubOwnerContext:()=>s3,resolveWorkflowsConfigSearchPaths:()=>H6,resolveSkillsConfigSearchPaths:()=>j6,resolveSharedHubOwnerContext:()=>K0,resolveSessionBackend:()=>lQ,resolveRulesConfigSearchPaths:()=>X6,resolveProviderConfig:()=>c4,resolvePluginConfigSearchPaths:()=>h4,resolveMcpServerRegistrations:()=>W$,resolveLocalClineAuthToken:()=>FZ,resolveHubUrl:()=>D9,resolveHubOwnerContext:()=>_$,resolveHubEndpointOptions:()=>f$,resolveHubBuildId:()=>u$,resolveHooksConfigSearchPaths:()=>E4,resolveDisabledToolNames:()=>$$,resolveDisabledPluginPaths:()=>c8,resolveDefaultMcpSettingsPath:()=>_0,resolveDefaultHubPort:()=>z2,resolveDefaultHubPathname:()=>V9,resolveDefaultHubHost:()=>Y9,resolveCoreSelectedToolIds:()=>uf,resolveCompatibleLocalHubUrl:()=>s8,resolveClineDir:()=>i3,resolveClineDataDir:()=>i8,resolveAndLoadAgentPlugins:()=>i2,resolveAgentPluginPaths:()=>v1,requestHubShutdown:()=>t8,requestDesktopToolApproval:()=>JZ,rememberRecoverableLocalHubUrl:()=>c$,registerRemoteConfigSessionBlobUpload:()=>B5,registerMcpServersFromSettingsFile:()=>o1,registerDisposable:()=>Pq,refreshProviderModelsFromSource:()=>AZ,refreshOpenAICodexToken:()=>o4,refreshOcaToken:()=>m4,refreshClineToken:()=>t4,readSessionCheckpointHistory:()=>k6,readRemoteConfigSessionBlobUploadMetadata:()=>rQ,readHubDiscovery:()=>V0,readGlobalSettings:()=>e0,probeHubServer:()=>G0,probeHubConnection:()=>HW,prewarmFileIndex:()=>Ef,prewarmDetachedHubServer:()=>Nf,prepareRemoteConfigCoreIntegration:()=>nQ,parseWorkflowConfigFromMarkdown:()=>W6,parseUserCommandEnvelope:()=>Fq,parseSkillConfigFromMarkdown:()=>Q6,parseSettings:()=>MJ,parseRuleConfigFromMarkdown:()=>Z6,parseHookEventPayload:()=>R8,openaiCodexOAuthProvider:()=>$Q,normalizeWorkspacePath:()=>P$,normalizeUserInput:()=>Kq,normalizeSdkError:()=>Gq,normalizeRuntimeCapabilities:()=>D0,normalizeProviderId:()=>$8,normalizeOpenAICodexCredentials:()=>e7,normalizeOAuthProvider:()=>BZ,normalizeHubWebSocketUrl:()=>d$,noopBasicLogger:()=>Bq,migrateLegacyProviderSettings:()=>b6,mergeRulesForSystemPrompt:()=>K2,mergeAgentHooks:()=>l1,makeTeamTaskSubSessionId:()=>O4,makeSubSessionId:()=>I2,loginOpenAICodex:()=>W8,loginOcaOAuth:()=>o2,loginLocalProvider:()=>GZ,loginClineOAuth:()=>Z8,loadOpenTelemetryAdapter:()=>$q,loadMcpSettingsFile:()=>n1,loadLlmsConfigFromFile:()=>wZ,loadAgentPluginsFromPathsWithDiagnostics:()=>g1,loadAgentPluginsFromPaths:()=>af,loadAgentPluginFromPath:()=>S4,listSessionHistoryFromBackend:()=>TQ,listPluginToolsWithDiagnostics:()=>aJ,listPluginTools:()=>U6,listMcpServerOAuthStatuses:()=>F6,listLocalProviders:()=>HZ,listHookConfigFiles:()=>J1,isToolDisabledGlobally:()=>E3,isTelemetryOptedOutGlobally:()=>Ff,isRuleEnabled:()=>p6,isPluginDisabledGlobally:()=>k3,isOpenAICodexTokenExpired:()=>o7,isHubReconnectableTransportError:()=>F9,isHubCommandTimeoutError:()=>Tf,isDiscoveryFilePresent:()=>a3,isClineAccountActionRequest:()=>hJ,isBuiltInProviderId:()=>g7,identifyAccount:()=>L$,hasMcpSettingsFile:()=>w$,getValidOpenAICodexCredentials:()=>e4,getValidOcaCredentials:()=>g4,getValidClineCredentials:()=>s4,getProviderConfigFields:()=>PZ,getProviderConfig:()=>FJ,getMcpServerOAuthState:()=>t1,getLocalProviderModels:()=>YZ,getLiveModelsCatalog:()=>e2,getFileIndex:()=>T$,getCurrentContextSize:()=>Y7,getCoreHeadlessToolNames:()=>L4,getCoreDefaultEnabledToolIds:()=>vf,getCoreBuiltinToolCatalog:()=>C1,getCoreAcpToolNames:()=>cf,getClineDefaultSystemPrompt:()=>Jq,generateWorkspaceInfoWithDiagnostics:()=>S8,generateWorkspaceInfo:()=>F2,generateOcaOpcRequestId:()=>WJ,formatRulesForSystemPrompt:()=>G2,formatDisplayUserInput:()=>Aq,filterExtensionToolRegistrations:()=>Df,filterDisabledTools:()=>O1,filterDisabledPluginPaths:()=>Uf,fetchClineRecommendedModels:()=>qZ,executeClineAccountAction:()=>CJ,ensureHubWebSocketServer:()=>h5,ensureHubServer:()=>wA,ensureDetachedHubServer:()=>e3,ensureCustomProvidersLoaded:()=>D5,ensureCompatibleLocalHubUrl:()=>_1,enrichPromptWithMentions:()=>q2,emptyWorkspaceManifest:()=>Vq,emptyStoredProviderSettings:()=>X1,discoverPluginModulePaths:()=>C4,deriveSubsessionStatus:()=>_4,deleteLocalProvider:()=>L5,defineLlmsConfig:()=>yZ,createWorkflowsConfigDefinition:()=>A6,createUserInstructionConfigService:()=>Y1,createToolPoliciesWithPreset:()=>kf,createTool:()=>Yq,createTeamName:()=>G5,createSubprocessHooks:()=>Y5,createSpawnAgentTool:()=>o$,createSkillsConfigDefinition:()=>Y6,createSessionHost:()=>U8,createRuntimeHost:()=>U8,createRulesConfigDefinition:()=>V6,createRemoteConfigSessionMessagesArtifactUploader:()=>iQ,createProviderConfig:()=>v7,createOpenTelemetryTelemetryService:()=>r8,createOcaRequestHeaders:()=>h7,createOcaOAuthProvider:()=>S7,createOAuthClientCallbacks:()=>a4,createMcpTools:()=>Y8,createLocalHubScheduleRuntimeHandlers:()=>qA,createLlmsSdk:()=>hZ,createInitialAccumulatedUsage:()=>A0,createInMemoryHubOwnerContext:()=>n3,createHubServerUrl:()=>n0,createHubAuthToken:()=>Of,createHookConfigFileHooks:()=>I4,createHookConfigFileExtension:()=>s2,createHookAuditHooks:()=>t2,createDisabledMcpToolPolicy:()=>P6,createDisabledMcpToolPolicies:()=>nJ,createDelegatedAgentConfigProvider:()=>C2,createDelegatedAgent:()=>E2,createDefaultToolsWithPreset:()=>If,createDefaultTools:()=>a$,createDefaultMcpServerClientFactory:()=>H8,createDefaultExecutors:()=>y2,createCoreSettingsService:()=>$2,createCoreSessionSnapshot:()=>X$,createContributionRegistry:()=>Hq,createContextCompactionPrepareTurn:()=>Q4,createConfiguredTelemetryService:()=>z$,createConfiguredTelemetryHandle:()=>O2,createClineTelemetryServiceMetadata:()=>Xq,createClineTelemetryServiceConfig:()=>jq,createClineOAuthProvider:()=>s7,createBuiltinTools:()=>E1,createAgentTeamsTools:()=>h1,createAgentRuntime:()=>Rq,createAgentHooksExtension:()=>n2,connectToHub:()=>qf,completeClineDeviceAuth:()=>t7,clearPrivateModelsCatalogCache:()=>x7,clearLiveModelsCatalogCache:()=>I7,clearHubDiscovery:()=>k0,captureWorkspacePathResolved:()=>q3,captureWorkspaceInitialized:()=>s6,captureWorkspaceInitError:()=>o6,captureToolUsage:()=>Qf,captureTokenUsage:()=>ff,captureTaskRestarted:()=>$f,captureTaskCreated:()=>e6,captureTaskCompleted:()=>x8,captureSubagentExecution:()=>g8,captureSkillUsed:()=>Zf,captureSdkError:()=>Wq,captureProviderConfigured:()=>y3,captureProviderApiError:()=>m8,captureModeSwitch:()=>Jf,captureMentionUsed:()=>jf,captureMentionSearchResults:()=>Hf,captureMentionFailed:()=>Xf,captureHookDiscovery:()=>Vf,captureExtensionActivated:()=>M3,captureDiffEditFailure:()=>Wf,captureConversationTurnEvent:()=>U2,captureCompactionSkipped:()=>Bf,captureCompactionExecuted:()=>Af,captureAuthSucceeded:()=>D$,captureAuthStarted:()=>U$,captureAuthLoggedOut:()=>g$,captureAuthFailed:()=>R$,captureAgentTeamCreated:()=>Yf,captureAgentCreated:()=>v$,buildWorkspaceMetadata:()=>h8,buildTeamProgressSummary:()=>G8,buildSdkErrorProperties:()=>Qq,buildRemoteConfigSessionBlobUploadMetadata:()=>V5,buildDelegatedAgentConfig:()=>w1,bootstrapAgentTeams:()=>k2,authorizeMcpServerOAuth:()=>pJ,addLocalProvider:()=>XZ,accumulateUsageTotals:()=>H0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>J6,UnifiedConfigFileWatcher:()=>r1,ToolPresets:()=>g0,TelemetryService:()=>R2,TelemetryLoggerSink:()=>p8,TEAM_TOOL_NAMES:()=>b2,SubprocessSandbox:()=>p2,StoredProviderSettingsSchema:()=>f8,StoredProviderSettingsEntrySchema:()=>yJ,SqliteTeamStore:()=>W2,SqliteSessionStore:()=>Y$,SessionVersioningService:()=>K1,SessionVersioningError:()=>S0,SessionSource:()=>F0,SapSettingsSchema:()=>_J,SKILLS_CONFIG_DIRECTORY_NAME:()=>f6,SESSION_STATUSES:()=>N4,SDK_ERROR_TELEMETRY_EVENT:()=>Uq,RpcClineAccountService:()=>n4,RemoteRuntimeHost:()=>B8,ReasoningSettingsSchema:()=>RJ,RULES_CONFIG_DIRECTORY_NAME:()=>vJ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>A5,ProviderSettingsSchema:()=>W1,ProviderSettingsManager:()=>G$,ProviderProtocolSchema:()=>PJ,ProviderIdSchema:()=>l4,ProviderClientSchema:()=>UJ,OpenTelemetryProvider:()=>L2,OcaSettingsSchema:()=>NJ,OPENAI_COMPATIBLE_PROVIDERS:()=>u4,NodeHubClient:()=>a0,NativeHubTransportAdapter:()=>g6,ModelCatalogSettingsSchema:()=>TJ,LocalRuntimeHost:()=>B$,Llms:()=>fq,InMemoryWorkspaceManager:()=>J8,InMemoryMcpManager:()=>e1,HubUIClient:()=>O9,HubTransportError:()=>O0,HubSessionClient:()=>L9,HubServerTransport:()=>M8,HubScheduleService:()=>P2,HubScheduleCommandService:()=>B2,HubRuntimeHost:()=>S$,HubCommandError:()=>N2,HookEventPayloadSchema:()=>H5,HookEventNameSchema:()=>X5,HookConfigFileName:()=>a2,HOOK_CONFIG_FILE_EVENT_MAP:()=>b4,HOOKS_CONFIG_DIRECTORY_NAME:()=>ef,GlobalSettingsSchema:()=>u8,GcpSettingsSchema:()=>OJ,FileTeamPersistenceStore:()=>N5,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>S5,DefaultToolNames:()=>f0,DefaultRuntimeBuilder:()=>_8,DefaultLlmsSdk:()=>I6,DEFAULT_MODELS_CATALOG_URL:()=>AJ,DEFAULT_HUB_PORT:()=>X9,DEFAULT_HUB_PATHNAME:()=>H9,DEFAULT_HUB_HOST:()=>j9,CoreSettingsService:()=>V1,CoreSessionService:()=>A$,ContributionRegistry:()=>Zq,ClineCore:()=>h6,ClineAccountService:()=>i4,ChatViewStateSchema:()=>TZ,ChatSummarySchema:()=>w5,ChatSessionStatusSchema:()=>M5,ChatSessionConfigSchema:()=>T5,ChatMessageSchema:()=>y5,ChatMessageRoleSchema:()=>q5,CORE_TELEMETRY_EVENTS:()=>x,CORE_BUILD_VERSION:()=>MZ,BrowserWebSocketHubAdapter:()=>m6,BUILT_IN_PROVIDER_IDS:()=>m7,BUILT_IN_PROVIDER:()=>d4,AzureSettingsSchema:()=>zJ,AwsSettingsSchema:()=>LJ,AuthSettingsSchema:()=>DJ,AgentTeamsRuntime:()=>J2,AgentTeam:()=>P8,Agent:()=>Dq,ALL_DEFAULT_TOOL_NAMES:()=>I$});M(T,Rv);import*as fq from"@cline/llms";import{buildClineSystemPrompt as Jq,buildSdkErrorProperties as Qq,ContributionRegistry as Zq,captureSdkError as Wq,createClineTelemetryServiceConfig as jq,createClineTelemetryServiceMetadata as Xq,createContributionRegistry as Hq,createTool as Yq,emptyWorkspaceManifest as Vq,formatDisplayUserInput as Aq,noopBasicLogger as Bq,normalizeSdkError as Gq,normalizeUserInput as Kq,parseUserCommandEnvelope as Fq,registerDisposable as Pq,SDK_ERROR_TELEMETRY_EVENT as Uq}from"@cline/shared";import"@cline/shared/storage";var RH={};y(RH,{isClineAccountActionRequest:()=>hJ,executeClineAccountAction:()=>CJ,RpcClineAccountService:()=>n4,ClineAccountService:()=>i4});function rL($){if(typeof $!=="object"||$===null||!("error"in $))return;let f=$.error;return typeof f==="string"&&f.trim()?f:void 0}function DH($,f,J){let Q=rL(J);if(Q)return Q;let Z=f.trim();if(Z){let W=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${$}: ${W}`}return`Cline account request failed with status ${$}`}class i4{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let f=$.apiBaseUrl.trim();if(!f)throw Error("apiBaseUrl is required");this.apiBaseUrl=f,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let f=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(f)}/balance`)}async fetchUsageTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/usages`)).items??[]}async fetchPaymentTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}`)}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}/balance`)}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId(f,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(f)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let f=$?.trim();if(f)return f;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId($,f){let J=f?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return j}async request($,f){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,W=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:f?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...Q??{}},body:f?.body!==void 0?JSON.stringify(f.body):void 0,signal:Z.signal});if(j.status===204||f?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let X=await j.text(),H;if(X.trim())try{H=JSON.parse(X)}catch{if(!j.ok)throw Error(DH(j.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(DH(j.status,X,H));if(typeof H==="object"&&H!==null){let Y=H;if(typeof Y.success==="boolean"){if(!Y.success)throw Error(Y.error||"Cline account request failed");if(Y.data!==void 0)return Y.data}}if(H===void 0||H===null)throw Error("Cline account response payload was empty");return H}finally{clearTimeout(W)}}}function hJ($){return $.action==="clineAccount"}async function CJ($,f){switch($.operation){case"fetchMe":return f.fetchMe();case"fetchBalance":return f.fetchBalance($.userId);case"fetchUsageTransactions":return f.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return f.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return f.fetchUserOrganizations();case"fetchOrganizationBalance":return f.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return f.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await f.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return f.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class n4{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:f})}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:f,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var LH={};y(LH,{createOAuthClientCallbacks:()=>a4});function a4($){return{onAuth:({url:f,instructions:J})=>{if($.onOutput?.(J??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(f)).catch((Q)=>{$.onOpenUrlError?.({url:f,error:Q})})}catch(Q){$.onOpenUrlError?.({url:f,error:Q})}$.onOutput?.(f)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}L0();var yH={};y(yH,{startClineDeviceAuth:()=>a7,refreshClineToken:()=>t4,loginClineOAuth:()=>Z8,getValidClineCredentials:()=>s4,createClineOAuthProvider:()=>s7,completeClineDeviceAuth:()=>t7});import{getClineEnvironmentConfig as l7}from"@cline/shared";var EJ={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},NH={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},p7="https://api.workos.com",iL="/auth",OH=Array.from({length:11},($,f)=>48801+f),nL=300000,aL=30000,Q8=30000,tL=300,sL=5;class H1 extends Error{status;errorCode;constructor($,f){super($);this.name="ClineOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function oL($){let f=Date.parse($);if(Number.isNaN(f))throw Error(`Invalid expiresAt value: ${$}`);return f}function r7($,f,J={}){let Q=$.userInfo.clineUserId??J.accountId,Z=$.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:Z,expires:oL($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||J.email,metadata:{provider:f,tokenType:$.tokenType,userInfo:$.userInfo}}}async function i7($){if(!$)return{};return typeof $==="function"?await $():$}function zH($,f){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return f;return Math.floor($)}async function _H($){await new Promise((f)=>setTimeout(f,$))}function n7($,f){if(!$.success||!$.data?.accessToken)throw Error(f);return $.data}async function TH($,f){let J=await fetch(I1(p7,NH.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(f?.requestTimeoutMs??Q8)}),Q=await J.json().catch(()=>({}));if(!J.ok)throw new H1(`Device authorization failed: ${J.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:J.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:zH(Q.expires_in,tL),pollIntervalSeconds:zH(Q.interval,sL)}}async function MH($){let f=Date.now()+$.expiresInSeconds*1000,J=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=f){let Q=await fetch(I1($.workosApiBaseUrl,NH.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),Z=await Q.json().catch(()=>({}));if(Q.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await _H(J*1000);break}case"slow_down":{J+=1,await _H(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new H1(Z.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:Z.error});default:throw new H1(`WorkOS token polling failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function qH($,f,J){let Q={accessToken:$.accessToken,refreshToken:$.refreshToken},Z=await fetch(I1(f.apiBaseUrl,EJ.register),{method:"POST",headers:{"Content-Type":"application/json",...await i7(f.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout(f.requestTimeoutMs??Q8)});if(!Z.ok){let j=await Z.text().catch(()=>""),X=u2(j);throw new H1(`Token registration failed: ${Z.status}${X.message?` - ${X.message}`:""}`,{status:Z.status,errorCode:X.code})}let W=await Z.json();return r7(n7(W,"Invalid token exchange response"),J??f.provider)}async function eL($,f,J,Q){let Z={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:f,provider:Q??J.provider},W=await fetch(I1(J.apiBaseUrl,EJ.token),{method:"POST",headers:{"Content-Type":"application/json",...await i7(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??Q8)});if(!W.ok){let X=await W.text().catch(()=>""),H=u2(X);throw new H1(`Token exchange failed: ${W.status}${H.message?` - ${H.message}`:""}`,{status:W.status,errorCode:H.code})}let j=await W.json();return r7(n7(j,"Invalid token exchange response"),Q??J.provider)}async function Z8($){U$($.telemetry,$.provider??"cline");let f=$.useWorkOSDeviceAuth??!0,J=$.callbackPorts?.length?$.callbackPorts:OH,Q=$.callbackPath??iL,Z=f?null:await o0({ports:J,callbackPath:Q,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),W=Z?.callbackUrl||`http://127.0.0.1:${J[0]??OH[0]}${Q}`;try{let j;if(f){let X=l7().workOsClientId,H=await TH(X,$);$.callbacks.onAuth({url:H.verificationUriComplete??H.verificationUri,instructions:`Enter this code in your browser: ${H.userCode}`});let Y=await MH({clientId:X,deviceCode:H.deviceCode,expiresInSeconds:H.expiresInSeconds,initialPollIntervalSeconds:H.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??Q8,workosApiBaseUrl:p7,onProgress:$.callbacks.onProgress});j=await qH(Y,$,$.provider)}else{let X=new URL(I1($.apiBaseUrl,EJ.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",W),X.searchParams.set("redirect_uri",W),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let H,Y=$.provider,V=await c2({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(V.error)throw Error(`OAuth error: ${V.error}`);if(H=V.code,Y=V.provider??Y,!H){let A=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=v2(A,{includeProvider:!0});H=B.code,Y=B.provider??Y}if(!H)throw Error("Missing authorization code");j=await eL(H,W,$,Y)}return D$($.telemetry,$.provider??"cline"),L$($.telemetry,{id:j.accountId,email:j.email,provider:$.provider??"cline"}),j}catch(j){throw R$($.telemetry,$.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function a7($){return await TH(l7().workOsClientId,$)}async function t7($){let f=$.provider??"cline";U$($.telemetry,f);try{let J=await MH({clientId:l7().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??Q8,workosApiBaseUrl:p7}),Q=await qH(J,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return D$($.telemetry,f),L$($.telemetry,{id:Q.accountId,email:Q.email,provider:f}),Q}catch(J){throw R$($.telemetry,f,J instanceof Error?J.message:String(J)),J}}async function t4($,f){let J=await fetch(I1(f.apiBaseUrl,EJ.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await i7(f.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(f.requestTimeoutMs??Q8)});if(!J.ok){let W=await J.text().catch(()=>""),j=u2(W);throw new H1(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let Q=await J.json(),Z=$.metadata?.provider??f.provider;return r7(n7(Q,"Invalid token refresh response"),Z,$)}async function s4($,f,J){if(!$)return null;let Q=J?.refreshBufferMs??nL,Z=J?.retryableTokenGraceMs??aL;if(J?.forceRefresh!==!0&&!x1($,Q))return $;try{return await t4($,f)}catch(j){if(j instanceof H1&&j.isLikelyInvalidGrant())return g$(f.telemetry,f.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function s7($){return{id:"cline",name:"Cline Account",usesCallbackServer:!($.useWorkOSDeviceAuth??!0),async login(f){return Z8({...$,callbacks:f})},async refreshToken(f){return t4(f,$)},getApiKey(f){return`workos:${f.access}`}}}L0();var hH={};y(hH,{refreshOpenAICodexToken:()=>o4,openaiCodexOAuthProvider:()=>$Q,normalizeOpenAICodexCredentials:()=>e7,loginOpenAICodex:()=>W8,isOpenAICodexTokenExpired:()=>o7,getValidOpenAICodexCredentials:()=>e4,OPENAI_CODEX_OAUTH_CONFIG:()=>e});import{nanoid as $O}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 bJ extends Error{status;errorCode;constructor($,f){super($);this.name="OpenAICodexOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function fO($,f,J=e.redirectUri){let Q=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:$,code_verifier:f,redirect_uri:J}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let Z=await Q.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}async function JO($){try{let f=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:e.clientId}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!f.ok){let Q=await f.text().catch(()=>""),Z=u2(Q);throw new bJ(`Token refresh failed: ${f.status}${Z.message?` - ${Z.message}`:""}`,{status:f.status,errorCode:Z.code})}let J=await f.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch(f){if(f instanceof bJ)throw f;return{type:"failed"}}}async function QO($="pi"){let{verifier:f,challenge:J}=await pf(),Q=$O(32),Z=new URL(e.authorizationEndpoint);return Z.searchParams.set("response_type","code"),Z.searchParams.set("client_id",e.clientId),Z.searchParams.set("redirect_uri",e.redirectUri),Z.searchParams.set("scope",e.scopes),Z.searchParams.set("code_challenge",J),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("state",Q),Z.searchParams.set("id_token_add_organizations","true"),Z.searchParams.set("codex_cli_simplified_flow","true"),Z.searchParams.set("originator",$),{verifier:f,state:Q,url:Z.toString()}}function ZO(){try{let $=new URL(e.redirectUri),f=$.port.length>0?Number.parseInt($.port,10):e.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(f)?f:e.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:e.callbackPort,callbackPath:"/auth/callback",redirectUri:e.redirectUri}}}function wH($,f){let J=f?z0(f):z0($),Q=J?J:z0($),W=Q?.[e.jwtClaimPath]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let j=Q?.organizations;if(Array.isArray(j)&&j.length>0){let H=j[0];if(typeof H?.id==="string"&&H.id.length>0)return H.id}let X=Q?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function SH($,f){let J=wH($.access,$.idToken)??f?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||f?.refresh||"",expires:$.expires,accountId:J,email:$.email??f?.email,metadata:{...f?.metadata??{},provider:"openai-codex"}}}async function W8($){U$($.telemetry,"openai-codex");let f=ZO(),{verifier:J,state:Q,url:Z}=await QO($.originator),W=await o0({host:f.host,ports:[f.port],callbackPath:f.callbackPath,expectedState:Q});$.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let X=await c2({waitForCallback:W.waitForCallback,cancelWait:W.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==Q)throw Error("State mismatch");if(j=X.code,!j){let V=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=v2(V,{allowHashCodeState:!0});if(A.state&&A.state!==Q)throw Error("State mismatch");j=A.code}if(!j)throw Error("Missing authorization code");let H=await fO(j,J,f.redirectUri);if(H.type!=="success")throw Error("Token exchange failed");let Y=SH(H);return D$($.telemetry,"openai-codex"),L$($.telemetry,{id:Y.accountId,email:Y.email,provider:"openai-codex"}),Y}catch(X){throw R$($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{W.close()}}async function o4($,f){let J=await JO($);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=SH(J,f);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function e4($,f){if(!$)return null;let J=f?.refreshBufferMs??e.refreshBufferMs,Q=f?.retryableTokenGraceMs??e.retryableTokenGraceMs;if(f?.forceRefresh!==!0&&!x1($,J))return $;try{return await o4($.refresh,$)}catch(W){if(W instanceof bJ&&W.isLikelyInvalidGrant())return g$(f?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Q)return $;return null}}function o7($,f=e.refreshBufferMs){return x1($,f)}function e7($){let f=$.accountId??wH($.access);if(!f)throw Error("Failed to extract accountId from token");return{...$,accountId:f,metadata:{...$.metadata??{},provider:"openai-codex"}}}var $Q={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return W8({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return o4($.refresh,$)},getApiKey($){return $.access}};var zV={};y(zV,{ClineCore:()=>h6});function CH($){if($===!0)return{};if(!$)return;return $}function EH($){if($==="user")return"global";return $}class fQ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let f=this.getService().ingestEvent($);return{event:f.event,duplicate:f.duplicate,matchedSpecIds:f.matchedSpecs.map((J)=>J.specId),queuedRuns:f.queuedRuns,suppressions:f.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function bH($){let{host:f}=$;return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||F0.CLI,interactive:!1,config:{providerId:$8(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:XO(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await f.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content),delivery:Q.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:jO(Z)}},async abortSession(J){return await f.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function kJ($){let f=WO($.automationService,$.automation),J=$.context?.client??($.clientName?{name:$.clientName}:void 0),Q=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),Z=$.context?.logger??$.logger,W=$.context?.telemetry??$.telemetry;if(!f&&!J&&!Q&&!Z&&!W)return $.context;return{...$.context??{},...J?{client:J}:{},...Q?{user:Q}:{},...Z?{logger:Z}:{},...W?{telemetry:W}:{},...f?{automation:f}:{}}}function WO($,f){if(!$)return;return{ingestEvent:(J)=>{f.ingestEvent(J)}}}function jO($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function XO($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var RY={};y(RY,{createCoreSettingsService:()=>$2,CoreSettingsService:()=>V1});import{existsSync as tJ}from"node:fs";import{basename as PY,isAbsolute as Mz,relative as qz}from"node:path";var rH={};y(rH,{resolveWorkflowsConfigSearchPaths:()=>H6,resolveSkillsConfigSearchPaths:()=>j6,resolveRulesConfigSearchPaths:()=>X6,parseWorkflowConfigFromMarkdown:()=>W6,parseSkillConfigFromMarkdown:()=>Q6,parseRuleConfigFromMarkdown:()=>Z6,createWorkflowsConfigDefinition:()=>A6,createUserInstructionConfigService:()=>Y1,createSkillsConfigDefinition:()=>Y6,createRulesConfigDefinition:()=>V6,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>J6,UnifiedConfigFileWatcher:()=>r1,SKILLS_CONFIG_DIRECTORY_NAME:()=>f6,RULES_CONFIG_DIRECTORY_NAME:()=>vJ});import{createHash as HO}from"node:crypto";import{watch as YO}from"node:fs";import{readdir as VO,readFile as AO}from"node:fs/promises";import{join as BO}from"node:path";function GO($){return HO("sha1").update($).digest("hex")}function xH($){return Boolean($&&typeof $==="object"&&"code"in $)}function kH($){return xH($)&&$.code==="ENOENT"}function IH($){return xH($)&&($.code==="EACCES"||$.code==="EPERM")}class r1{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,f){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=f?.debounceMs??75,this.emitParseErrors=f?.emitParseErrors??!1;for(let J of $){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let Q of J.directories){let Z=this.baseTypesByDirectory.get(Q);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(Q,new Set([J.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let f=this.definitionsByType.get($);if(!f)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(f)})}getSnapshot($){let f=this.recordsByType.get($);return new Map([...f?.entries()??[]].map(([J,Q])=>[J,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[f,J]of this.recordsByType.entries())$.set(f,new Map([...J.entries()].map(([Q,Z])=>[Q,{...Z}])));return $}emit($){for(let f of this.listeners)f($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[f,J]of this.watchersByDirectory.entries()){if($.has(f))continue;J.close(),this.watchersByDirectory.delete(f)}this.watchedTypesByDirectory=$;for(let f of $.keys()){if(this.watchersByDirectory.has(f))continue;try{let J=YO(f,()=>{let Q=this.watchedTypesByDirectory.get(f);if(!Q)return;for(let Z of Q)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set(f,J),J.on("error",(Q)=>{let Z=this.watchedTypesByDirectory.get(f);if(!Z)return;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:f})})}catch(J){if(!kH(J)&&!IH(J)){let Q=$.get(f);if(!Q)continue;for(let Z of Q)this.emit({kind:"error",type:Z,error:J,filePath:f})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let f of $){let J=this.definitionsByType.get(f);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal($){let{records:f,discoveredDirectories:J}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[Z,W]of Q.entries()){if(f.has(Z))continue;this.emit({kind:"remove",type:$.type,id:Z,filePath:W.filePath})}for(let[Z,W]of f.entries()){let j=Q.get(Z);if(j&&j.filePath===W.filePath&&j.fingerprint===W.fingerprint)continue;this.emit({kind:"upsert",record:{type:W.type,id:Z,item:W.item,filePath:W.filePath}})}if(this.recordsByType.set($.type,f),this.discoveredDirectoriesByType.set($.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let f=new Map,J=new Set;for(let Q of $.directories){J.add(Q);let Z=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let W of Z){let{fileName:j,filePath:X}=W;if(J.add(W.directoryPath),$.includeFile&&!$.includeFile(j,X))continue;try{let H=await AO(X,"utf8"),Y={type:$.type,directoryPath:W.directoryPath,fileName:j,filePath:X,content:H},V=$.parseFile(Y),A=$.resolveId(V,Y).trim();if(!A)continue;f.set(A,{type:$.type,id:A,item:V,filePath:X,fingerprint:GO(H)})}catch(H){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:H,filePath:X})}}}return{records:f,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let $=new Map;for(let[f,J]of this.baseTypesByDirectory.entries())$.set(f,new Set(J));for(let[f,J]of this.discoveredDirectoriesByType.entries())for(let Q of J){let Z=$.get(Q);if(Z)Z.add(f);else $.set(Q,new Set([f]))}return $}async readDirectoryFileCandidates($){try{return(await VO($,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:$,fileName:J.name,filePath:BO($,J.name)})).sort((J,Q)=>J.fileName.localeCompare(Q.fileName))}catch(f){if(kH(f)||IH(f))return[];throw f}}}import{readdir as JQ,readFile as KO,stat as mH}from"node:fs/promises";import{basename as i1,dirname as FO,extname as QQ,join as y0}from"node:path";import{RULES_CONFIG_DIRECTORY_NAME as vJ,resolveRulesConfigSearchPaths as PO,resolveSkillsConfigSearchPaths as UO,resolveWorkflowsConfigSearchPaths as DO,SKILLS_CONFIG_DIRECTORY_NAME as f6,WORKFLOWS_CONFIG_DIRECTORY_NAME as J6}from"@cline/shared/storage";import RO from"yaml";var IJ="SKILL.md",LO="managed.json",OO=new Set([".md",".markdown",".txt"]);function ZQ($){return $.trim().toLowerCase()}function $6($){let f=$;return f?.code==="ENOENT"||f?.code==="EACCES"||f?.code==="EPERM"}function xJ($){return OO.has(QQ($).toLowerCase())}async function WQ($){try{let f=await JQ($,{withFileTypes:!0}),J=[];for(let Q of f){if(!Q.isDirectory())continue;let Z=y0($,Q.name),W=y0(Z,LO);try{let j=await KO(W,"utf8"),X=JSON.parse(j);if(X&&typeof X==="object")J.push(Z)}catch(j){if($6(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((Q,Z)=>Q.localeCompare(Z))}catch(f){if($6(f))return[];throw f}}function jQ($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,Q,Z]=J;try{let W=RO.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}catch(W){let j=W instanceof Error?W.message:String(W);return{data:{},body:$,hadFrontmatter:!0,parseError:j}}}function mJ($,f,J){if($===void 0||$===null){if(J)throw Error(`Missing required frontmatter field '${f}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${f}' must be a string.`);let Q=$.trim();if(!Q&&J)throw Error(`Frontmatter field '${f}' cannot be empty.`);return Q||void 0}function j8($,f){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${f}' must be a boolean.`);return $}function Q6($,f){let{data:J,body:Q,parseError:Z}=jQ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in skill file.");let X=mJ(J.name,"name",!1)??f.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:mJ(J.description,"description",!1),disabled:j8(J.disabled,"disabled")??(j8(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function Z6($,f){let{data:J,body:Q,parseError:Z}=jQ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in rule file.");let j=mJ(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:j8(J.disabled,"disabled")??(j8(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function W6($,f){let{data:J,body:Q,parseError:Z}=jQ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in workflow file.");let j=mJ(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:j8(J.disabled,"disabled")??(j8(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function j6($){return UO($)}function X6($){return PO($)}function H6($){return DO($)}async function gH($){if(i1($)===".cline"){let f=await WQ($);return(await Promise.all(f.map((Q)=>gH(y0(Q,f6))))).flat()}try{let f=await JQ($,{withFileTypes:!0}),J=[];for(let Q of f){if(Q.isFile()&&Q.name===IJ){J.push({directoryPath:$,fileName:Q.name,filePath:y0($,Q.name)});continue}if(Q.isDirectory())J.push({directoryPath:y0($,Q.name),fileName:IJ,filePath:y0($,Q.name,IJ)})}return J}catch(f){if($6(f))return[];throw f}}async function gJ($){if(i1($)===".cline"){let f=await WQ($);return(await Promise.all(f.map((Q)=>gJ(y0(Q,"rules.md"))))).flat()}try{if((await mH($)).isFile())return[{directoryPath:FO($),fileName:i1($),filePath:$}]}catch(f){if(!$6(f))throw f}try{let J=(await JQ($,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&xJ(Z.name)).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:y0($,Z.name)})),Q=y0($,"AGENTS.md");try{if((await mH(Q)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:$,fileName:"AGENTS.md",filePath:Q})}}catch{}return J}catch(f){if($6(f))return[];throw f}}async function zO($){if(i1($)===".cline"){let f=await WQ($);return(await Promise.all(f.map((Q)=>gJ(y0(Q,J6))))).flat()}return gJ($)}function Y6($){let f=$?.directories??j6($?.workspacePath),J=$?.workspacePath?y0($.workspacePath,".cline"):void 0;return{type:"skill",directories:J?[...f,J]:f,discoverFiles:gH,includeFile:(Q)=>Q===IJ,parseFile:(Q)=>Q6(Q.content,i1(Q.directoryPath)),resolveId:(Q)=>ZQ(Q.name)}}function V6($){let f=$?.directories??X6($?.workspacePath),J=$?.workspacePath?y0($.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...f,J]:f,discoverFiles:gJ,includeFile:(Q,Z)=>Q===".clinerules"||xJ(Q)||xJ(Z),parseFile:(Q)=>Z6(Q.content,i1(Q.filePath,QQ(Q.filePath))),resolveId:(Q)=>ZQ(Q.name)}}function A6($){let f=$?.directories??H6($?.workspacePath),J=$?.workspacePath?y0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...f,J]:f,discoverFiles:zO,includeFile:(Q)=>xJ(Q),parseFile:(Q)=>W6(Q.content,i1(Q.filePath,QQ(Q.filePath))),resolveId:(Q)=>ZQ(Q.name)}}function vH($){let f=[Y6($?.skills),V6($?.rules),A6($?.workflows)];return new r1(f,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as uH}from"@cline/shared";function _O($,f){if($.description?.trim())return uH($.description,".");if(f==="workflow")return;return uH($.instructions,".")}function NO($){return $.disabled!==!0}function cH($,f){return[...$.getSnapshot(f).entries()].map(([J,Q])=>({id:J,record:Q})).filter(({record:J})=>NO(J.item)).map(({id:J,record:Q})=>({id:J,name:Q.item.name,instructions:Q.item.instructions,description:_O(Q.item,f),kind:f})).sort((J,Q)=>J.name.localeCompare(Q.name))}function B6($){let f=new Map;for(let J of[...cH($,"workflow"),...cH($,"skill")])if(!f.has(J.name))f.set(J.name,J);return[...f.values()].sort((J,Q)=>J.name.localeCompare(Q.name))}function dH($,f){if(!$.startsWith("/")||$.length<2)return $;let J=$.match(/^\/(\S+)/);if(!J)return $;let Q=J[1];if(!Q)return $;let Z=Q.length+1,W=$.slice(Z),j=B6(f).find((X)=>X.name===Q);return j?`${j.instructions}${W}`:$}function uJ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function TO($){if(!$||$.length===0)return;let f=$.map(uJ).filter((J)=>J.length>0);return f.length>0?new Set(f):void 0}function MO($,f,J){if(!J)return!0;let Q=uJ($),Z=uJ(f),W=Q.includes(":")?Q.split(":").at(-1)??Q:Q,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(Q)||J.has(Z)||J.has(W)||J.has(j)}function G6($,f){let J=TO(f);return[...$.getSnapshot("skill").entries()].map(([Z,W])=>{let j=W.item;return{id:Z,name:j.name.trim(),description:j.description?.trim(),disabled:j.disabled===!0,skill:j}}).filter((Z)=>MO(Z.id,Z.name,J))}function qO($,f){return G6($,f).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,Q)=>J.localeCompare(Q))}function yO($,f,J){let Q=uJ(f);if(!Q)return{error:"Missing skill name."};let Z=G6($,J),W=Z.find((V)=>V.id===Q);if(W){let{skill:V}=W;if(V.disabled===!0)return{error:`Skill "${V.name}" is configured but disabled.`};return{id:W.id,skill:V}}let j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=Z.filter(({id:V})=>{if(V===j)return!0;return V.endsWith(`:${j}`)}),H=X.filter(({skill:V})=>V.disabled!==!0);if(H.length===1){let{id:V,skill:A}=H[0];return{id:V,skill:A}}if(H.length>1)return{error:`Skill "${f}" is ambiguous. Use one of: ${H.map(({id:V})=>V).join(", ")}`};if(X.length===1){let{skill:V}=X[0];return{error:`Skill "${V.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${f}" is ambiguous, and all matches are disabled: ${X.map(({id:V})=>V).join(", ")}`};let Y=qO($,J);return{error:Y.length>0?`Skill "${f}" not found. Available skills: ${Y.join(", ")}`:"No skills are currently available."}}function wO($,f=Promise.resolve(),J){let Q=new Set,Z=async(W,j)=>{await f;let X=yO($,W,J);if("error"in X)return X.error;let{id:H,skill:Y}=X;if(Q.has(H))return`Skill "${Y.name}" is already running.`;Q.add(H);try{let V=j?.trim(),A=V?`
|
|
459
|
-
<command-args>${
|
|
458
|
+
</html>`;var hX="a8331954c0cf48ba99b5dd223a14c6ea",CX="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",EX="openid offline_access",z6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",bX="c1aba3deed5740659981a752714eba33",kX="https://login-ext.identity.oraclecloud.com",IX="openid offline_access",T6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",xX="opc-request-id",eL="/auth/oca",$O=Array.from({length:11},($,f)=>48801+f),fO=300000,JO=30000,mX=30000,WO=600000;class N6 extends Error{status;errorCode;constructor($,f){super($);this.name="OcaOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var V1={internal:{clientId:hX,idcsUrl:CX,scopes:EX,baseUrl:z6},external:{clientId:bX,idcsUrl:kX,scopes:IX,baseUrl:T6}},JJ=new Map,ZO=86400000,QO=300000,jO=32,Z9=new W9(ZO,jO);function gX($){if(typeof $==="function")return $();return $??"internal"}function vX($){return{internal:{clientId:$?.internal?.clientId??V1.internal.clientId,idcsUrl:$?.internal?.idcsUrl??V1.internal.idcsUrl,scopes:$?.internal?.scopes??V1.internal.scopes,baseUrl:$?.internal?.baseUrl??V1.internal.baseUrl},external:{clientId:$?.external?.clientId??V1.external.clientId,idcsUrl:$?.external?.idcsUrl??V1.external.idcsUrl,scopes:$?.external?.scopes??V1.external.scopes,baseUrl:$?.external?.baseUrl??V1.external.baseUrl}}}function HO($=Date.now()){let f=$-WO;for(let[J,W]of JJ.entries())if(W.createdAt<f)JJ.delete(J)}function XO($,f,J){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let Z=_0(f)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=_0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function uX($,f,J){let W=$.access_token;if(!W)throw Error("Token response did not include an access token");let Z=$.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let Q=_0($.id_token),j=_0(W),H=Q?.sub??j?.sub,X=Q?.email??j?.email;return{access:W,refresh:Z,expires:XO($,W,$.id_token),accountId:H??J?.accountId,email:X??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:f,subject:H,idToken:$.id_token}}}async function cX($,f){let J=V6($),W=Z9.get(J);if(W)return W;let Z=`${J}/.well-known/openid-configuration`,Q=await fetch(Z,{method:"GET",signal:AbortSignal.timeout(f)});if(!Q.ok){let X=`${J}/oauth2/v1/token`;return Z9.set(J,X,Date.now(),QO),X}let H=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return Z9.set(J,H),H}function dX($){return{code:$.error,message:$.error_description}}async function YO($){let f=JJ.get($.state);if(!f)throw Error("No PKCE verifier found for this state");JJ.delete($.state);let J=$.mode==="external"?$.config.external:$.config.internal,W=await cX(J.idcsUrl,$.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:f.redirectUri,client_id:J.clientId,code_verifier:f.verifier}),Q=await fetch(W,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout($.requestTimeoutMs)}),j=await Q.json();if(!Q.ok){let X=dX(j);throw new N6(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let H=_0(j.id_token);if(!j.id_token||!H)throw Error("No ID token received from OCA");if(H.nonce!==f.nonce)throw Error("OIDC nonce verification failed");return uX(j,$.mode)}function AO($){let f=$.mode==="external"?$.config.external:$.config.internal,J=new URL(`${V6(f.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",f.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",f.scopes),J.searchParams.set("code_challenge",$.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",$.callbackUrl),J.searchParams.set("state",$.state),J.searchParams.set("nonce",$.nonce),J.toString()}async function A2($){O$($.telemetry,"oca");let f=vX($.config),J=gX($.mode),W=$.callbackPorts?.length?$.callbackPorts:$O,Z=$.callbackPath??eL,Q=$.requestTimeoutMs??mX,j=await $$({ports:W,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),H=j.callbackUrl;if(!H)throw Error("Unable to bind local OAuth callback server");let X=SX(16),Y=SX(16),{verifier:A,challenge:V}=await A6();HO(),JJ.set(X,{verifier:A,nonce:Y,mode:J,redirectUri:H,createdAt:Date.now()});let B=AO({callbackUrl:H,mode:J,state:X,nonce:Y,challenge:V,config:f});$.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let K=await $2({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),G=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!G){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==X)throw Error("State mismatch");let P=await YO({code:G,state:R,mode:J,config:f,requestTimeoutMs:Q});return _$($.telemetry,"oca"),T$($.telemetry,{id:P.accountId,email:P.email,provider:"oca"}),P}catch(K){throw z$($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{j.close()}}async function WJ($,f={}){let J=vX(f.config),W=f.requestTimeoutMs??mX,Z=$.metadata?.mode,Q=Z==="internal"||Z==="external"?Z:gX(f.mode),j=Q==="external"?J.external:J.internal,H=await cX(j.idcsUrl,W),X=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:j.clientId}),Y=await fetch(H,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout(W)}),A=await Y.json();if(!Y.ok){let V=dX(A);throw new N6(`Token refresh failed: ${Y.status}${V.message?` - ${V.message}`:""}`,{status:Y.status,errorCode:V.code})}return uX(A,Q,$)}async function ZJ($,f,J){if(!$)return null;let W=f?.refreshBufferMs??J?.refreshBufferMs??fO,Z=f?.retryableTokenGraceMs??J?.retryableTokenGraceMs??JO;if(f?.forceRefresh!==!0&&!a1($,W))return $;try{return await WJ($,J)}catch(j){if(j instanceof N6&&j.isLikelyInvalidGrant())return i$(J?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function Q9($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(f){return A2({...$,callbacks:f})},async refreshToken(f){return WJ(f,$)},getApiKey(f){return f.access}}}async function M6($,f){let J=new TextEncoder,W=async(Y)=>{let A=await crypto.subtle.digest("SHA-256",J.encode(Y));return Array.from(new Uint8Array(A).slice(0,4),(V)=>V.toString(16).padStart(2,"0")).join("")},[Z,Q]=await Promise.all([W(f),W($)]),j=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),H=new Uint32Array(1);crypto.getRandomValues(H);let X=(H[0]??0).toString(16).padStart(8,"0");return Z+Q+j+X}async function j9($){let f=await M6($.taskId,$.accessToken);return{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",client:$.metadata?.client??"Cline","client-version":$.metadata?.clientVersion??"unknown","client-ide":$.metadata?.clientIde??"unknown","client-ide-version":$.metadata?.clientIdeVersion??"unknown",[xX]:f}}var sX={};w(sX,{resolveProviderConfig:()=>HJ,getProviderConfig:()=>I6,getLiveModelsCatalog:()=>V2,clearPublicModelsCatalogCache:()=>hO,clearPrivateModelsCatalogCache:()=>B9,clearLiveModelsCatalogCache:()=>V9,OPENAI_COMPATIBLE_PROVIDERS:()=>jJ,DEFAULT_MODELS_CATALOG_URL:()=>C6});import*as X0 from"@cline/llms";function H9($){if(!Array.isArray($))return[];return $.map((f)=>{if(typeof f==="string")return f.trim();if(f&&typeof f==="object"){let J=f;for(let W of[J.id,J.name,J.model])if(typeof W==="string"&&W.trim())return W.trim()}return""}).filter((f)=>f.length>0)}function VO($,f){let J=H9($);if(J.length>0)return J;if(!$||typeof $!=="object")return[];let W=$,Z=H9(W.data??W.models);if(Z.length>0)return Z;if(W.models&&typeof W.models==="object"&&!Array.isArray(W.models)){let j=Object.keys(W.models).filter((H)=>H.trim().length>0);if(j.length>0)return j}let Q=W.providers?.[f];if(Q&&typeof Q==="object"){let H=H9(Q.models??Q);if(H.length>0)return H}return[]}async function y6($,f){let J=await fetch($,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${$}: HTTP ${J.status}`);return VO(await J.json(),f)}function pX($){return $.replace(/\/+$/,"")}function q6($,f,J){let W=J?.trim();if(!W)return;let Z=$?.trim();if(!Z||!f?.trim())return W;try{let Q=new URL(W),j=new URL(f),H=new URL(Z);if(Q.origin!==j.origin)return W;let X=pX(j.pathname),Y=pX(H.pathname);if(X&&Q.pathname.startsWith(`${X}/`)){let A=Q.pathname.slice(X.length);H.pathname=`${Y}${A}`}else H.pathname=Q.pathname;return H.search=Q.search,H.hash=Q.hash,H.toString()}catch{return W}}function BO($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{...J}]))}function KO($){if($.baseUrl.length===0)return!1;switch($.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return $.protocol==="openai-chat"}}var GO=Object.values(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:BO($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),iX=Object.fromEntries(GO.map(($)=>[$.id,$]));function PO($){return iX[$]}function FO(){return Object.fromEntries(Object.entries(iX).filter(([,$])=>KO($)))}function nX($=[]){let f=$.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return f.length>0?f:void 0}var C6="https://models.dev/api.json",UO=600000,aX=300000,RO=5000,h6=new Map,QJ=new Map,X9=new Map,w6=new Map;async function DO(){return X0.getGeneratedProviderModels()}async function LO($,f={},J={},W={},Z={},Q={}){let j=await DO(),H=X0.resolveProviderModelCatalogKeys($),X=Object.assign({},...H.map((V)=>j[V]??{})),Y=Boolean(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),A=Object.keys(Z).length>0;if(Y&&A)return X0.sortModelsByReleaseDate({...Z,...Q});if($==="openai-codex")return X0.sortModelsByReleaseDate({...f,...X0.filterOpenAICodexModels(J),...Z,...Q});return X0.sortModelsByReleaseDate({...X,...f,...J,...W,...Z,...Q})}function OO($,f){let J=X0.resolveProviderModelCatalogKeys($);return Object.assign({},...J.map((W)=>f[W]??{}))}function E6($){let f=$?.trim();return f&&f.length>0?f:""}function A9($){let f=$.apiKey?.trim()||$.accessToken?.trim();return f&&f.length>0?f:void 0}function _O($){let f=2166136261;for(let J=0;J<$.length;J+=1)f^=$.charCodeAt(J),f+=(f<<1)+(f<<4)+(f<<7)+(f<<8)+(f<<24);return(f>>>0).toString(16)}function zO($,f){return`${$}:${E6(f.baseUrl)}:${_O(A9(f)??"")}`}async function b6($,f,J=RO){let W=new AbortController,Z=setTimeout(()=>W.abort(),J);try{return await fetch($,{...f,signal:W.signal})}finally{clearTimeout(Z)}}function Zf($,f,J){if(J&&!$.includes(f))$.push(f)}function k6($,f){let J=["streaming","tools"];return Zf(J,"images",Boolean(f.supportsImages)),Zf(J,"prompt-cache",Boolean(f.supportsPromptCache)),Zf(J,"reasoning",Boolean(f.supportsReasoning)),{id:$,name:f.name??$,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxTokens:f.maxTokens,capabilities:J,releaseDate:f.releaseDate,status:"active"}}async function TO($,f){let J=await b6("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],Q={};for(let j of Z){let H=j.id?.trim();if(!H)continue;if(H.includes("whisper")||H.includes("tts")||H.includes("embedding"))continue;let X=j.supported_features??[];Q[H]=k6(H,{name:H,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:X.includes("reasoning")||X.includes("reasoning_effort"),supportsImages:!1})}return Q}function rX($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let f=Number($);return Number.isFinite(f)?f:void 0}return}async function NO($,f){let J=await b6("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":f}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],Q={};for(let j of Z){let H=j.id?.trim();if(!H)continue;Q[H]=k6(H,{name:H,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}async function MO($,f){let W=`${(E6($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await b6(W,{method:"GET",headers:{Authorization:`Bearer ${f}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],H={};for(let X of j){let Y=X.id?.trim();if(!Y)continue;let A=X.supported_features??[],V=X.supported_sampling_parameters??[],B=X.input_modalities??[],K=["streaming"];Zf(K,"tools",A.includes("tools")),Zf(K,"reasoning",A.includes("reasoning")),Zf(K,"temperature",V.includes("temperature")),Zf(K,"images",B.includes("image"));let G={input:rX(X.pricing?.prompt),output:rX(X.pricing?.completion)};H[Y]={id:Y,name:X.name??Y,description:X.description,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return H}function yO($){let f=E6($);if(!f)return"http://localhost:4000";return f.endsWith("/v1")?f.slice(0,-3):f}async function qO($,f){let W=`${yO($.baseUrl)}/v1/model/info`,Z=async(Y)=>b6(W,{method:"GET",headers:{accept:"application/json",...Y}}),Q=await Z({"x-litellm-api-key":f});if(!Q.ok)Q=await Z({Authorization:`Bearer ${f}`});if(!Q.ok)throw Error(`LiteLLM model refresh failed: HTTP ${Q.status}`);let H=(await Q.json())?.data??[],X={};for(let Y of H){let A=Y.model_name?.trim(),B=Y.litellm_params?.model?.trim()||A;if(!B)continue;let K=Y.model_info,G=k6(B,{name:A??B,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(X[B]=G,A)X[A]={...G,id:A,name:A}}return X}var tX={baseten:TO,hicap:NO,litellm:qO,poolside:MO},Y9=new Map,S6=new Map;function wO($,f){return`${$}:${E6(f.baseUrl)}`}async function SO($,f,J){let W=X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=q6(J.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!Z)return{};let Q=f?.cacheTtlMs??aX,j=wO($,J),H=Date.now(),X=Y9.get(j);if(X&&X.expiresAt>H)return X.data;let Y=S6.get(j);if(Y)return Y;let A=y6(Z,$).then((V)=>{let B=Object.fromEntries(V.map((K)=>[K,k6(K,{name:K})]));return Y9.set(j,{data:B,expiresAt:H+Q}),B}).finally(()=>{S6.delete(j)});return S6.set(j,A),A}function hO(){Y9.clear(),S6.clear()}async function CO($,f){let J=A9(f);if(!J)return{};let W=tX[$];if(!W)return{};return W(f,J)}function EO($,f,J){if(!J)return!1;if(!tX[$])return!1;if(f?.loadPrivateOnAuth===!1)return!1;return Boolean(A9(J))}async function bO($,f,J){let W=f?.cacheTtlMs??aX,Z=zO($,J),Q=Date.now(),j=X9.get(Z);if(j&&j.expiresAt>Q)return j.data;let H=w6.get(Z);if(H)return H;let X=CO($,J).then((Y)=>{return X9.set(Z,{data:Y,expiresAt:Q+W}),Y}).finally(()=>{w6.delete(Z)});return w6.set(Z,X),X}async function kO($){return X0.fetchModelsDevProviderModels($,globalThis.fetch)}async function V2($={}){let f=$.url??C6,J=$.cacheTtlMs??UO,W=Date.now(),Z=h6.get(f);if(Z&&Z.expiresAt>W)return Z.data;let Q=QJ.get(f);if(Q)return Q;let j=kO(f).then((H)=>{return h6.set(f,{data:H,expiresAt:W+J}),H}).finally(()=>{QJ.delete(f)});return QJ.set(f,j),j}function V9($){if($){h6.delete($),QJ.delete($);return}h6.clear(),QJ.clear()}function B9(){X9.clear(),w6.clear()}function IO($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:nX(J.capabilities)}]))}var jJ=IO(FO());function I6($){let f=PO($);if(!f)return;return{baseUrl:f.baseUrl||void 0,modelId:f.modelId,knownModels:f.knownModels,capabilities:nX(f.capabilities)}}async function HJ($,f,J){let W=I6($);if(!W)return;try{let Z=f?.loadLatestOnInit?await V2(f):void 0,Q=Z?OO($,Z):{},j=J&&EO($,f,J)?await bO($,f,J):{},X=Boolean(X0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?J??{providerId:$,modelId:W.modelId,baseUrl:W.baseUrl}:J,Y=X?await SO($,f,X).catch(()=>({})):{},A=await LO($,W.knownModels,Q,j,Y,J?.knownModels);return{...W,knownModels:A}}catch(Z){if(f?.failOnError)throw Z;return W}}var XJ=g0.BUILT_IN_PROVIDER,K9=g0.BUILT_IN_PROVIDER_IDS,G9=g0.isBuiltInProviderId,B2=g0.normalizeProviderId,YJ=y.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),x6=y.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),m6=y.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),g6=y.object({apiKey:y.string().optional(),accessToken:y.string().optional(),refreshToken:y.string().optional(),expiresAt:y.number().int().positive().optional(),accountId:y.string().optional()}),xO=y.enum(["none","low","medium","high","xhigh"]),v6=y.object({enabled:y.boolean().optional(),effort:xO.optional(),budgetTokens:y.number().int().positive().optional()}),u6=y.object({accessKey:y.string().optional(),secretKey:y.string().optional(),sessionToken:y.string().optional(),region:y.string().optional(),profile:y.string().optional(),authentication:y.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:y.boolean().optional(),useCrossRegionInference:y.boolean().optional(),useGlobalInference:y.boolean().optional(),endpoint:y.string().url().optional(),customModelBaseId:y.string().optional()}),c6=y.object({projectId:y.string().optional(),region:y.string().optional()}),d6=y.object({apiVersion:y.string().optional(),useIdentity:y.boolean().optional()}),l6=y.object({clientId:y.string().optional(),clientSecret:y.string().optional(),tokenUrl:y.string().url().optional(),resourceGroup:y.string().optional(),deploymentId:y.string().optional(),useOrchestrationMode:y.boolean().optional(),api:y.enum(["orchestration","foundation-models"]).optional(),defaultSettings:y.record(y.string(),y.unknown()).optional()}),p6=y.object({mode:y.enum(["internal","external"]).optional(),usePromptCache:y.boolean().optional()}),r6=y.object({loadLatestOnInit:y.boolean().optional(),loadPrivateOnAuth:y.boolean().optional(),url:y.string().url().optional(),cacheTtlMs:y.number().int().positive().optional(),failOnError:y.boolean().optional()}),B1=y.object({provider:YJ,apiKey:y.string().optional(),auth:g6.optional(),model:y.string().optional(),protocol:x6.optional(),client:m6.optional(),routingProviderId:YJ.optional(),maxTokens:y.number().int().positive().optional(),contextWindow:y.number().int().positive().optional(),baseUrl:y.string().url().optional(),headers:y.record(y.string(),y.string()).optional(),timeout:y.number().int().positive().optional(),reasoning:v6.optional(),aws:u6.optional(),gcp:c6.optional(),azure:d6.optional(),sap:l6.optional(),oca:p6.optional(),region:y.string().optional(),apiLine:y.enum(["china","international"]).optional(),capabilities:y.array(y.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:r6.optional()});function i6($){return B1.parse($)}function n6($){return B1.safeParse($)}function mO($){return $.protocol==="openai-responses"||$.client==="openai"}function v0($,f={}){let J=$.provider,W=B2(J),Z=f.includeKnownModels!==!1,Q=$.reasoning?.effort||"none",j=Q==="none"?void 0:Q,H=jJ[W],X=Object.assign({},...g0.resolveProviderModelCatalogKeys(W).map((R)=>g0.getGeneratedModelsForProvider(R))),Y=Object.keys(X)[0],A=$.auth?.accessToken??$.apiKey??$.auth?.apiKey,V=$.baseUrl??(W==="oca"?$.oca?.mode==="internal"?z6:T6:H?.baseUrl),B=$.routingProviderId??(mO($)&&W!==XJ.OPENAI_NATIVE?XJ.OPENAI_NATIVE:void 0),K=Z?H?.knownModels??(Object.keys(X).length>0?X:void 0):void 0,G={providerId:J,clientType:$.client,routingProviderId:B,modelId:$.model??H?.modelId??Y??"default",...Z?{knownModels:K}:{},apiKey:A,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:V,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:j,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??H?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(G).filter(([R,P])=>P!==void 0))}function P9($){let f=i6($);return v0(f)}function F9($){let f=n6($);if(f.success)return{success:!0,config:v0(f.data)};return{success:!1,error:f.error}}var AJ=B1;var a6=K1.object({settings:B1,updatedAt:K1.string().datetime(),tokenSource:K1.enum(["manual","oauth","migration"]).default("manual")}),K2=K1.object({version:K1.literal(1),lastUsedProvider:K1.string().min(1).optional(),providers:K1.record(K1.string(),a6)});function G1(){return{version:1,providers:{}}}Z$();var $Y={};w($Y,{InMemoryWorkspaceManager:()=>G2});import{upsertWorkspaceInfo as gO,WorkspaceManifestSchema as U9}from"@cline/shared";class G2{manifest;listeners=new Set;constructor($){this.manifest=U9.parse($??{workspaces:{}})}async addWorkspacePath($){let f=await yf($);return this.manifest=gO(this.manifest,f),this.emit({type:"workspace_added",workspace:f}),f}async switchWorkspace($){let f=L$($),J=this.manifest.workspaces[f];if(J)return this.manifest=U9.parse({...this.manifest,currentWorkspacePath:f}),this.emit({type:"workspace_switched",workspace:J}),J;let W=await this.addWorkspacePath(f);return this.manifest=U9.parse({...this.manifest,currentWorkspacePath:W.rootPath}),this.emit({type:"workspace_switched",workspace:W}),W}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let f=L$($);return this.manifest.workspaces[f]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let f of this.listeners)f($)}}L0();import{createHash as vO}from"node:crypto";var fY=new Set,JY=new Set;function uO($){return vO("sha256").update($).digest("hex")}function cO($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function WY($){if(!$.telemetry)return;let f=uO($.rootPath),J=$.rootCount??1;if(!fY.has(f))fY.add(f),P4($.telemetry,{root_count:J,vcs_types:cO($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!JY.has(f)){JY.add(f);let W=Error($.initError.message);W.name=$.initError.errorType||"Error",F4($.telemetry,W,{fallback_to_single_root:!0,workspace_count:J})}}function lO($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function pO($,f,J){if(f.length>0)for(let Q of f)J?.log(Q.message,{severity:"warn"});if($.length===0)return;let W=$.slice(0,3).map(lO).join("; "),Z=$.length>3?`; and ${$.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${W}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let Q of $)J?.log(`Plugin initialization failed (${Q.phase}) for ${Q.pluginPath}`,{severity:"warn",stack:Q.stack,pluginPath:Q.pluginPath,pluginName:Q.pluginName})}function rO($,f){let J=typeof $.thinking==="boolean",W=typeof $.reasoningEffort==="string";if(!J&&!W)return f;return{...f??{},...J?{enabled:$.thinking}:{},...W?{effort:$.reasoningEffort}:{}}}function ZY($,f){return dO($,f)}function iO($){let f=0;for(let J of $??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;f+=1}return f}function nO($){let f={...$.storedHeaders??{},...$.configHeaders??{}},J=$.accountId?.trim()||aO($.accessToken);if(f.originator="cline",f.session_id=$.sessionId,f["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)f["ChatGPT-Account-Id"]=J;return f}function aO($){let f=$?.trim();if(!f)return;let J=_0(f),W=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}function tO($,f,J,W,Z){let Q=J.getProviderSettings($.providerId),j=W||Q?.modelCatalog?{...W??{},...Q?.modelCatalog??{}}:void 0,H={...Q??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??Q?.apiKey,baseUrl:$.baseUrl??Q?.baseUrl,headers:$.providerId==="openai-codex"?nO({sessionId:f,configHeaders:$.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:$.apiKey??Q?.auth?.accessToken??Q?.apiKey}):$.headers??Q?.headers,reasoning:rO($,Q?.reasoning),modelCatalog:j},X=v0(H);if($.knownModels)X.knownModels=$.knownModels;if($.extensionContext)X.extensionContext=$.extensionContext;let A=$.fetch??X.fetch??Z;if(A)X.fetch=A;return X}async function QY($){let{input:f,sessionId:J,providerSettingsManager:W,defaultTelemetry:Z,defaultCapabilities:Q,defaultToolPolicies:j,defaultFetch:H,onPluginEvent:X,onTeamEvent:Y,createSpawnTool:A,localRuntime:V,readSessionMetadata:B,writeSessionMetadata:K}=$,G=H1(f.config),{modelCatalogDefaults:R,userInstructionService:P,configExtensions:F,onTeamRestored:U,..._}=V??{},z=Object.keys(_).length>0?_:void 0,{workspaceInfo:D,workspaceMetadata:O,durationMs:N,vcsType:q,initError:$0}=await GW(G),Y0=z?.extensionContext,o={...Y0??{},workspace:{...D,...Y0?.workspace??{}},session:{...Y0?.session??{},sessionId:J},logger:Y0?.logger??z?.logger,telemetry:Y0?.telemetry??z?.telemetry??Z};WY({telemetry:o.telemetry,rootPath:D.rootPath,workspaceInfo:D,rootCount:1,vcsType:q,durationMs:N,initError:$0,featureFlagEnabled:!0});let A0=Y2({cwd:f.config.cwd,workspacePath:G,rootSessionId:J,logger:z?.logger,workspaceInfo:D}),i=vH(z?.hooks)?void 0:X2({rootSessionId:J,workspacePath:G,workspaceInfo:D}),J$=Wf([z?.hooks,i]),p;if(ZY(F,"plugins"))try{p=await Q2({pluginPaths:z?.pluginPaths,workspacePath:G,cwd:f.config.cwd,onEvent:X,providerId:f.config.providerId,modelId:f.config.modelId,workspaceInfo:D,session:o.session,client:o.client,user:o.user,logger:o.logger,telemetry:o.telemetry,automation:o.automation}),pO(p.failures,p.warnings,z?.logger)}catch(d2){let r=d2 instanceof Error?d2.message:String(d2);z?.logger?.log?.(`plugin loading failed; continuing without plugins (${r})`)}let k=hZ(A0?[A0]:void 0,hZ(z?.extensions,I4(p?.extensions))),D0=ZY(F,"plugins")?e1(p?.pluginPaths??[]):void 0,n={...f.config,...z??{},sessionId:J,hooks:J$,extensions:k,extensionContext:o,telemetry:o.telemetry},a0=tO(n,J,W,R,H),T1=Wf([n.hooks,n.checkpoint?.enabled===!0?DX({cwd:n.cwd,sessionId:J,logger:n.logger,createCheckpoint:n.checkpoint?.createCheckpoint,initialRunCount:iO(f.initialMessages),readSessionMetadata:B,writeSessionMetadata:K}):void 0]),N1={...n,providerConfig:a0,workspaceMetadata:O,hooks:T1},_f=f.toolPolicies??n.toolPolicies??j,c2=R0(Q,f.capabilities),X4=c2?.requestToolApproval,AW=c2?.toolExecutors,zf=new G2({currentWorkspacePath:D.rootPath,workspaces:{[D.rootPath]:D}});return{effectiveInput:f,config:N1,providerConfig:a0,workspaceMetadata:O,workspaceInfo:D,extensions:k,hooks:T1,toolPolicies:_f,requestToolApproval:X4,pluginSandboxShutdown:p?.shutdown,runtimeBuilderInput:{config:N1,hooks:T1,extensions:k,onTeamEvent:Y,createSpawnTool:A,onTeamRestored:U,userInstructionService:P,pluginSkillDirectories:D0,configExtensions:F,toolExecutors:AW,workspaceManager:zf,logger:N1.logger,telemetry:N1.telemetry}}}import{existsSync as s6,mkdirSync as sO,readdirSync as oO,rmdirSync as eO,rmSync as $_,unlinkSync as f_}from"node:fs";import{dirname as jY,join as t6}from"node:path";function s(){return new Date().toISOString()}function VJ($){if(!$||!s6($))return;try{f_($)}catch{}}function J_($){let f=af($);if(f)return{rootSessionId:f.rootSessionId,fileStem:`${f.agentId}__${f.teamTaskId}`};let J=v8($);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:$,fileStem:$}}class R9{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return t6(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let f=this.sessionArtifactsDir($);if(!s6(f))sO(f,{recursive:!0});return f}sessionMessagesPath($){return t6(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,f=!1){let J=f?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return t6(J,`${$}.json`)}removeSessionDirIfEmpty($){let f=this.sessionArtifactsDir($),J=this.ensureSessionsDir();while(f.startsWith(J)&&f!==J){if(!s6(f)){f=jY(f);continue}try{if(oO(f).length>0)break;eO(f)}catch{break}f=jY(f)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!s6($))return;try{$_($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,f,J){let{rootSessionId:W,fileStem:Z}=J_($),Q=this.sessionArtifactsDir(W);return{messagesPath:t6(Q,`${Z}.messages.json`)}}}import{resolveDocumentsExtensionPath as W_}from"@cline/shared/storage";L0();function HY($,f,J,W,Z){if(J)R4($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});else U4($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});Z_($.telemetry,{workspacePath:W})}function Z_($,f){let J=W_("Hooks"),W=Y1(f.workspacePath),Z=new Map;for(let Q of W){let j=Q.hookEventName??"unknown",H=Z.get(j)??{global:0,workspace:0};if(Q.path===J||Q.path.startsWith(`${J}/`))H.global+=1;else H.workspace+=1;Z.set(j,H)}for(let[Q,j]of Z.entries())q4($,Q,j.global,j.workspace)}function XY($,f){for(let J of f.mentions)M4($,J,f.matchedFiles.includes(J)?1:0,"file",!f.matchedFiles.includes(J));for(let J of f.matchedFiles)T4($,"file",J.length);for(let J of f.ignoredMentions)N4($,"file","not_found",J)}var OB={};w(OB,{ProviderSettingsManager:()=>R$});import{chmodSync as yB,existsSync as P7,mkdirSync as Aw,readFileSync as Vw,writeFileSync as Bw}from"node:fs";import{basename as qB,dirname as F7}from"node:path";import{resolveProviderSettingsPath as Kw}from"@cline/shared/storage";var T={};w(T,{writeHubDiscovery:()=>v4,writeGlobalSettings:()=>a$,withHubStartupLock:()=>u4,verifyHubConnection:()=>H$,updateMcpServerOAuthState:()=>Yf,updateLocalProvider:()=>p5,uninstallPlugin:()=>mQ,truncateNotificationBody:()=>f4,toggleDisabledTool:()=>b4,toTeamProgressLifecycleEvent:()=>y2,toProviderConfig:()=>v0,toHubHealthUrl:()=>CW,toHookConfigFileName:()=>$J,summarizeUsageFromMessages:()=>sf,stopLocalHubServerGracefully:()=>lW,startLocalOAuthServer:()=>$$,startHubWebSocketServer:()=>Z4,startHubServer:()=>TB,startClineDeviceAuth:()=>T9,splitCoreSessionConfig:()=>X8,spawnDetachedHubServerWithRetry:()=>bf,spawnDetachedHubServer:()=>mW,setTelemetryOptOutGlobally:()=>P3,setMcpServerDisabled:()=>Hf,setDisabledTools:()=>NW,setDisabledPlugin:()=>D3,sendHubCommand:()=>r3,saveLocalProviderSettings:()=>rQ,saveLocalProviderOAuthCredentials:()=>tQ,sanitizeSessionToken:()=>r1,safeParseSettings:()=>n6,safeCreateProviderConfig:()=>F9,runSubprocessEvent:()=>h2,runHook:()=>E2,reviveTeamStateDates:()=>Z6,restartLocalHubIfIdleAfterStartupTimeout:()=>l4,resolveWorkspaceHubOwnerContext:()=>b3,resolveWorkflowsConfigSearchPaths:()=>yJ,resolveSkillsConfigSearchPaths:()=>NJ,resolveSharedHubOwnerContext:()=>G0,resolveSessionBackend:()=>DQ,resolveRulesConfigSearchPaths:()=>MJ,resolveProviderConfig:()=>HJ,resolvePluginSkillDirectoriesFromPaths:()=>e1,resolvePluginConfigSearchPaths:()=>t8,resolveMcpServerRegistrations:()=>A$,resolveLocalClineAuthToken:()=>sQ,resolveHubUrl:()=>pW,resolveHubOwnerContext:()=>q$,resolveHubEndpointOptions:()=>j$,resolveHubBuildId:()=>t$,resolveHooksConfigSearchPaths:()=>o8,resolveDisabledToolNames:()=>W$,resolveDisabledPluginPaths:()=>W8,resolveDefaultMcpSettingsPath:()=>z0,resolveDefaultHubPort:()=>Ef,resolveDefaultHubPathname:()=>xW,resolveDefaultHubHost:()=>IW,resolveCoreSelectedToolIds:()=>j6,resolveCompatibleLocalHubUrl:()=>G8,resolveClineDir:()=>S3,resolveClineDataDir:()=>A8,resolveAndLoadAgentPlugins:()=>Q2,resolveAgentPluginPaths:()=>o1,requestHubShutdown:()=>K8,requestDesktopToolApproval:()=>SQ,rememberRecoverableLocalHubUrl:()=>s$,registerRemoteConfigSessionBlobUpload:()=>b5,registerMcpServersFromSettingsFile:()=>Af,registerDisposable:()=>jw,refreshProviderModelsFromSource:()=>iQ,refreshOpenAICodexToken:()=>UJ,refreshOcaToken:()=>WJ,refreshClineToken:()=>PJ,readSessionCheckpointHistory:()=>eJ,readRemoteConfigSessionBlobUploadMetadata:()=>OQ,readHubDiscovery:()=>V0,readGlobalSettings:()=>E0,probeHubServer:()=>Q$,probeHubConnection:()=>p3,prewarmFileIndex:()=>s4,prewarmDetachedHubServer:()=>c4,prepareRemoteConfigCoreIntegration:()=>zQ,parseWorkflowConfigFromMarkdown:()=>TJ,parseUserCommandEnvelope:()=>Qw,parseSkillConfigFromMarkdown:()=>_J,parseSettings:()=>i6,parseRuleConfigFromMarkdown:()=>zJ,parseHookEventPayload:()=>C2,openaiCodexOAuthProvider:()=>w9,normalizeWorkspacePath:()=>L$,normalizeUserInput:()=>Zw,normalizeSdkError:()=>Ww,normalizeRuntimeCapabilities:()=>R0,normalizeProviderId:()=>B2,normalizeOpenAICodexCredentials:()=>q9,normalizeOAuthProvider:()=>nQ,normalizeHubWebSocketUrl:()=>o$,noopBasicLogger:()=>Jw,migrateLegacyProviderSettings:()=>oJ,mergeRulesForSystemPrompt:()=>Mf,mergeAgentHooks:()=>Wf,makeTeamTaskSubSessionId:()=>g8,makeSubSessionId:()=>nf,loginOpenAICodex:()=>U2,loginOcaOAuth:()=>A2,loginLocalProvider:()=>aQ,loginClineOAuth:()=>F2,loadOpenTelemetryAdapter:()=>lq,loadMcpSettingsFile:()=>jf,loadLlmsConfigFromFile:()=>B7,loadAgentPluginsFromPathsWithDiagnostics:()=>s1,loadAgentPluginsFromPaths:()=>K6,loadAgentPluginFromPath:()=>n8,listSessionHistoryFromBackend:()=>$Q,listPluginToolsWithDiagnostics:()=>U5,listPluginTools:()=>IJ,listMcpServerOAuthStatuses:()=>bJ,listLocalProviders:()=>lQ,listHookConfigFiles:()=>Y1,isToolDisabledGlobally:()=>F3,isTelemetryOptedOutGlobally:()=>E4,isSessionNotFoundError:()=>y$,isRuleEnabled:()=>Y4,isPluginDisabledGlobally:()=>R3,isOpenAICodexTokenExpired:()=>y9,isHubReconnectableTransportError:()=>cW,isHubCommandTimeoutError:()=>d4,isDiscoveryFilePresent:()=>C3,isClineAccountActionRequest:()=>o6,isBuiltInProviderId:()=>G9,identifyAccount:()=>T$,hasMcpSettingsFile:()=>x$,getValidOpenAICodexCredentials:()=>RJ,getValidOcaCredentials:()=>ZJ,getValidClineCredentials:()=>FJ,getProviderConfigFields:()=>oQ,getProviderConfig:()=>I6,getMcpServerOAuthState:()=>Xf,getLocalProviderModels:()=>pQ,getLiveModelsCatalog:()=>V2,getFileIndex:()=>C$,getCurrentContextSize:()=>kZ,getCoreHeadlessToolNames:()=>m8,getCoreDefaultEnabledToolIds:()=>Q6,getCoreBuiltinToolCatalog:()=>l1,getCoreAcpToolNames:()=>H6,getClineDefaultSystemPrompt:()=>rq,generateWorkspaceInfoWithDiagnostics:()=>p2,generateWorkspaceInfo:()=>yf,generateOcaOpcRequestId:()=>M6,formatRulesForSystemPrompt:()=>Nf,formatDisplayUserInput:()=>fw,filterExtensionToolRegistrations:()=>I4,filterDisabledTools:()=>S1,filterDisabledPluginPaths:()=>k4,fetchClineRecommendedModels:()=>A7,executeClineAccountAction:()=>e6,ensureHubWebSocketServer:()=>WW,ensureHubServer:()=>NB,ensureDetachedHubServer:()=>I3,ensureCustomProvidersLoaded:()=>c5,ensureCompatibleLocalHubUrl:()=>b1,enrichPromptWithMentions:()=>mf,emptyWorkspaceManifest:()=>$w,emptyStoredProviderSettings:()=>G1,discoverPluginModulePaths:()=>s8,deriveSubsessionStatus:()=>u8,deleteLocalProvider:()=>r5,defineLlmsConfig:()=>V7,createWorkflowsConfigDefinition:()=>SJ,createUserInstructionConfigService:()=>F1,createToolPoliciesWithPreset:()=>e4,createTool:()=>eq,createTeamName:()=>I5,createSubprocessHooks:()=>h5,createSpawnAgentTool:()=>Q1,createSkillsConfigDefinition:()=>qJ,createSessionHost:()=>S2,createRuntimeHost:()=>S2,createRulesConfigDefinition:()=>wJ,createRemoteConfigSessionMessagesArtifactUploader:()=>_Q,createProviderConfig:()=>P9,createOpenTelemetryTelemetryService:()=>H8,createOcaRequestHeaders:()=>j9,createOcaOAuthProvider:()=>Q9,createOAuthClientCallbacks:()=>GJ,createMcpTools:()=>_2,createLocalHubScheduleRuntimeHandlers:()=>zB,createLlmsSdk:()=>G7,createInitialAccumulatedUsage:()=>B0,createInMemoryHubOwnerContext:()=>h3,createHubServerUrl:()=>t0,createHubAuthToken:()=>g4,createHookConfigFileHooks:()=>fJ,createHookConfigFileExtension:()=>Y2,createHookAuditHooks:()=>X2,createDisabledMcpToolPolicy:()=>kJ,createDisabledMcpToolPolicies:()=>F5,createDelegatedAgentConfigProvider:()=>df,createDelegatedAgent:()=>lf,createDefaultToolsWithPreset:()=>$6,createDefaultTools:()=>J1,createDefaultMcpServerClientFactory:()=>O2,createDefaultExecutors:()=>gf,createCoreSettingsService:()=>Bf,createCoreSessionSnapshot:()=>B$,createContributionRegistry:()=>oq,createContextCompactionPrepareTurn:()=>L8,createConfiguredTelemetryService:()=>N$,createConfiguredTelemetryHandle:()=>Cf,createClineTelemetryServiceMetadata:()=>sq,createClineTelemetryServiceConfig:()=>tq,createClineOAuthProvider:()=>M9,createBuiltinTools:()=>p1,createAgentTeamsTools:()=>d1,createAgentRuntime:()=>Yw,createAgentHooksExtension:()=>j2,connectToHub:()=>p4,completeClineDeviceAuth:()=>N9,clearPrivateModelsCatalogCache:()=>B9,clearLiveModelsCatalogCache:()=>V9,clearHubDiscovery:()=>b0,captureWorkspacePathResolved:()=>Y3,captureWorkspaceInitialized:()=>P4,captureWorkspaceInitError:()=>F4,captureToolUsage:()=>O4,captureTokenUsage:()=>D4,captureTaskRestarted:()=>R4,captureTaskCreated:()=>U4,captureTaskCompleted:()=>o2,captureSubagentExecution:()=>$8,captureSkillUsed:()=>_4,captureSdkError:()=>aq,captureProviderConfigured:()=>A3,captureProviderApiError:()=>e2,captureModeSwitch:()=>L4,captureMentionUsed:()=>T4,captureMentionSearchResults:()=>M4,captureMentionFailed:()=>N4,captureHookDiscovery:()=>q4,captureExtensionActivated:()=>X3,captureDiffEditFailure:()=>z4,captureConversationTurnEvent:()=>wf,captureCompactionSkipped:()=>S4,captureCompactionExecuted:()=>w4,captureAuthSucceeded:()=>_$,captureAuthStarted:()=>O$,captureAuthLoggedOut:()=>i$,captureAuthFailed:()=>z$,captureAgentTeamCreated:()=>y4,captureAgentCreated:()=>n$,buildWorkspaceMetadata:()=>r2,buildTeamProgressSummary:()=>M2,buildSdkErrorProperties:()=>iq,buildRemoteConfigSessionBlobUploadMetadata:()=>C5,buildDelegatedAgentConfig:()=>u1,bootstrapAgentTeams:()=>rf,authorizeMcpServerOAuth:()=>K5,addLocalProvider:()=>dQ,accumulateUsageTotals:()=>H0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>OJ,UnifiedConfigFileWatcher:()=>Qf,ToolPresets:()=>m0,TelemetryService:()=>Sf,TelemetryLoggerSink:()=>j8,TEAM_TOOL_NAMES:()=>pf,SubprocessSandbox:()=>W2,StoredProviderSettingsSchema:()=>K2,StoredProviderSettingsEntrySchema:()=>a6,SqliteTeamStore:()=>Uf,SqliteSessionStore:()=>G$,SessionVersioningService:()=>_1,SessionVersioningError:()=>w0,SessionSource:()=>P0,SessionNotFoundError:()=>M$,SapSettingsSchema:()=>l6,SKILLS_CONFIG_DIRECTORY_NAME:()=>LJ,SESSION_STATUSES:()=>c8,SESSION_NOT_FOUND_ERROR_CODE:()=>C1,SDK_ERROR_TELEMETRY_EVENT:()=>Hw,RpcClineAccountService:()=>KJ,RemoteRuntimeHost:()=>N2,ReasoningSettingsSchema:()=>v6,RULES_CONFIG_DIRECTORY_NAME:()=>X5,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>E5,ProviderSettingsSchema:()=>B1,ProviderSettingsManager:()=>R$,ProviderProtocolSchema:()=>x6,ProviderIdSchema:()=>YJ,ProviderClientSchema:()=>m6,OpenTelemetryProvider:()=>hf,OcaSettingsSchema:()=>p6,OPENAI_COMPATIBLE_PROVIDERS:()=>jJ,NodeHubClient:()=>s0,NativeHubTransportAdapter:()=>W4,ModelCatalogSettingsSchema:()=>r6,LocalRuntimeHost:()=>U$,Llms:()=>pq,InMemoryWorkspaceManager:()=>G2,InMemoryMcpManager:()=>Vf,HubUIClient:()=>nW,HubTransportError:()=>O0,HubSessionClient:()=>iW,HubServerTransport:()=>u2,HubScheduleService:()=>qf,HubScheduleCommandService:()=>Tf,HubRuntimeHost:()=>m$,HubCommandError:()=>kf,HookEventPayloadSchema:()=>S5,HookEventNameSchema:()=>w5,HookConfigFileName:()=>H2,HOOK_CONFIG_FILE_EVENT_MAP:()=>e8,HOOKS_CONFIG_DIRECTORY_NAME:()=>L6,GlobalSettingsSchema:()=>J8,GcpSettingsSchema:()=>c6,FileTeamPersistenceStore:()=>t5,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>JW,DefaultToolNames:()=>J0,DefaultRuntimeBuilder:()=>I2,DefaultLlmsSdk:()=>$4,DEFAULT_MODELS_CATALOG_URL:()=>C6,DEFAULT_HUB_PORT:()=>bW,DEFAULT_HUB_PATHNAME:()=>kW,DEFAULT_HUB_HOST:()=>EW,CoreSettingsService:()=>U1,CoreSessionService:()=>F$,ContributionRegistry:()=>nq,ClineCore:()=>aJ,ClineAccountService:()=>BJ,ChatViewStateSchema:()=>X7,ChatSummarySchema:()=>fW,ChatSessionStatusSchema:()=>o5,ChatSessionConfigSchema:()=>s5,ChatMessageSchema:()=>$W,ChatMessageRoleSchema:()=>e5,CORE_TELEMETRY_EVENTS:()=>x,CORE_BUILD_VERSION:()=>Y7,BrowserWebSocketHubAdapter:()=>J4,BUILT_IN_PROVIDER_IDS:()=>K9,BUILT_IN_PROVIDER:()=>XJ,AzureSettingsSchema:()=>d6,AwsSettingsSchema:()=>u6,AuthSettingsSchema:()=>g6,AgentTeamsRuntime:()=>Gf,AgentTeam:()=>w2,Agent:()=>Xw,ALL_DEFAULT_TOOL_NAMES:()=>l$});M(T,yc);import*as pq from"@cline/llms";import{buildClineSystemPrompt as rq,buildSdkErrorProperties as iq,ContributionRegistry as nq,captureSdkError as aq,createClineTelemetryServiceConfig as tq,createClineTelemetryServiceMetadata as sq,createContributionRegistry as oq,createTool as eq,emptyWorkspaceManifest as $w,formatDisplayUserInput as fw,noopBasicLogger as Jw,normalizeSdkError as Ww,normalizeUserInput as Zw,parseUserCommandEnvelope as Qw,registerDisposable as jw,SDK_ERROR_TELEMETRY_EVENT as Hw}from"@cline/shared";import"@cline/shared/storage";var AY={};w(AY,{isClineAccountActionRequest:()=>o6,executeClineAccountAction:()=>e6,RpcClineAccountService:()=>KJ,ClineAccountService:()=>BJ});function Q_($){if(typeof $!=="object"||$===null||!("error"in $))return;let f=$.error;return typeof f==="string"&&f.trim()?f:void 0}function YY($,f,J){let W=Q_(J);if(W)return W;let Z=f.trim();if(Z){let Q=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${$}: ${Q}`}return`Cline account request failed with status ${$}`}class BJ{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let f=$.apiBaseUrl.trim();if(!f)throw Error("apiBaseUrl is required");this.apiBaseUrl=f,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let f=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(f)}/balance`)}async fetchUsageTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/usages`)).items??[]}async fetchPaymentTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}`)}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}/balance`)}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId(f,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(f)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let f=$?.trim();if(f)return f;let W=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(W)return W;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId($,f){let J=f?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((H)=>H.organizationId===$)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return j}async request($,f){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let W=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,Q=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:f?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...W??{}},body:f?.body!==void 0?JSON.stringify(f.body):void 0,signal:Z.signal});if(j.status===204||f?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let H=await j.text(),X;if(H.trim())try{X=JSON.parse(H)}catch{if(!j.ok)throw Error(YY(j.status,H,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(YY(j.status,H,X));if(typeof X==="object"&&X!==null){let Y=X;if(typeof Y.success==="boolean"){if(!Y.success)throw Error(Y.error||"Cline account request failed");if(Y.data!==void 0)return Y.data}}if(X===void 0||X===null)throw Error("Cline account response payload was empty");return X}finally{clearTimeout(Q)}}}function o6($){return $.action==="clineAccount"}async function e6($,f){switch($.operation){case"fetchMe":return f.fetchMe();case"fetchBalance":return f.fetchBalance($.userId);case"fetchUsageTransactions":return f.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return f.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return f.fetchUserOrganizations();case"fetchOrganizationBalance":return f.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return f.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await f.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return f.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class KJ{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:f})}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:f,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var VY={};w(VY,{createOAuthClientCallbacks:()=>GJ});function GJ($){return{onAuth:({url:f,instructions:J})=>{if($.onOutput?.(J??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(f)).catch((W)=>{$.onOpenUrlError?.({url:f,error:W})})}catch(W){$.onOpenUrlError?.({url:f,error:W})}$.onOutput?.(f)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}L0();var DY={};w(DY,{startClineDeviceAuth:()=>T9,refreshClineToken:()=>PJ,loginClineOAuth:()=>F2,getValidClineCredentials:()=>FJ,createClineOAuthProvider:()=>M9,completeClineDeviceAuth:()=>N9});import{getClineEnvironmentConfig as D9}from"@cline/shared";var $5={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},PY={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},L9="https://api.workos.com",j_="/auth",BY=Array.from({length:11},($,f)=>48801+f),H_=300000,X_=30000,P2=30000,Y_=300,A_=5;class P1 extends Error{status;errorCode;constructor($,f){super($);this.name="ClineOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function V_($){let f=Date.parse($);if(Number.isNaN(f))throw Error(`Invalid expiresAt value: ${$}`);return f}function O9($,f,J={}){let W=$.userInfo.clineUserId??J.accountId,Z=$.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:Z,expires:V_($.expiresAt),accountId:W??void 0,email:$.userInfo.email||J.email,metadata:{provider:f,tokenType:$.tokenType,userInfo:$.userInfo}}}async function _9($){if(!$)return{};return typeof $==="function"?await $():$}function KY($,f){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return f;return Math.floor($)}async function GY($){await new Promise((f)=>setTimeout(f,$))}function z9($,f){if(!$.success||!$.data?.accessToken)throw Error(f);return $.data}async function FY($,f){let J=await fetch(n1(L9,PY.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(f?.requestTimeoutMs??P2)}),W=await J.json().catch(()=>({}));if(!J.ok)throw new P1(`Device authorization failed: ${J.status}${W.error_description?` - ${W.error_description}`:""}`,{status:J.status,errorCode:W.error});if(!W.device_code||!W.user_code||!W.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:W.device_code,userCode:W.user_code,verificationUri:W.verification_uri,verificationUriComplete:W.verification_uri_complete,expiresInSeconds:KY(W.expires_in,Y_),pollIntervalSeconds:KY(W.interval,A_)}}async function UY($){let f=Date.now()+$.expiresInSeconds*1000,J=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=f){let W=await fetch(n1($.workosApiBaseUrl,PY.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),Z=await W.json().catch(()=>({}));if(W.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await GY(J*1000);break}case"slow_down":{J+=1,await GY(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new P1(Z.error_description||"WorkOS authorization failed",{status:W.status,errorCode:Z.error});default:throw new P1(`WorkOS token polling failed: ${W.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:W.status,errorCode:Z.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function RY($,f,J){let W={accessToken:$.accessToken,refreshToken:$.refreshToken},Z=await fetch(n1(f.apiBaseUrl,$5.register),{method:"POST",headers:{"Content-Type":"application/json",...await _9(f.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(f.requestTimeoutMs??P2)});if(!Z.ok){let j=await Z.text().catch(()=>""),H=ef(j);throw new P1(`Token registration failed: ${Z.status}${H.message?` - ${H.message}`:""}`,{status:Z.status,errorCode:H.code})}let Q=await Z.json();return O9(z9(Q,"Invalid token exchange response"),J??f.provider)}async function B_($,f,J,W){let Z={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:f,provider:W??J.provider},Q=await fetch(n1(J.apiBaseUrl,$5.token),{method:"POST",headers:{"Content-Type":"application/json",...await _9(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??P2)});if(!Q.ok){let H=await Q.text().catch(()=>""),X=ef(H);throw new P1(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let j=await Q.json();return O9(z9(j,"Invalid token exchange response"),W??J.provider)}async function F2($){O$($.telemetry,$.provider??"cline");let f=$.useWorkOSDeviceAuth??!0,J=$.callbackPorts?.length?$.callbackPorts:BY,W=$.callbackPath??j_,Z=f?null:await $$({ports:J,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),Q=Z?.callbackUrl||`http://127.0.0.1:${J[0]??BY[0]}${W}`;try{let j;if(f){let H=D9().workOsClientId,X=await FY(H,$);$.callbacks.onAuth({url:X.verificationUriComplete??X.verificationUri,instructions:`Enter this code in your browser: ${X.userCode}`});let Y=await UY({clientId:H,deviceCode:X.deviceCode,expiresInSeconds:X.expiresInSeconds,initialPollIntervalSeconds:X.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??P2,workosApiBaseUrl:L9,onProgress:$.callbacks.onProgress});j=await RY(Y,$,$.provider)}else{let H=new URL(n1($.apiBaseUrl,$5.authorize));H.searchParams.set("client_type","extension"),H.searchParams.set("callback_url",Q),H.searchParams.set("redirect_uri",Q),$.callbacks.onAuth({url:H.toString(),instructions:"Continue the authentication process in your browser."});let X,Y=$.provider,A=await $2({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(A.error)throw Error(`OAuth error: ${A.error}`);if(X=A.code,Y=A.provider??Y,!X){let V=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=of(V,{includeProvider:!0});X=B.code,Y=B.provider??Y}if(!X)throw Error("Missing authorization code");j=await B_(X,Q,$,Y)}return _$($.telemetry,$.provider??"cline"),T$($.telemetry,{id:j.accountId,email:j.email,provider:$.provider??"cline"}),j}catch(j){throw z$($.telemetry,$.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function T9($){return await FY(D9().workOsClientId,$)}async function N9($){let f=$.provider??"cline";O$($.telemetry,f);try{let J=await UY({clientId:D9().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??P2,workosApiBaseUrl:L9}),W=await RY(J,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return _$($.telemetry,f),T$($.telemetry,{id:W.accountId,email:W.email,provider:f}),W}catch(J){throw z$($.telemetry,f,J instanceof Error?J.message:String(J)),J}}async function PJ($,f){let J=await fetch(n1(f.apiBaseUrl,$5.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await _9(f.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(f.requestTimeoutMs??P2)});if(!J.ok){let Q=await J.text().catch(()=>""),j=ef(Q);throw new P1(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let W=await J.json(),Z=$.metadata?.provider??f.provider;return O9(z9(W,"Invalid token refresh response"),Z,$)}async function FJ($,f,J){if(!$)return null;let W=J?.refreshBufferMs??H_,Z=J?.retryableTokenGraceMs??X_;if(J?.forceRefresh!==!0&&!a1($,W))return $;try{return await PJ($,f)}catch(j){if(j instanceof P1&&j.isLikelyInvalidGrant())return i$(f.telemetry,f.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function M9($){return{id:"cline",name:"Cline Account",usesCallbackServer:!($.useWorkOSDeviceAuth??!0),async login(f){return F2({...$,callbacks:f})},async refreshToken(f){return PJ(f,$)},getApiKey(f){return`workos:${f.access}`}}}L0();var _Y={};w(_Y,{refreshOpenAICodexToken:()=>UJ,openaiCodexOAuthProvider:()=>w9,normalizeOpenAICodexCredentials:()=>q9,loginOpenAICodex:()=>U2,isOpenAICodexTokenExpired:()=>y9,getValidOpenAICodexCredentials:()=>RJ,OPENAI_CODEX_OAUTH_CONFIG:()=>e});import{nanoid as K_}from"nanoid";var e={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class f5 extends Error{status;errorCode;constructor($,f){super($);this.name="OpenAICodexOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function G_($,f,J=e.redirectUri){let W=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:$,code_verifier:f,redirect_uri:J}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!W.ok)return{type:"failed"};let Z=await W.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}async function P_($){try{let f=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:e.clientId}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!f.ok){let W=await f.text().catch(()=>""),Z=ef(W);throw new f5(`Token refresh failed: ${f.status}${Z.message?` - ${Z.message}`:""}`,{status:f.status,errorCode:Z.code})}let J=await f.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch(f){if(f instanceof f5)throw f;return{type:"failed"}}}async function F_($="pi"){let{verifier:f,challenge:J}=await A6(),W=K_(32),Z=new URL(e.authorizationEndpoint);return Z.searchParams.set("response_type","code"),Z.searchParams.set("client_id",e.clientId),Z.searchParams.set("redirect_uri",e.redirectUri),Z.searchParams.set("scope",e.scopes),Z.searchParams.set("code_challenge",J),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("state",W),Z.searchParams.set("id_token_add_organizations","true"),Z.searchParams.set("codex_cli_simplified_flow","true"),Z.searchParams.set("originator",$),{verifier:f,state:W,url:Z.toString()}}function U_(){try{let $=new URL(e.redirectUri),f=$.port.length>0?Number.parseInt($.port,10):e.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(f)?f:e.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:e.callbackPort,callbackPath:"/auth/callback",redirectUri:e.redirectUri}}}function LY($,f){let J=f?_0(f):_0($),W=J?J:_0($),Q=W?.[e.jwtClaimPath]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let j=W?.organizations;if(Array.isArray(j)&&j.length>0){let X=j[0];if(typeof X?.id==="string"&&X.id.length>0)return X.id}let H=W?.chatgpt_account_id;if(typeof H==="string"&&H.length>0)return H;return null}function OY($,f){let J=LY($.access,$.idToken)??f?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||f?.refresh||"",expires:$.expires,accountId:J,email:$.email??f?.email,metadata:{...f?.metadata??{},provider:"openai-codex"}}}async function U2($){O$($.telemetry,"openai-codex");let f=U_(),{verifier:J,state:W,url:Z}=await F_($.originator),Q=await $$({host:f.host,ports:[f.port],callbackPath:f.callbackPath,expectedState:W});$.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let H=await $2({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(H.state&&H.state!==W)throw Error("State mismatch");if(j=H.code,!j){let A=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),V=of(A,{allowHashCodeState:!0});if(V.state&&V.state!==W)throw Error("State mismatch");j=V.code}if(!j)throw Error("Missing authorization code");let X=await G_(j,J,f.redirectUri);if(X.type!=="success")throw Error("Token exchange failed");let Y=OY(X);return _$($.telemetry,"openai-codex"),T$($.telemetry,{id:Y.accountId,email:Y.email,provider:"openai-codex"}),Y}catch(H){throw z$($.telemetry,"openai-codex",H instanceof Error?H.message:String(H)),H}finally{Q.close()}}async function UJ($,f){let J=await P_($);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=OY(J,f);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function RJ($,f){if(!$)return null;let J=f?.refreshBufferMs??e.refreshBufferMs,W=f?.retryableTokenGraceMs??e.retryableTokenGraceMs;if(f?.forceRefresh!==!0&&!a1($,J))return $;try{return await UJ($.refresh,$)}catch(Q){if(Q instanceof f5&&Q.isLikelyInvalidGrant())return i$(f?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}function y9($,f=e.refreshBufferMs){return a1($,f)}function q9($){let f=$.accountId??LY($.access);if(!f)throw Error("Failed to extract accountId from token");return{...$,accountId:f,metadata:{...$.metadata??{},provider:"openai-codex"}}}var w9={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return U2({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return UJ($.refresh,$)},getApiKey($){return $.access}};var KV={};w(KV,{ClineCore:()=>aJ});function zY($){if($===!0)return{};if(!$)return;return $}function TY($){if($==="user")return"global";return $}class S9{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let f=this.getService().ingestEvent($);return{event:f.event,duplicate:f.duplicate,matchedSpecIds:f.matchedSpecs.map((J)=>J.specId),queuedRuns:f.queuedRuns,suppressions:f.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function NY($){let{host:f}=$;return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||P0.CLI,interactive:!1,config:{providerId:B2(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:L_(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,W){let Z=await f.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content),delivery:W.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:D_(Z)}},async abortSession(J){return await f.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function J5($){let f=R_($.automationService,$.automation),J=$.context?.client??($.clientName?{name:$.clientName}:void 0),W=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),Z=$.context?.logger??$.logger,Q=$.context?.telemetry??$.telemetry;if(!f&&!J&&!W&&!Z&&!Q)return $.context;return{...$.context??{},...J?{client:J}:{},...W?{user:W}:{},...Z?{logger:Z}:{},...Q?{telemetry:Q}:{},...f?{automation:f}:{}}}function R_($,f){if(!$)return;return{ingestEvent:(J)=>{f.ingestEvent(J)}}}function D_($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function L_($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var VA={};w(VA,{createCoreSettingsService:()=>Bf,CoreSettingsService:()=>U1});import{existsSync as R5}from"node:fs";import{basename as XA,isAbsolute as cz,relative as dz}from"node:path";var mY={};w(mY,{resolveWorkflowsConfigSearchPaths:()=>yJ,resolveSkillsConfigSearchPaths:()=>NJ,resolveRulesConfigSearchPaths:()=>MJ,parseWorkflowConfigFromMarkdown:()=>TJ,parseSkillConfigFromMarkdown:()=>_J,parseRuleConfigFromMarkdown:()=>zJ,createWorkflowsConfigDefinition:()=>SJ,createUserInstructionConfigService:()=>F1,createSkillsConfigDefinition:()=>qJ,createRulesConfigDefinition:()=>wJ,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>OJ,UnifiedConfigFileWatcher:()=>Qf,SKILLS_CONFIG_DIRECTORY_NAME:()=>LJ,RULES_CONFIG_DIRECTORY_NAME:()=>X5});import{createHash as O_}from"node:crypto";import{watch as __}from"node:fs";import{readdir as z_,readFile as T_}from"node:fs/promises";import{join as N_}from"node:path";function M_($){return O_("sha1").update($).digest("hex")}function qY($){return Boolean($&&typeof $==="object"&&"code"in $)}function MY($){return qY($)&&$.code==="ENOENT"}function yY($){return qY($)&&($.code==="EACCES"||$.code==="EPERM")}class Qf{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,f){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=f?.debounceMs??75,this.emitParseErrors=f?.emitParseErrors??!1;for(let J of $){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let W of J.directories){let Z=this.baseTypesByDirectory.get(W);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(W,new Set([J.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let f=this.definitionsByType.get($);if(!f)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(f)})}getSnapshot($){let f=this.recordsByType.get($);return new Map([...f?.entries()??[]].map(([J,W])=>[J,{...W}]))}getAllSnapshots(){let $=new Map;for(let[f,J]of this.recordsByType.entries())$.set(f,new Map([...J.entries()].map(([W,Z])=>[W,{...Z}])));return $}emit($){for(let f of this.listeners)f($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[f,J]of this.watchersByDirectory.entries()){if($.has(f))continue;J.close(),this.watchersByDirectory.delete(f)}this.watchedTypesByDirectory=$;for(let f of $.keys()){if(this.watchersByDirectory.has(f))continue;try{let J=__(f,()=>{let W=this.watchedTypesByDirectory.get(f);if(!W)return;for(let Z of W)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set(f,J),J.on("error",(W)=>{let Z=this.watchedTypesByDirectory.get(f);if(!Z)return;for(let Q of Z)this.emit({kind:"error",type:Q,error:W,filePath:f})})}catch(J){if(!MY(J)&&!yY(J)){let W=$.get(f);if(!W)continue;for(let Z of W)this.emit({kind:"error",type:Z,error:J,filePath:f})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let f of $){let J=this.definitionsByType.get(f);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal($){let{records:f,discoveredDirectories:J}=await this.loadDefinition($),W=this.recordsByType.get($.type)??new Map;for(let[Z,Q]of W.entries()){if(f.has(Z))continue;this.emit({kind:"remove",type:$.type,id:Z,filePath:Q.filePath})}for(let[Z,Q]of f.entries()){let j=W.get(Z);if(j&&j.filePath===Q.filePath&&j.fingerprint===Q.fingerprint)continue;this.emit({kind:"upsert",record:{type:Q.type,id:Z,item:Q.item,filePath:Q.filePath}})}if(this.recordsByType.set($.type,f),this.discoveredDirectoriesByType.set($.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let f=new Map,J=new Set;for(let W of $.directories){J.add(W);let Z=$.discoverFiles?await $.discoverFiles(W):await this.readDirectoryFileCandidates(W);for(let Q of Z){let{fileName:j,filePath:H}=Q;if(J.add(Q.directoryPath),$.includeFile&&!$.includeFile(j,H))continue;try{let X=await T_(H,"utf8"),Y={type:$.type,directoryPath:Q.directoryPath,fileName:j,filePath:H,content:X},A=$.parseFile(Y),V=$.resolveId(A,Y).trim();if(!V)continue;f.set(V,{type:$.type,id:V,item:A,filePath:H,fingerprint:M_(X)})}catch(X){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:X,filePath:H})}}}return{records:f,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let $=new Map;for(let[f,J]of this.baseTypesByDirectory.entries())$.set(f,new Set(J));for(let[f,J]of this.discoveredDirectoriesByType.entries())for(let W of J){let Z=$.get(W);if(Z)Z.add(f);else $.set(W,new Set([f]))}return $}async readDirectoryFileCandidates($){try{return(await z_($,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:$,fileName:J.name,filePath:N_($,J.name)})).sort((J,W)=>J.fileName.localeCompare(W.fileName))}catch(f){if(MY(f)||yY(f))return[];throw f}}}import{readdir as C9,readFile as y_,stat as h9}from"node:fs/promises";import{basename as I$,dirname as q_,extname as Z5,join as y0,resolve as DJ}from"node:path";import{AGENTS_RULES_FILE_NAME as wY,RULES_CONFIG_DIRECTORY_NAME as X5,resolveGlobalAgentsRulesPath as w_,resolveRulesConfigSearchPaths as S_,resolveSkillsConfigSearchPaths as h_,resolveWorkflowsConfigSearchPaths as C_,SKILLS_CONFIG_DIRECTORY_NAME as LJ,WORKFLOWS_CONFIG_DIRECTORY_NAME as OJ}from"@cline/shared/storage";import E_ from"yaml";var W5="SKILL.md",b_="managed.json",k_=new Set([".md",".markdown",".txt"]);function E9($){return $.trim().toLowerCase()}function R2($){let f=$;return f?.code==="ENOENT"||f?.code==="EACCES"||f?.code==="EPERM"||f?.code==="ELOOP"}function Q5($){return k_.has(Z5($).toLowerCase())}function SY($){let f=[],J=new Set;for(let W of $){let Z=DJ(W);if(J.has(Z))continue;J.add(Z),f.push(W)}return f}function I_($){let f=[...$?.directories??NJ($?.workspacePath)];if($?.pluginSkillDirectories)f.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)f.push(...UX({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return SY(f)}async function b9($){try{let f=await C9($,{withFileTypes:!0}),J=[];for(let W of f){if(!W.isDirectory())continue;let Z=y0($,W.name),Q=y0(Z,b_);try{let j=await y_(Q,"utf8"),H=JSON.parse(j);if(H&&typeof H==="object")J.push(Z)}catch(j){if(R2(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((W,Z)=>W.localeCompare(Z))}catch(f){if(R2(f))return[];throw f}}function k9($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,W,Z]=J;try{let Q=E_.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:Z,hadFrontmatter:!0}}catch(Q){let j=Q instanceof Error?Q.message:String(Q);return{data:{},body:$,hadFrontmatter:!0,parseError:j}}}function j5($,f,J){if($===void 0||$===null){if(J)throw Error(`Missing required frontmatter field '${f}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${f}' must be a string.`);let W=$.trim();if(!W&&J)throw Error(`Frontmatter field '${f}' cannot be empty.`);return W||void 0}function D2($,f){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${f}' must be a boolean.`);return $}function x_($,f){if(I$($.filePath).toLowerCase()!==wY.toLowerCase())return I$($.filePath,Z5($.filePath));if(f&&DJ($.filePath)===DJ(f,wY))return"Workspace AGENTS.md";if(DJ($.filePath)===DJ(w_()))return"Global AGENTS.md";return I$($.filePath,Z5($.filePath))}function _J($,f){let{data:J,body:W,parseError:Z}=k9($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in skill file.");let H=j5(J.name,"name",!1)??f.trim();if(!H)throw Error("Missing skill name.");return{name:H,description:j5(J.description,"description",!1),disabled:D2(J.disabled,"disabled")??(D2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function zJ($,f){let{data:J,body:W,parseError:Z}=k9($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in rule file.");let j=j5(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:D2(J.disabled,"disabled")??(D2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function TJ($,f){let{data:J,body:W,parseError:Z}=k9($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in workflow file.");let j=j5(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:D2(J.disabled,"disabled")??(D2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function NJ($){return h_($)}function MJ($){return S_($)}function yJ($){return C_($)}async function hY($){if(I$($)===".cline"){let f=await b9($);return(await Promise.all(f.map((W)=>hY(y0(W,LJ))))).flat()}try{let f=await C9($,{withFileTypes:!0}),J=[];for(let W of f){if(W.isFile()&&W.name===W5){J.push({directoryPath:$,fileName:W.name,filePath:y0($,W.name)});continue}let Z=y0($,W.name);if(W.isDirectory()||W.isSymbolicLink()&&await h9(Z).then((j)=>j.isDirectory()).catch((j)=>{if(R2(j))return!1;throw j}))J.push({directoryPath:Z,fileName:W5,filePath:y0(Z,W5)})}return J}catch(f){if(R2(f))return[];throw f}}async function H5($){if(I$($)===".cline"){let f=await b9($);return(await Promise.all(f.map((W)=>H5(y0(W,"rules.md"))))).flat()}try{if((await h9($)).isFile())return[{directoryPath:q_($),fileName:I$($),filePath:$}]}catch(f){if(!R2(f))throw f}try{let J=(await C9($,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&Q5(Z.name)).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:y0($,Z.name)})),W=y0($,"AGENTS.md");try{if((await h9(W)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:$,fileName:"AGENTS.md",filePath:W})}}catch{}return J}catch(f){if(R2(f))return[];throw f}}async function m_($){if(I$($)===".cline"){let f=await b9($);return(await Promise.all(f.map((W)=>H5(y0(W,OJ))))).flat()}return H5($)}function qJ($){let f=I_($),J=$?.workspacePath?y0($.workspacePath,".cline"):void 0;return{type:"skill",directories:J?SY([...f,J]):f,discoverFiles:hY,includeFile:(W)=>W===W5,parseFile:(W)=>_J(W.content,I$(W.directoryPath)),resolveId:(W)=>E9(W.name)}}function wJ($){let f=$?.directories??MJ($?.workspacePath),J=$?.workspacePath?y0($.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...f,J]:f,discoverFiles:H5,includeFile:(W,Z)=>W===".clinerules"||Q5(W)||Q5(Z),parseFile:(W)=>zJ(W.content,x_(W,$?.workspacePath)),resolveId:(W)=>E9(W.name)}}function SJ($){let f=$?.directories??yJ($?.workspacePath),J=$?.workspacePath?y0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...f,J]:f,discoverFiles:m_,includeFile:(W)=>Q5(W),parseFile:(W)=>TJ(W.content,I$(W.filePath,Z5(W.filePath))),resolveId:(W)=>E9(W.name)}}function CY($){let f=[qJ($?.skills),wJ($?.rules),SJ($?.workflows)];return new Qf(f,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as EY}from"@cline/shared";function g_($,f){if($.description?.trim())return EY($.description,".");if(f==="workflow")return;return EY($.instructions,".")}function v_($){return $.disabled!==!0}function bY($,f){return[...$.getSnapshot(f).entries()].map(([J,W])=>({id:J,record:W})).filter(({record:J})=>v_(J.item)).map(({id:J,record:W})=>({id:J,name:W.item.name,instructions:W.item.instructions,description:g_(W.item,f),kind:f})).sort((J,W)=>J.name.localeCompare(W.name))}function hJ($){let f=new Map;for(let J of[...bY($,"workflow"),...bY($,"skill")])if(!f.has(J.name))f.set(J.name,J);return[...f.values()].sort((J,W)=>J.name.localeCompare(W.name))}function kY($,f){if(!$.startsWith("/")||$.length<2)return $;let J=$.match(/^\/(\S+)/);if(!J)return $;let W=J[1];if(!W)return $;let Z=W.length+1,Q=$.slice(Z),j=hJ(f).find((H)=>H.name===W);return j?`${j.instructions}${Q}`:$}function Y5($){return $.trim().replace(/^\/+/,"").toLowerCase()}function u_($){if(!$||$.length===0)return;let f=$.map(Y5).filter((J)=>J.length>0);return f.length>0?new Set(f):void 0}function c_($,f,J){if(!J)return!0;let W=Y5($),Z=Y5(f),Q=W.includes(":")?W.split(":").at(-1)??W:W,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(W)||J.has(Z)||J.has(Q)||J.has(j)}function CJ($,f){let J=u_(f);return[...$.getSnapshot("skill").entries()].map(([Z,Q])=>{let j=Q.item;return{id:Z,name:j.name.trim(),description:j.description?.trim(),disabled:j.disabled===!0,skill:j}}).filter((Z)=>c_(Z.id,Z.name,J))}function d_($,f){return CJ($,f).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,W)=>J.localeCompare(W))}function l_($,f,J){let W=Y5(f);if(!W)return{error:"Missing skill name."};let Z=CJ($,J),Q=Z.find((A)=>A.id===W);if(Q){let{skill:A}=Q;if(A.disabled===!0)return{error:`Skill "${A.name}" is configured but disabled.`};return{id:Q.id,skill:A}}let j=W.includes(":")?W.split(":").at(-1)??W:W,H=Z.filter(({id:A})=>{if(A===j)return!0;return A.endsWith(`:${j}`)}),X=H.filter(({skill:A})=>A.disabled!==!0);if(X.length===1){let{id:A,skill:V}=X[0];return{id:A,skill:V}}if(X.length>1)return{error:`Skill "${f}" is ambiguous. Use one of: ${X.map(({id:A})=>A).join(", ")}`};if(H.length===1){let{skill:A}=H[0];return{error:`Skill "${A.name}" is configured but disabled.`}}if(H.length>1)return{error:`Skill "${f}" is ambiguous, and all matches are disabled: ${H.map(({id:A})=>A).join(", ")}`};let Y=d_($,J);return{error:Y.length>0?`Skill "${f}" not found. Available skills: ${Y.join(", ")}`:"No skills are currently available."}}function p_($,f=Promise.resolve(),J){let W=new Set,Z=async(Q,j)=>{await f;let H=l_($,Q,J);if("error"in H)return H.error;let{id:X,skill:Y}=H;if(W.has(X))return`Skill "${Y.name}" is already running.`;W.add(X);try{let A=j?.trim(),V=A?`
|
|
459
|
+
<command-args>${A}</command-args>`:"",B=Y.description?.trim()?`Description: ${Y.description.trim()}
|
|
460
460
|
|
|
461
|
-
`:"";return`<command-name>${Y.name}</command-name>${
|
|
461
|
+
`:"";return`<command-name>${Y.name}</command-name>${V}
|
|
462
462
|
<command-instructions>
|
|
463
463
|
${B}${Y.instructions}
|
|
464
|
-
</command-instructions>`}finally{
|
|
464
|
+
</command-instructions>`}finally{W.delete(X)}};return Object.defineProperty(Z,"configuredSkills",{get:()=>CJ($,J).map(({skill:Q,...j})=>j),enumerable:!0,configurable:!1}),Z}function IY($){let f=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((W)=>Boolean(W))},async setup(W){if(await f,$.includeRules)W.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>KW($.watcher)});if($.registerSkillsTool)W.registerTool(x1(p_($.watcher,f,$.allowedSkillNames)));for(let Z of hJ($.watcher).filter((Q)=>Q.kind==="skill"&&$.includeSkills||Q.kind==="workflow"&&$.includeWorkflows))W.registerCommand({name:Z.name,description:Z.description,handler:(Q)=>{let j=Q.trim();return j?`${Z.instructions}
|
|
465
465
|
|
|
466
|
-
${j}`:Z.instructions}})}}}class
|
|
467
|
-
${
|
|
466
|
+
${j}`:Z.instructions}})}}}class xY{watcher;ready;stopped=!1;constructor($){this.watcher=CY($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([f,J])=>({type:$,id:f,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return hJ(this.watcher)}resolveRuntimeSlashCommand($){return kY($,this.watcher)}hasConfiguredSkills($){return CJ(this.watcher,$).some((f)=>!f.disabled)}createExtension($){return IY({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function F1($){return new xY($)}import{readFile as r_,writeFile as i_}from"node:fs/promises";import vY from"yaml";function n_($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,W,Z]=J,Q=vY.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:Z,hadFrontmatter:!0}}function gY($,f){return`---
|
|
467
|
+
${vY.stringify($).trimEnd()}
|
|
468
468
|
---
|
|
469
|
-
${f}`}function
|
|
469
|
+
${f}`}function a_($,f){let{data:J,body:W,hadFrontmatter:Z}=n_($);if(!Z&&f)return $;if(f){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return W;return gY(J,W)}return J.disabled=!0,gY(J,W)}async function uY({filePath:$,enabled:f}){let J=await r_($,"utf8"),W=a_(J,f);return await i_($,W),{filePath:$,enabled:f,disabled:!f}}var QA={};w(QA,{updateMcpServerOAuthState:()=>Yf,setMcpServerDisabled:()=>Hf,resolveMcpServerRegistrations:()=>A$,resolveDefaultMcpSettingsPath:()=>z0,registerMcpServersFromSettingsFile:()=>Af,loadMcpSettingsFile:()=>jf,listMcpServerOAuthStatuses:()=>bJ,hasMcpSettingsFile:()=>x$,getMcpServerOAuthState:()=>Xf,createMcpTools:()=>_2,createDisabledMcpToolPolicy:()=>kJ,createDisabledMcpToolPolicies:()=>F5,createDefaultMcpServerClientFactory:()=>O2,authorizeMcpServerOAuth:()=>K5,InMemoryMcpManager:()=>Vf});import{spawn as _z}from"node:child_process";import{StringDecoder as $A}from"node:string_decoder";import{UnauthorizedError as tY}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as zz}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as Bz}from"node:crypto";import{UnauthorizedError as Kz}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as Gz}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as Pz}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as Fz}from"@modelcontextprotocol/sdk/client/streamableHttp.js";A5();var Uz="/mcp/oauth/callback",Rz=[1456,1457,1458],Dz=300000;function Lz($){if($ instanceof Error){let f=$.message.trim();if(f.length>0)return f}return String($)}function Oz($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function B5($){let f={};try{f=Xf($.serverName,{filePath:$.settingsPath})??{}}catch{f={}}let J,W,Z=async(j)=>{let H=L2(j(f))??{};try{f=Yf($.serverName,()=>H,{filePath:$.settingsPath})}catch{f=H}};return{provider:{get redirectUrl(){return f.redirectUrl??$.redirectUrl},get clientMetadata(){return Oz(f.redirectUrl??$.redirectUrl)},state:()=>{return W=Bz(),W},clientInformation:()=>f.clientInformation,saveClientInformation:async(j)=>{await Z((H)=>({...H,clientInformation:j,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>f.tokens,saveTokens:async(j)=>{await Z((H)=>({...H,tokens:j,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(j)=>{J=j.toString(),await $.onAuthorizationUrl?.(J)},saveCodeVerifier:async(j)=>{await Z((H)=>({...H,codeVerifier:j,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!f.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return f.codeVerifier},invalidateCredentials:async(j)=>{await Z((H)=>{if(j==="all")return{lastError:H.lastError,redirectUrl:H.redirectUrl};return{...H,...j==="client"?{clientInformation:void 0}:{},...j==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...j==="verifier"?{codeVerifier:void 0}:{},...j==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(j)=>{await Z((H)=>({...H,discoveryState:j}))},discoveryState:()=>f.discoveryState},getLastAuthorizationUrl:()=>J,getLastOAuthState:()=>W,resetInteractiveState:async()=>{await Z((j)=>({...j,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(j)=>{await Z((H)=>({...H,lastError:j}))},clearError:async()=>{await Z((j)=>({...j,lastError:void 0}))}}}function V5($){let f=$.registration.transport;if(f.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let J=f.headers?{headers:f.headers}:void 0;if(f.type==="sse")return new Pz(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch});return new Fz(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch})}function aY($){return new Gz({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function K5($){let f=$.serverName.trim();if(!f)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:J}=await Promise.resolve().then(() => (A5(),nY)),W=J({filePath:$.filePath}).find((X)=>X.name===f);if(!W)throw Error(`MCP server "${f}" is not configured.`);if(W.disabled)throw Error(`MCP server "${f}" is disabled. Enable it before running OAuth.`);if(W.transport.type==="stdio")throw Error(`MCP server "${f}" uses stdio transport and does not support OAuth browser flow.`);let Z=await $$({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:Rz,callbackPath:$.callbackPath??Uz,timeoutMs:$.timeoutMs??Dz,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!Z.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let Q=B5({settingsPath:$.filePath,serverName:f,redirectUrl:Z.callbackUrl,onAuthorizationUrl:async(X)=>{await $.openUrl?.(X)}});await Q.resetInteractiveState();let j=aY($),H;try{let X=V5({registration:W,oauthProvider:Q.provider,fetch:$.fetch});try{return await j.connect(X),await j.listTools(),await Q.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" is already authorized.`}}catch(Y){if(!(Y instanceof Kz))throw Y;if(!Q.getLastAuthorizationUrl())throw Error(`MCP server "${f}" did not provide an authorization URL.`);let V=await Z.waitForCallback();if(!V)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(V.error)throw Error(`OAuth authorization failed: ${V.error}`);if(!V.code)throw Error("OAuth callback did not include an authorization code.");let B=Q.getLastOAuthState();if(!B)throw Error(`MCP server "${f}" did not start an OAuth stateful authorization flow.`);if(V.state!==B)throw Error("OAuth authorization failed: state mismatch.");await X.finishAuth(V.code),H=aY($);let K=V5({registration:W,oauthProvider:Q.provider,fetch:$.fetch});return await H.connect(K),await H.listTools(),await Q.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" OAuth authorization completed.`}}}catch(X){let Y=Lz(X);throw await Q.markError(Y),Error(Y)}finally{await j.close().catch(()=>{return}),await H?.close().catch(()=>{return}),Z.close()}}var Tz="2024-11-05",Nz=5000,Mz=1500,sY="http://127.0.0.1:1456/mcp/oauth/callback";function G5($){return $ instanceof Error?$.message:String($)}function oY($){let f=Buffer.from(JSON.stringify($),"utf8"),J=Buffer.from(`Content-Length: ${f.byteLength}\r
|
|
470
470
|
\r
|
|
471
|
-
`,"utf8");return Buffer.concat([J,f])}function
|
|
472
|
-
`,"utf8")}class
|
|
471
|
+
`,"utf8");return Buffer.concat([J,f])}function eY($){return Buffer.from(`${JSON.stringify($)}
|
|
472
|
+
`,"utf8")}class g9{buffer="";decoder=new $A("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`\r
|
|
473
473
|
\r
|
|
474
|
-
`);if(J<0)break;let Z=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!Z)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let
|
|
475
|
-
`);if(J<0)break;let Q=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),Q.length>0)f.push(Q)}return f}}class YY{registration;process;nextRequestId=1;pending=new Map;framedParser=new VQ;newlineParser=new AQ;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],f;for(let J of $){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:Hz,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},Vz),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(Q){f=Q instanceof Error?Q:Error(String(Q))}}throw f??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((f)=>typeof f?.name==="string"&&typeof f.inputSchema==="object"&&f.inputSchema!==null).map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let f=this.registration.transport;if(f.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${f.type}`);this.framedParser=new VQ,this.newlineParser=new AQ,this.stderrBuffer="",this.protocolMode=$;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=jz(f.command,f.args??[],{cwd:f.cwd,env:{...process.env,...f.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=Q,Q.stdout.on("data",(Z)=>this.handleStdout(Z)),Q.stderr.on("data",(Z)=>{if(this.process!==Q)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(Z)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${rJ(Z)}`))}),Q.once("exit",(Z,W)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${W??"null"}).${j}`))})}handleStdout($){try{let f=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let J of f){let Q=JSON.parse(J);if(typeof Q.id!=="number")continue;let Z=this.pending.get(Q.id);if(!Z)continue;if(this.pending.delete(Q.id),clearTimeout(Z.timeout),Q.error){let W=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;Z.reject(Error(W));continue}Z.resolve(Q.result)}}catch(f){this.handleProtocolFailure(f)}}handleProtocolFailure($){let f=this.process;if(!f)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${rJ($)}.${J}`)),f.kill()}async request($,f,J=Yz){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,W={jsonrpc:"2.0",id:Z,method:$,...f?{params:f}:{}},j=new Promise((X,H)=>{let Y=setTimeout(()=>{this.pending.delete(Z),H(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},J);this.pending.set(Z,{resolve:X,reject:H,timeout:Y})});try{Q.stdin.write(this.protocolMode==="framed"?jY(W):XY(W))}catch(X){let H=this.pending.get(Z);if(H)clearTimeout(H.timeout),this.pending.delete(Z);throw X}return j}notify($,f){let J=this.process;if(!J?.stdin.writable)return;let Q={jsonrpc:"2.0",method:$,...f?{params:f}:{}};J.stdin.write(this.protocolMode==="framed"?jY(Q):XY(Q))}failAllPending($){for(let[f,J]of this.pending)clearTimeout(J.timeout),this.pending.delete(f),J.reject($)}}class VY{registration;options;client;authContext;constructor($,f){this.registration=$;this.options=f}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=lJ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??WY});this.authContext=$;try{let f=new Xz({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=dJ({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await f.connect(J),await $.clearError(),this.client=f}catch(f){let J=f instanceof ZY?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):rJ(f);throw await $.markError(J),Error(J)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema&&typeof J.inputSchema==="object"&&!Array.isArray(J.inputSchema)?J.inputSchema:{}}))}catch(f){return await this.handleOperationError(f)}}async callTool($){let f=await this.ensureConnectedClient();try{return await f.callTool({name:$.name,arguments:$.arguments??{}})}catch(J){return await this.handleOperationError(J)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let f=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${f} Run authorizeMcpServerOAuth for this server.`;return`${f} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let f=this.authContext??lJ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??WY}),J=$ instanceof ZY?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):rJ($);throw await f.markError(J),Error(J)}}function H8($={}){return(f)=>f.transport.type==="stdio"?new YY(f):new VY(f,$)}cJ();function c0(){return Date.now()}function Az($){return $.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}class e1{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let f=this.servers.get($.name);if(!f){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:c0()});return}let J=JSON.stringify(f.registration.transport)!==JSON.stringify($.transport);if(f.registration={...$},f.updatedAt=c0(),J)await this.disconnectState(f),f.client=void 0,f.toolCache=void 0,f.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.connectState(f)})}async disconnectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f)})}async setServerDisabled($,f){await this.runExclusive($,async()=>{let J=this.requireServer($);if(J.registration={...J.registration,disabled:f},J.updatedAt=c0(),f)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,f)=>$.name.localeCompare(f.name))}async listTools($){let f=this.requireServer($),J=f.toolCacheUpdatedAt??0;if(f.toolCache&&c0()-J<=this.toolsCacheTtlMs)return f.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let f=this.requireServer($),Q=await(await this.ensureConnectedClient(f)).listTools(),Z=Az(Q);return f.toolCache=Z,f.toolCacheUpdatedAt=c0(),f.updatedAt=c0(),Z})}async callTool($){return this.runExclusive($.serverName,async()=>{let f=this.requireServer($.serverName),J=await this.ensureConnectedClient(f);return f.updatedAt=c0(),J.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let f of $)await this.unregisterServer(f)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=c0();try{let f=$.client??await this.clientFactory($.registration);await f.connect(),$.client=f,$.status="connected",$.lastError=void 0,$.updatedAt=c0()}catch(f){throw $.status="disconnected",$.lastError=f instanceof Error?f.message:String(f),$.updatedAt=c0(),f}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=c0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=c0()}}requireServer($){let f=this.servers.get($);if(!f)throw Error(`Unknown MCP server: ${$}`);return f}async runExclusive($,f){let J=this.operationLocks.get($)??Promise.resolve(),Q,Z=new Promise((j)=>{Q=j}),W=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set($,W),await J.catch(()=>{return});try{return await f()}finally{if(Q?.(),this.operationLocks.get($)===W)this.operationLocks.delete($)}}}import{createHash as Bz}from"node:crypto";var AY=128,Gz=/[^a-zA-Z0-9_-]+/g,BY=8,Kz=1,Fz="mcp_tool";function Pz($){return Bz("sha1").update($).digest("hex").slice(0,BY)}function Uz($){return $.replace(Gz,"_")}var iJ=({serverName:$,toolName:f})=>{let J=`${$}__${f}`,Q=Uz(J);if(Q===J&&J.length<=AY)return J;let Z=Pz(J),W=AY-Kz-BY;return`${Q.slice(0,W)||Fz}_${Z}`};function P6($){return{[($.nameTransform??iJ)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function nJ($){let f={};for(let J of $.toolNames)Object.assign(f,P6({serverName:$.serverName,toolName:J,nameTransform:$.nameTransform}));return f}import{createTool as Dz}from"@cline/shared";function Rz($,f){let J=f.description?.trim();if(J)return J;return`Execute MCP tool "${f.name}" from server "${$}".`}async function Y8($){let f=await $.provider.listTools($.serverName),J=$.nameTransform??iJ;return f.map((Q)=>{let Z=J({serverName:$.serverName,toolName:Q.name});return Dz({name:Z,description:Rz($.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(W,j)=>$.provider.callTool({serverName:$.serverName,toolName:Q.name,arguments:W&&typeof W==="object"&&!Array.isArray(W)?W:void 0,context:j})})})}O$();var FY={};y(FY,{listPluginToolsWithDiagnostics:()=>aJ,listPluginTools:()=>U6});import{stat as Lz}from"node:fs/promises";O$();var Oz=32,V8=new Map;function zz($,f){if(!V8.has($)&&V8.size>=Oz){let J=V8.keys().next().value;if(J)V8.delete(J)}V8.set($,f)}async function _z($){let f=await Promise.all($.pluginPaths.map(async(J)=>{try{let Q=await Lz(J);return`${J}:${Q.mtimeMs}:${Q.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:f})}function KY($,f){return $.map((J)=>({...J,enabled:!f.has(J.name)}))}function Nz($){return $.sort((f,J)=>{let Q=f.name.localeCompare(J.name);if(Q!==0)return Q;return f.path.localeCompare(J.path)})}function Tz($,f){if(!$.setup)return[];let J=[],Q={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return $.setup(Q,{workspaceInfo:f}),J}async function aJ($){let f=v1({workspacePath:$.workspacePath,cwd:$.cwd}),J=$$($.disabledToolNames);if(f.length===0)return{tools:[],failures:[],warnings:[]};let Q=await _z({pluginPaths:f,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),Z=V8.get(Q);if(Z)return{tools:KY(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let W=[],j=[],X=[],H;try{H=await of({pluginPaths:f,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),j=[...H.failures],X=[...H.warnings];for(let A of H.extensions??[]){let B=A.__clinePluginPath;if(!B)continue;for(let G of Tz(A,{rootPath:$.workspacePath}))W.push({name:G.name,pluginName:A.name,path:B,source:B.startsWith($.workspacePath)?"workspace-plugin":"global-plugin",description:G.description?.trim()||void 0})}}catch(A){j=f.map((B)=>({pluginPath:B,phase:"load",message:A instanceof Error?A.message:String(A),stack:A instanceof Error?A.stack:void 0}))}finally{await H?.shutdown().catch(()=>{})}let Y=Nz(W);return zz(Q,{tools:Y,failures:j,warnings:X}),{tools:KY(Y,J),failures:j,warnings:X}}async function U6($){return(await aJ($)).tools}function sJ($,f){if(!f)return"global";let J=qz(f,$);return!J.startsWith("..")&&!Mz(J)?"workspace":"global"}function D6($){return[...$].sort((f,J)=>{let Q=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(f.source!==J.source)return Q(f.source)-Q(J.source);return f.name.localeCompare(J.name)})}function DY($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function UY($,f){if($.userInstructionService)return await f($.userInstructionService);let J=DY($);if(!J)return await f(void 0);let Q=Y1({skills:{workspacePath:J},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Q.start(),await f(Q)}finally{Q.stop()}}function yz($,f){if(!$)return;let J=$.listRecords("skill");if(f.id){let Q=J.find((Z)=>Z.id===f.id);if(Q)return Q}for(let Q of J)if(Q.filePath===f.path||Q.item.name===f.name||Q.id===f.name)return Q;return}class V1{async list($={}){return await UY($,async(f)=>{let J=DY($),Q=[],Z=[],W=[],j=[],X=[];if(f){for(let Y of f.listRecords("workflow")){let V=Y.item;Q.push({id:Y.id,name:V.name,path:Y.filePath,enabled:V.disabled!==!0,kind:"workflow",source:sJ(Y.filePath,J),description:V.instructions,toggleable:!1})}for(let Y of f.listRecords("rule")){let V=Y.item;Z.push({id:Y.id,name:V.name,path:Y.filePath,enabled:V.disabled!==!0,kind:"rule",source:sJ(Y.filePath,J),description:V.instructions,toggleable:!1})}for(let Y of f.listRecords("skill")){let V=Y.item;W.push({id:Y.id,name:V.name,path:Y.filePath,enabled:V.disabled!==!0,kind:"skill",source:sJ(Y.filePath,J),description:V.description,toggleable:!0})}}if(J)try{for(let Y of await U6({workspacePath:J,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${Y.pluginName}:${Y.name}:${Y.path}`,name:Y.name,path:Y.path,enabled:Y.enabled,kind:"tool",source:Y.source,description:Y.description,toggleable:!0})}catch{}let H=_0();if(w$({filePath:H}))try{for(let Y of W$({filePath:H}))X.push({id:Y.name,name:Y.name,path:H,enabled:Y.disabled!==!0,kind:"mcp",source:sJ(H,J),description:Y.transport.type,toggleable:!0})}catch{}return{workflows:D6(Q.filter((Y)=>tJ(Y.path))),rules:D6(Z.filter((Y)=>tJ(Y.path))),skills:D6(W.filter((Y)=>tJ(Y.path))),tools:D6(j),mcp:D6(X.filter((Y)=>tJ(Y.path)))}})}async toggle($){if($.type==="skills")return await UY($,async(f)=>{let J=yz(f,$),Q=J?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${$.id??$.name??PY($.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,W=$.enabled??(Z!==void 0?!Z:void 0);if(W===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??PY($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await aH({filePath:Q,enabled:W}),await f?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:f}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)Pf($.name);else b3($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let f=$.name?.trim()||$.id?.trim();if(!f)throw Error("MCP server settings toggle requires a server name.");let J=$.path?.trim()||_0(),Q=$.enabled;if(Q===void 0){let Z=W$({filePath:J}).find((W)=>W.name===f);if(!Z)throw Error(`Unknown MCP server: ${f}`);Q=Z.disabled===!0}return a1({filePath:J,name:f,disabled:!Q}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function $2(){return new V1}function LY($){return{async list(f){let J=$;if(J.listSettings)return await J.listSettings(f);return await $2().list(f)},async toggle(f){let J=$;if(J.toggleSetting)return await J.toggleSetting(f);return await $2().toggle(f)}}}function OY($){function f(){let J=$.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return f().list(J)},update(J){return f().update(J)},delete(J){return f().delete(J)}}}var zY={};y(zY,{splitCoreSessionConfig:()=>R6});function R6($){let{hooks:f,logger:J,telemetry:Q,extensionContext:Z,extraTools:W,extensions:j,onTeamEvent:X,onConsecutiveMistakeLimitReached:H,checkpoint:Y,compaction:V,...A}=$,B={};if(f)B.hooks=f;if(J)B.logger=J;if(Q)B.telemetry=Q;if(Z)B.extensionContext=Z;if(W)B.extraTools=W;if(j)B.extensions=j;if(X)B.onTeamEvent=X;if(H)B.onConsecutiveMistakeLimitReached=H;if(Y?.createCheckpoint)B.checkpoint=Y;if(V?.compact)B.compaction=V;let G=Object.keys(B).length>0?B:void 0;return{config:{...A,...Y?{checkpoint:{enabled:Y.enabled}}:{},...V?{compaction:{enabled:V.enabled,strategy:V.strategy,thresholdRatio:V.thresholdRatio,reserveTokens:V.reserveTokens,preserveRecentTokens:V.preserveRecentTokens,maxInputTokens:V.maxInputTokens,summarizer:V.summarizer}}:{}},...G?{localRuntime:G}:{}}}function _Y($){let f=$.config;return"providerId"in f?{...$,config:{...f,...wz($.localRuntime)},localRuntime:$.localRuntime}:$}function BQ($,f={}){let J=R6($.config),Q=D0(f.defaultCapabilities,$.capabilities),Z=Sz(J.localRuntime,$.localRuntime),W=f.withExtensionContext?.(Z?.extensionContext);if(W)Z={...Z??{},extensionContext:W};return{...$,...J,...Z?{localRuntime:Z}:{},...Q?{capabilities:Q}:{}}}function wz($){if(!$)return{};let{modelCatalogDefaults:f,userInstructionService:J,configExtensions:Q,onTeamRestored:Z,...W}=$;return W}function Sz(...$){let f={};for(let J of $)if(J)Object.assign(f,J);return Object.keys(f).length>0?f:void 0}L0();function NY($){let f=$.input.config.telemetry??$.telemetry;if(!f)return;f.capture({event:x.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??F0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function L6($){return!!$&&typeof $==="object"&&!Array.isArray($)}function GQ($){let f=$?.trim();return f?f:void 0}function hz($,f){let J=$?.trim();if(!J)return f;let Q=Date.parse(J);if(!Number.isFinite(Q))return f;return new Date(Q).toISOString()}function TY($,f){return new Date(new Date($).getTime()+Math.max(0,Math.floor(f))*1000).toISOString()}function MY($,f){return new Date(new Date($).getTime()-Math.max(0,Math.floor(f))*1000).toISOString()}function Cz($,f){if(!$)return f;return new Date($).getTime()>=new Date(f).getTime()?$:f}function Ez($,f){let J=$.eventId.trim(),Q=$.eventType.trim(),Z=$.source.trim(),W=GQ($.subject),j=GQ($.dedupeKey)??`${Q}:${Z}:${W??J}`;return{eventId:J,eventType:Q,source:Z,subject:W,occurredAt:hz($.occurredAt,f),workspaceRoot:GQ($.workspaceRoot),payload:L6($.payload)?$.payload:void 0,attributes:L6($.attributes)?$.attributes:void 0,dedupeKey:j}}function KQ($,f){if(!f)return;let J=f.split("."),Q=$;for(let Z of J){if(!L6(Q))return;Q=Q[Z]}return Q}function bz($,f){if($.attributes&&Object.hasOwn($.attributes,f))return $.attributes[f];if($.payload&&Object.hasOwn($.payload,f))return $.payload[f];let J={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Q=KQ(J,f);if(Q!==void 0)return Q;if($.attributes){let Z=KQ($.attributes,f);if(Z!==void 0)return Z}if($.payload)return KQ($.payload,f);return}function oJ($,f){if(Array.isArray(f))return f.some((J)=>oJ($,J));if(Array.isArray($))return $.some((J)=>oJ(J,f));if(L6(f)){if(!L6($))return!1;return Object.entries(f).every(([J,Q])=>oJ($[J],Q))}return Object.is($,f)}function kz($,f){if(!f||Object.keys(f).length===0)return!0;return Object.entries(f).every(([J,Q])=>oJ(bz($,J),Q))}class FQ{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let f=new Date(this.nowFn()).toISOString(),J=Ez($,f),Q=this.store.insertEventLog(J,{receivedAtIso:f});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let Z=this.store.listEventSpecsForType(J.eventType),W=[],j=[],X=[];for(let V of Z){if(!kz(J,V.filters)){W.push({specId:V.specId,externalId:V.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(V);let A=this.materializeForSpec(V,J,Q.record.receivedAt);if(A.run)X.push(A.run);else W.push({specId:V.specId,externalId:V.externalId,reason:A.reason,dedupeKey:J.dedupeKey})}let H=j.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:H,matchedSpecCount:j.length,queuedRunCount:X.length,suppressedCount:W.filter((V)=>V.reason!=="filter_mismatch").length});let Y=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:H,matchedSpecCount:j.length,queuedRunCount:X.length}),{event:Y??Q.record,duplicate:!1,matchedSpecs:j,queuedRuns:X,suppressions:W}}catch(Z){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:Z});throw Z}}materializeForSpec($,f,J){let Q=f.dedupeKey??f.eventId,Z=$.debounceSeconds??0;if(Z>0){let H=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Q});if(H){let Y=Cz(H.scheduledFor,TY(J,Z)),V=this.store.updateQueuedEventRunForDebounce({runId:H.runId,triggerEventId:f.eventId,scheduledFor:Y});if(V)return{run:V,reason:"dedupe_window"}}}let W=$.dedupeWindowSeconds??0;if(W>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Q,sinceIso:MY(J,W)}))return{reason:"dedupe_window"};let j=$.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:MY(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:f.eventId,scheduledFor:Z>0?TY(J,Z):J}),reason:"dedupe_window"}}}import{existsSync as sz,readdirSync as oz,readFileSync as ez,statSync as $_}from"node:fs";import{relative as f_}from"node:path";import{resolveCronSpecsDir as J_}from"@cline/shared/storage";import{createHash as Iz}from"node:crypto";import xz from"yaml";function mz($){let f=$.replace(/\\/g,"/");if(f.startsWith("events/")&&f.endsWith(".event.md"))return"event";if(f.endsWith(".cron.md"))return"schedule";return"one_off"}function gz($){let f=$.replace(/\r\n/g,`
|
|
474
|
+
`);if(J<0)break;let Z=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!Z)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let Q=Number.parseInt(Z[1],10),j=J+4,H=j+Q;if(this.buffer.length<H)break;f.push(this.buffer.slice(j,H)),this.buffer=this.buffer.slice(H)}return f}}class v9{buffer="";decoder=new $A("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`
|
|
475
|
+
`);if(J<0)break;let W=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),W.length>0)f.push(W)}return f}}class fA{registration;process;nextRequestId=1;pending=new Map;framedParser=new g9;newlineParser=new v9;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],f;for(let J of $){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:Tz,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},Mz),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(W){f=W instanceof Error?W:Error(String(W))}}throw f??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((f)=>typeof f?.name==="string"&&typeof f.inputSchema==="object"&&f.inputSchema!==null).map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let f=this.registration.transport;if(f.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${f.type}`);this.framedParser=new g9,this.newlineParser=new v9,this.stderrBuffer="",this.protocolMode=$;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=_z(f.command,f.args??[],{cwd:f.cwd,env:{...process.env,...f.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=W,W.stdout.on("data",(Z)=>this.handleStdout(Z)),W.stderr.on("data",(Z)=>{if(this.process!==W)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),W.once("error",(Z)=>{if(this.process!==W)return;this.failAllPending(Error(`MCP process error: ${G5(Z)}`))}),W.once("exit",(Z,Q)=>{if(this.process!==W)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${Q??"null"}).${j}`))})}handleStdout($){try{let f=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let J of f){let W=JSON.parse(J);if(typeof W.id!=="number")continue;let Z=this.pending.get(W.id);if(!Z)continue;if(this.pending.delete(W.id),clearTimeout(Z.timeout),W.error){let Q=W.error.message||`MCP request failed with code ${W.error.code??"unknown"}`;Z.reject(Error(Q));continue}Z.resolve(W.result)}}catch(f){this.handleProtocolFailure(f)}}handleProtocolFailure($){let f=this.process;if(!f)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${G5($)}.${J}`)),f.kill()}async request($,f,J=Nz){let W=this.process;if(!W?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,Q={jsonrpc:"2.0",id:Z,method:$,...f?{params:f}:{}},j=new Promise((H,X)=>{let Y=setTimeout(()=>{this.pending.delete(Z),X(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},J);this.pending.set(Z,{resolve:H,reject:X,timeout:Y})});try{W.stdin.write(this.protocolMode==="framed"?oY(Q):eY(Q))}catch(H){let X=this.pending.get(Z);if(X)clearTimeout(X.timeout),this.pending.delete(Z);throw H}return j}notify($,f){let J=this.process;if(!J?.stdin.writable)return;let W={jsonrpc:"2.0",method:$,...f?{params:f}:{}};J.stdin.write(this.protocolMode==="framed"?oY(W):eY(W))}failAllPending($){for(let[f,J]of this.pending)clearTimeout(J.timeout),this.pending.delete(f),J.reject($)}}class JA{registration;options;client;authContext;constructor($,f){this.registration=$;this.options=f}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=B5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??sY});this.authContext=$;try{let f=new zz({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=V5({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await f.connect(J),await $.clearError(),this.client=f}catch(f){let J=f instanceof tY?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):G5(f);throw await $.markError(J),Error(J)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema&&typeof J.inputSchema==="object"&&!Array.isArray(J.inputSchema)?J.inputSchema:{}}))}catch(f){return await this.handleOperationError(f)}}async callTool($){let f=await this.ensureConnectedClient();try{return await f.callTool({name:$.name,arguments:$.arguments??{}})}catch(J){return await this.handleOperationError(J)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let f=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${f} Run authorizeMcpServerOAuth for this server.`;return`${f} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let f=this.authContext??B5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??sY}),J=$ instanceof tY?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):G5($);throw await f.markError(J),Error(J)}}function O2($={}){return(f)=>f.transport.type==="stdio"?new fA(f):new JA(f,$)}A5();function u0(){return Date.now()}function yz($){return $.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}class Vf{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let f=this.servers.get($.name);if(!f){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:u0()});return}let J=JSON.stringify(f.registration.transport)!==JSON.stringify($.transport);if(f.registration={...$},f.updatedAt=u0(),J)await this.disconnectState(f),f.client=void 0,f.toolCache=void 0,f.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.connectState(f)})}async disconnectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f)})}async setServerDisabled($,f){await this.runExclusive($,async()=>{let J=this.requireServer($);if(J.registration={...J.registration,disabled:f},J.updatedAt=u0(),f)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,f)=>$.name.localeCompare(f.name))}async listTools($){let f=this.requireServer($),J=f.toolCacheUpdatedAt??0;if(f.toolCache&&u0()-J<=this.toolsCacheTtlMs)return f.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let f=this.requireServer($),W=await(await this.ensureConnectedClient(f)).listTools(),Z=yz(W);return f.toolCache=Z,f.toolCacheUpdatedAt=u0(),f.updatedAt=u0(),Z})}async callTool($){return this.runExclusive($.serverName,async()=>{let f=this.requireServer($.serverName),J=await this.ensureConnectedClient(f);return f.updatedAt=u0(),J.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let f of $)await this.unregisterServer(f)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=u0();try{let f=$.client??await this.clientFactory($.registration);await f.connect(),$.client=f,$.status="connected",$.lastError=void 0,$.updatedAt=u0()}catch(f){throw $.status="disconnected",$.lastError=f instanceof Error?f.message:String(f),$.updatedAt=u0(),f}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=u0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=u0()}}requireServer($){let f=this.servers.get($);if(!f)throw Error(`Unknown MCP server: ${$}`);return f}async runExclusive($,f){let J=this.operationLocks.get($)??Promise.resolve(),W,Z=new Promise((j)=>{W=j}),Q=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set($,Q),await J.catch(()=>{return});try{return await f()}finally{if(W?.(),this.operationLocks.get($)===Q)this.operationLocks.delete($)}}}import{createHash as qz}from"node:crypto";var WA=128,wz=/[^a-zA-Z0-9_-]+/g,ZA=8,Sz=1,hz="mcp_tool";function Cz($){return qz("sha1").update($).digest("hex").slice(0,ZA)}function Ez($){return $.replace(wz,"_")}var P5=({serverName:$,toolName:f})=>{let J=`${$}__${f}`,W=Ez(J);if(W===J&&J.length<=WA)return J;let Z=Cz(J),Q=WA-Sz-ZA;return`${W.slice(0,Q)||hz}_${Z}`};function kJ($){return{[($.nameTransform??P5)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function F5($){let f={};for(let J of $.toolNames)Object.assign(f,kJ({serverName:$.serverName,toolName:J,nameTransform:$.nameTransform}));return f}import{createTool as bz}from"@cline/shared";function kz($,f){let J=f.description?.trim();if(J)return J;return`Execute MCP tool "${f.name}" from server "${$}".`}async function _2($){let f=await $.provider.listTools($.serverName),J=$.nameTransform??P5;return f.map((W)=>{let Z=J({serverName:$.serverName,toolName:W.name});return bz({name:Z,description:kz($.serverName,W),inputSchema:W.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(Q,j)=>$.provider.callTool({serverName:$.serverName,toolName:W.name,arguments:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:void 0,context:j})})})}Z$();var HA={};w(HA,{listPluginToolsWithDiagnostics:()=>U5,listPluginTools:()=>IJ});import{stat as Iz}from"node:fs/promises";Z$();var xz=32,z2=new Map;function mz($,f){if(!z2.has($)&&z2.size>=xz){let J=z2.keys().next().value;if(J)z2.delete(J)}z2.set($,f)}async function gz($){let f=await Promise.all($.pluginPaths.map(async(J)=>{try{let W=await Iz(J);return`${J}:${W.mtimeMs}:${W.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:f})}function jA($,f){return $.map((J)=>({...J,enabled:!f.has(J.name)}))}function vz($){return $.sort((f,J)=>{let W=f.name.localeCompare(J.name);if(W!==0)return W;return f.path.localeCompare(J.path)})}function uz($,f){if(!$.setup)return[];let J=[],W={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return $.setup(W,{workspaceInfo:f}),J}async function U5($){let f=o1({workspacePath:$.workspacePath,cwd:$.cwd}),J=W$($.disabledToolNames);if(f.length===0)return{tools:[],failures:[],warnings:[]};let W=await gz({pluginPaths:f,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),Z=z2.get(W);if(Z)return{tools:jA(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let Q=[],j=[],H=[],X;try{X=await P6({pluginPaths:f,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),j=[...X.failures],H=[...X.warnings];for(let V of X.extensions??[]){let B=V.__clinePluginPath;if(!B)continue;for(let K of uz(V,{rootPath:$.workspacePath}))Q.push({name:K.name,pluginName:V.name,path:B,source:B.startsWith($.workspacePath)?"workspace-plugin":"global-plugin",description:K.description?.trim()||void 0})}}catch(V){j=f.map((B)=>({pluginPath:B,phase:"load",message:V instanceof Error?V.message:String(V),stack:V instanceof Error?V.stack:void 0}))}finally{await X?.shutdown().catch(()=>{})}let Y=vz(Q);return mz(W,{tools:Y,failures:j,warnings:H}),{tools:jA(Y,J),failures:j,warnings:H}}async function IJ($){return(await U5($)).tools}function D5($,f){if(!f)return"global";let J=dz(f,$);return!J.startsWith("..")&&!cz(J)?"workspace":"global"}function xJ($){return[...$].sort((f,J)=>{let W=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(f.source!==J.source)return W(f.source)-W(J.source);return f.name.localeCompare(J.name)})}function AA($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function YA($,f){if($.userInstructionService)return await f($.userInstructionService);let J=AA($);if(!J)return await f(void 0);let W=$.cwd?.trim()||J,Z=F1({skills:{workspacePath:J,includePluginSkills:!0,cwd:W},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Z.start(),await f(Z)}finally{Z.stop()}}function lz($,f){if(!$)return;let J=$.listRecords("skill");if(f.id){let W=J.find((Z)=>Z.id===f.id);if(W)return W}for(let W of J)if(W.filePath===f.path||W.item.name===f.name||W.id===f.name)return W;return}class U1{async list($={}){return await YA($,async(f)=>{let J=AA($),W=[],Z=[],Q=[],j=[],H=[];if(f){for(let Y of f.listRecords("workflow")){let A=Y.item;W.push({id:Y.id,name:A.name,path:Y.filePath,enabled:A.disabled!==!0,kind:"workflow",source:D5(Y.filePath,J),description:A.instructions,toggleable:!1})}for(let Y of f.listRecords("rule")){let A=Y.item;Z.push({id:Y.id,name:A.name,path:Y.filePath,enabled:A.disabled!==!0,kind:"rule",source:D5(Y.filePath,J),description:A.instructions,toggleable:!1})}for(let Y of f.listRecords("skill")){let A=Y.item;Q.push({id:Y.id,name:A.name,path:Y.filePath,enabled:A.disabled!==!0,kind:"skill",source:D5(Y.filePath,J),description:A.description,toggleable:!0})}}if(J)try{for(let Y of await IJ({workspacePath:J,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${Y.pluginName}:${Y.name}:${Y.path}`,name:Y.name,path:Y.path,enabled:Y.enabled,kind:"tool",source:Y.source,description:Y.description,toggleable:!0})}catch{}let X=z0();if(x$({filePath:X}))try{for(let Y of A$({filePath:X}))H.push({id:Y.name,name:Y.name,path:X,enabled:Y.disabled!==!0,kind:"mcp",source:D5(X,J),description:Y.transport.type,toggleable:!0})}catch{}return{workflows:xJ(W.filter((Y)=>R5(Y.path))),rules:xJ(Z.filter((Y)=>R5(Y.path))),skills:xJ(Q.filter((Y)=>R5(Y.path))),tools:xJ(j),mcp:xJ(H.filter((Y)=>R5(Y.path)))}})}async toggle($){if($.type==="skills")return await YA($,async(f)=>{let J=lz(f,$),W=J?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${$.id??$.name??XA($.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,Q=$.enabled??(Z!==void 0?!Z:void 0);if(Q===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??XA($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await uY({filePath:W,enabled:Q}),await f?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:f}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)b4($.name);else U3($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let f=$.name?.trim()||$.id?.trim();if(!f)throw Error("MCP server settings toggle requires a server name.");let J=$.path?.trim()||z0(),W=$.enabled;if(W===void 0){let Z=A$({filePath:J}).find((Q)=>Q.name===f);if(!Z)throw Error(`Unknown MCP server: ${f}`);W=Z.disabled===!0}return Hf({filePath:J,name:f,disabled:!W}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function Bf(){return new U1}function BA($){return{async list(f){let J=$;if(J.listSettings)return await J.listSettings(f);return await Bf().list(f)},async toggle(f){let J=$;if(J.toggleSetting)return await J.toggleSetting(f);return await Bf().toggle(f)}}}function KA($){function f(){let J=$.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return f().list(J)},update(J){return f().update(J)},delete(J){return f().delete(J)}}}function GA($){let f=$.config;return"providerId"in f?{...$,config:{...f,...pz($.localRuntime)},localRuntime:$.localRuntime}:$}function u9($,f={}){let J=X8($.config),W=R0(f.defaultCapabilities,$.capabilities),Z=rz(J.localRuntime,$.localRuntime),Q=f.withExtensionContext?.(Z?.extensionContext);if(Q)Z={...Z??{},extensionContext:Q};return{...$,...J,...Z?{localRuntime:Z}:{},...W?{capabilities:W}:{}}}function pz($){if(!$)return{};let{modelCatalogDefaults:f,userInstructionService:J,configExtensions:W,onTeamRestored:Z,...Q}=$;return Q}function rz(...$){let f={};for(let J of $)if(J)Object.assign(f,J);return Object.keys(f).length>0?f:void 0}L0();function PA($){let f=$.input.config.telemetry??$.telemetry;if(!f)return;f.capture({event:x.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??P0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function mJ($){return!!$&&typeof $==="object"&&!Array.isArray($)}function c9($){let f=$?.trim();return f?f:void 0}function iz($,f){let J=$?.trim();if(!J)return f;let W=Date.parse(J);if(!Number.isFinite(W))return f;return new Date(W).toISOString()}function FA($,f){return new Date(new Date($).getTime()+Math.max(0,Math.floor(f))*1000).toISOString()}function UA($,f){return new Date(new Date($).getTime()-Math.max(0,Math.floor(f))*1000).toISOString()}function nz($,f){if(!$)return f;return new Date($).getTime()>=new Date(f).getTime()?$:f}function az($,f){let J=$.eventId.trim(),W=$.eventType.trim(),Z=$.source.trim(),Q=c9($.subject),j=c9($.dedupeKey)??`${W}:${Z}:${Q??J}`;return{eventId:J,eventType:W,source:Z,subject:Q,occurredAt:iz($.occurredAt,f),workspaceRoot:c9($.workspaceRoot),payload:mJ($.payload)?$.payload:void 0,attributes:mJ($.attributes)?$.attributes:void 0,dedupeKey:j}}function d9($,f){if(!f)return;let J=f.split("."),W=$;for(let Z of J){if(!mJ(W))return;W=W[Z]}return W}function tz($,f){if($.attributes&&Object.hasOwn($.attributes,f))return $.attributes[f];if($.payload&&Object.hasOwn($.payload,f))return $.payload[f];let J={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},W=d9(J,f);if(W!==void 0)return W;if($.attributes){let Z=d9($.attributes,f);if(Z!==void 0)return Z}if($.payload)return d9($.payload,f);return}function L5($,f){if(Array.isArray(f))return f.some((J)=>L5($,J));if(Array.isArray($))return $.some((J)=>L5(J,f));if(mJ(f)){if(!mJ($))return!1;return Object.entries(f).every(([J,W])=>L5($[J],W))}return Object.is($,f)}function sz($,f){if(!f||Object.keys(f).length===0)return!0;return Object.entries(f).every(([J,W])=>L5(tz($,J),W))}class l9{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let f=new Date(this.nowFn()).toISOString(),J=az($,f),W=this.store.insertEventLog(J,{receivedAtIso:f});if(!W.created)return this.logger?.debug("cron.event.duplicate",{eventId:W.record.eventId,eventType:W.record.eventType,source:W.record.source}),{event:W.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:W.record.dedupeKey}]};try{let Z=this.store.listEventSpecsForType(J.eventType),Q=[],j=[],H=[];for(let A of Z){if(!sz(J,A.filters)){Q.push({specId:A.specId,externalId:A.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(A);let V=this.materializeForSpec(A,J,W.record.receivedAt);if(V.run)H.push(V.run);else Q.push({specId:A.specId,externalId:A.externalId,reason:V.reason,dedupeKey:J.dedupeKey})}let X=j.length===0?"unmatched":H.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(W.record.eventId,{status:X,matchedSpecCount:j.length,queuedRunCount:H.length,suppressedCount:Q.filter((A)=>A.reason!=="filter_mismatch").length});let Y=this.store.getEventLog(W.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:W.record.eventId,eventType:W.record.eventType,status:X,matchedSpecCount:j.length,queuedRunCount:H.length}),{event:Y??W.record,duplicate:!1,matchedSpecs:j,queuedRuns:H,suppressions:Q}}catch(Z){if(this.store.updateEventLogProcessing(W.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:W.record.eventId,eventType:W.record.eventType,error:Z});throw Z}}materializeForSpec($,f,J){let W=f.dedupeKey??f.eventId,Z=$.debounceSeconds??0;if(Z>0){let X=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:W});if(X){let Y=nz(X.scheduledFor,FA(J,Z)),A=this.store.updateQueuedEventRunForDebounce({runId:X.runId,triggerEventId:f.eventId,scheduledFor:Y});if(A)return{run:A,reason:"dedupe_window"}}}let Q=$.dedupeWindowSeconds??0;if(Q>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:W,sinceIso:UA(J,Q)}))return{reason:"dedupe_window"};let j=$.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:UA(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:f.eventId,scheduledFor:Z>0?FA(J,Z):J}),reason:"dedupe_window"}}}import{existsSync as KT,readdirSync as GT,readFileSync as PT,statSync as FT}from"node:fs";import{relative as UT}from"node:path";import{resolveCronSpecsDir as RT}from"@cline/shared/storage";import{createHash as oz}from"node:crypto";import ez from"yaml";function $T($){let f=$.replace(/\\/g,"/");if(f.startsWith("events/")&&f.endsWith(".event.md"))return"event";if(f.endsWith(".cron.md"))return"schedule";return"one_off"}function fT($){let f=$.replace(/\r\n/g,`
|
|
476
476
|
`);if(!f.startsWith(`---
|
|
477
|
-
`))return{frontmatter:void 0,body:$};let J=f.slice(4),
|
|
478
|
-
---`);if(
|
|
479
|
-
`))
|
|
480
|
-
`),J.update(f),J.digest("hex")}function iz($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var nz=["schedule","timezone"],az=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],tz=["cwd"];function qY($,f,J,Q,Z){return{externalId:$,relativePath:$,triggerKind:f,body:J,contentHash:wY(Q,J),error:Z}}function j$($,f,J,Q,Z,W){return{externalId:$,relativePath:f,triggerKind:J,body:Q,contentHash:Z,error:W}}function SY($){let f=$.relativePath.replace(/\\/g,"/"),J=mz(f),{frontmatter:Q,body:Z}=gz($.raw),W={};if(Q!==void 0&&Q.trim().length>0)try{let U=xz.parse(Q);if(U&&typeof U==="object"&&!Array.isArray(U))W=U;else if(U!==null&&U!==void 0)return qY(f,J,Z,{},"frontmatter must be a YAML mapping")}catch(U){return qY(f,J,Z,{},U instanceof Error?`failed to parse frontmatter: ${U.message}`:"failed to parse frontmatter")}let j=wY(W,Z),X=d0(W.id),H=X??f;if(J!=="schedule"){for(let U of nz)if(W[U]!==void 0)return j$(H,f,J,Z,j,`field "${U}" is only allowed on *.cron.md specs`)}for(let U of tz)if(W[U]!==void 0)return j$(H,f,J,Z,j,`field "${U}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let U of az)if(W[U]!==void 0)return j$(H,f,J,Z,j,`field "${U}" is only allowed on .event.md specs`)}let Y=d0(W.prompt),V=Z.trim(),A=Y??(V.length>0?V:void 0);if(!A)return j$(H,f,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let B=d0(W.workspaceRoot);if(!B)return j$(H,f,J,Z,j,"workspaceRoot is required");let G,K;try{G=lz(W.tools),K=rz(W.extensions)}catch(U){return j$(H,f,J,Z,j,U instanceof Error?U.message:String(U))}let D=cz(W.mode);if(W.mode!==void 0&&D===void 0)return j$(H,f,J,Z,j,"mode must be one of: act, plan, yolo");let F={id:X,title:d0(W.title)??X??iz(f),prompt:A,workspaceRoot:B,mode:D??"yolo",systemPrompt:d0(W.systemPrompt),modelSelection:uz(W.modelSelection),maxIterations:PQ(W.maxIterations),timeoutSeconds:PQ(W.timeoutSeconds),tools:G,notesDirectory:d0(W.notesDirectory),extensions:K,source:d0(W.source)??"user",tags:vz(W.tags),enabled:typeof W.enabled==="boolean"?W.enabled:!0,metadata:DQ(W.metadata)},P;if(J==="schedule"){let U=d0(W.schedule);if(!U)return j$(H,f,J,Z,j,"schedule is required for *.cron.md specs");let z=d0(W.timezone);try{P3(U,z)}catch(R){return j$(H,f,J,Z,j,R instanceof Error?R.message:String(R))}P={...F,triggerKind:"schedule",schedule:U,timezone:z}}else if(J==="event"){let U=d0(W.event);if(!U)return j$(H,f,J,Z,j,"event is required for .event.md specs");P={...F,triggerKind:"event",event:U,filters:DQ(W.filters),debounceSeconds:UQ(W.debounceSeconds),dedupeWindowSeconds:UQ(W.dedupeWindowSeconds),cooldownSeconds:UQ(W.cooldownSeconds),maxParallel:PQ(W.maxParallel)}}else P={...F,triggerKind:"one_off"};return{externalId:H,relativePath:f,triggerKind:J,body:Z,contentHash:j,spec:P}}function Q_($,f){return f_($,f).replace(/\\/g,"/")}function Z_($){if(!sz($))return[];let f=[],J=[$];while(J.length>0){let Q=J.pop();if(!Q)continue;let Z;try{Z=oz(Q,{withFileTypes:!0})}catch{continue}for(let W of Z){let j=`${Q}/${W.name}`;if(W.isDirectory()){if(W.name==="reports")continue;J.push(j);continue}if(!W.isFile())continue;if(!W.name.endsWith(".md"))continue;f.push(j)}}return f}class LQ{store;cronDir;constructor($){this.store=$.store,this.cronDir=J_($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},f=Z_(this.cronDir),J=new Set;for(let Z of f){let W=Q_(this.cronDir,Z);J.add(W),$.scanned+=1;let j=await this.reconcileFile(W,Z);if(j){if($.changes.push(j),$.upserted+=1,j.parse.error)$.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of Q)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,f){let J=this.store.getSpecBySourcePath($),Q,Z;try{Q=ez(f,"utf8"),Z=$_(f).mtimeMs}catch{return}let j=SY({relativePath:$,raw:Q}),X=this.store.upsertSpec({externalId:j.externalId,sourcePath:$,triggerKind:j.triggerKind,sourceMtimeMs:Z,sourceHash:j.contentHash,parseStatus:j.error?"invalid":"valid",parseError:j.error,spec:j.spec});if(!j.error&&j.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==X.record.scheduleExpr||J.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:j}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let f of $)this.applyScheduleNextRunAt(f,{forceReset:!1})}applyScheduleNextRunAt($,f){if(!$.scheduleExpr)return;if(!f.forceReset&&$.nextRunAt)return;try{let J=Date.now(),Q=$.lastRunAt?Math.max(J,new Date($.lastRunAt).getTime()):J,Z=R1($.scheduleExpr,Q,$.timezone),W=new Date(Z).toISOString();if($.nextRunAt!==W)this.store.updateSpecNextRunAt($.specId,W)}catch{}}}import{existsSync as W_,mkdirSync as j_,watch as X_}from"node:fs";import{relative as H_,resolve as Y_}from"node:path";var V_=250;class OQ{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??V_),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{j_($,{recursive:!0}),this.watcher=X_($,{recursive:!0},(f,J)=>{if(!J)return;let Q=String(J).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch(f){this.onError(f)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let f=this.pending.get($);if(f)clearTimeout(f);let J=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,J)}async reconcileNow($){try{let f=Y_(this.reconciler.getCronDir(),$);if(!W_(f)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=H_(this.reconciler.getCronDir(),f).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,f),await this.onReconciled()}catch(f){this.onError(f)}}}class O6{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new I8({dbPath:$.dbPath});let f=$.specs;this.reconciler=new LQ({store:this.store,specs:f}),this.materializer=new w8({store:this.store}),this.eventIngress=new FQ({store:this.store,logger:$.logger}),this.runner=new C8({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:f,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new OQ({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:J});else Q.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var gY={};y(gY,{manifestToSessionRecord:()=>$5,listSessionHistoryFromBackend:()=>TQ,listSessionHistory:()=>f5,hydrateSessionHistory:()=>mY});import{readdir as K_,readFile as kY}from"node:fs/promises";import{join as IY}from"node:path";import{formatDisplayUserInput as F_,normalizeUserInput as P_}from"@cline/shared";import{resolveSessionDataDir as xY}from"@cline/shared/storage";import{existsSync as A_}from"node:fs";import{readFile as B_}from"node:fs/promises";import{formatDisplayUserInput as hY}from"@cline/shared";class z6{listeners=new Set;subscribe($,f){let J={listener:$,sessionId:f?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit($){let f=$.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==f)continue;J.listener($)}}get size(){return this.listeners.size}}async function A1($){let f=$?.trim();if(!f||!A_(f))return[];try{let J=(await B_(f,"utf8")).trim();if(!J)return[];let Q=JSON.parse(J);if(Array.isArray(Q))return CY(Q);if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let Z=Q.messages;if(Array.isArray(Z))return CY(Z)}return[]}catch{return[]}}function G_($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:hY($.content)};return{...$,content:$.content.map((f)=>{if(f.type!=="text"||typeof f.text!=="string")return f;return{...f,text:hY(f.text)}})}}function CY($){return $.map(G_)}function zQ($){return $?{...$}:void 0}async function EY($,f){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await f.queueSpawnRequest($);let Q=await f.upsertSubagentSessionFromHook($);if(!Q)return;await f.appendSubagentHookAudit(Q,$),await f.applySubagentStatus(Q,$)}function _6($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function l0($){let f=_6($);if(!f)return;return f.toLowerCase()==="unknown"?void 0:f}function eJ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function U_($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function NQ($){let f=$??200;return Number.isFinite(f)?Math.max(0,Math.floor(f)):200}function D_($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function R_($){return $.isSubagent!==!0&&!_6($.parentSessionId)}function L_($){let f=$.match(/\d{13,}/g);if(!f||f.length===0)return 0;let J=0;for(let Q of f){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function $5($){return{sessionId:$.session_id,source:$.source,pid:$.pid,startedAt:$.started_at,endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspace_root,teamName:$.team_name,enableTools:$.enable_tools,enableSpawn:$.enable_spawn,enableTeams:$.enable_teams,isSubagent:!1,prompt:$.prompt,metadata:$.metadata,messagesPath:$.messages_path,updatedAt:$.ended_at??$.started_at}}async function O_($){let f=NQ($);if(f===0)return[];let J=xY(),Z=(await K_(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:L_(j.name.trim())})).sort((j,X)=>X.recency-j.recency||X.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let X=j.name.trim();if(!X)return;let H=IY(J,X,`${X}.json`),Y=await kY(H,"utf8").catch(()=>{return});if(!Y)return;let V;try{V=JSON.parse(Y)}catch{return}let A=q0.safeParse(V);if(!A.success)return;return $5(A.data)}))).filter((j)=>Boolean(j)).sort((j,X)=>X.startedAt.localeCompare(j.startedAt)).slice(0,f)}async function z_($,f,J){let Q=NQ(f);if(Q===0)return await $.listSessions(0),[];let Z=J.includeSubagents?Q:D_(Q),W=await $.listSessions(Z);return(J.includeSubagents?W:W.filter(R_)).slice(0,Q)}function __($){if(typeof $==="string")return $.trim();let f=[];for(let J of $){if(!J||typeof J!=="object")continue;let Q=J;if(Q.type!=="text")continue;let Z=Q.text?.trim();if(Z)f.push(Z)}return f.join(`
|
|
481
|
-
`).trim()}function
|
|
482
|
-
`)[0]??Z);return N_(W,50)}return}function M_($){let f=0;for(let J of $)f+=eJ(J.metrics?.cost)??0;return f}function q_($){let f,J;for(let Q=$.length-1;Q>=0;Q-=1){let Z=$[Q];if(!f)f=l0(Z.modelInfo?.provider);if(!J)J=l0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function y_($){return l0($?.provider)??l0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function w_($){return l0($?.model)??l0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function _Q($,f){let J=U_($.metadata),Q=_6(f?.title)??_6(J?.title),Z=eJ(f?.totalCost)??eJ(J?.totalCost),W=J||Q!==void 0||Z!==void 0?{...J??{},...Q!==void 0?{title:Q}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:l0(f?.provider)??l0($.provider)??y_(J)??"",model:l0(f?.model)??l0($.model)??w_(J)??"",metadata:W}}function S_($){let f=$.content;if(!Array.isArray(f))return!1;return f.some((J)=>!!J&&typeof J==="object"&&J.type==="tool-call")}function h_($,f){if($.status!=="running"||$.interactive!==!0)return!1;let J=f.at(-1);return J?.role==="assistant"&&!S_(J)}async function C_($,f){return await Promise.all(f.map(async(J)=>{if(J.status!=="running"||J.interactive!==!0)return J;let Q=await $.readSessionMessages(J.sessionId);return h_(J,Q)?{...J,status:"idle"}:J}))}async function mY($,f){return await Promise.all(f.map(async(J)=>{let Q=_Q(J),Z=Boolean(_6(Q.metadata?.title)),W=Boolean(l0(Q.provider)),j=Boolean(l0(Q.model)),X=eJ(Q.metadata?.totalCost),H=X!==void 0&&X>0;if(Z&&W&&j&&H)return Q;let Y=await $.readSessionMessages(J.sessionId);if(Y.length===0)return Q;let V=q_(Y),A=M_(Y);return _Q(J,{title:Z?void 0:T_(Y),provider:W?void 0:V.provider,model:j?void 0:V.model,totalCost:H||A<=0?void 0:A})}))}async function f5($,f={}){let J=NQ(f.limit),Q=f.includeSubagents===!0,Z=await z_($,J,{includeSubagents:Q}),W=f.includeManifestFallback===!0&&Z.length<J?await O_(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let Y of[...Z,...W]){if(j.has(Y.sessionId))continue;j.set(Y.sessionId,Y)}let X=W.length===0?Z:Array.from(j.values()).sort((Y,V)=>V.startedAt.localeCompare(Y.startedAt)).slice(0,J),H=await C_($,X);if(f.hydrate===!1)return H.map((Y)=>_Q(Y));return await mY($,H)}async function E_($){let f=$.trim();if(!f)return;let J=IY(xY(),f,`${f}.json`),Q=await kY(J,"utf8").catch(()=>{return});if(!Q)return;try{let Z=q0.safeParse(JSON.parse(Q));return Z.success?Z.data.messages_path:void 0}catch{return}}async function TQ($,f={}){let J=new Map;return await f5({listSessions:async(Z)=>{let W=await $.listSessions(Z);J.clear();for(let j of W)J.set(j.sessionId,j);return W.map(T4)},readSessionMessages:async(Z)=>{let W=J.get(Z)?.messagesPath??await E_(Z);return await A1(W)}},f)}var OV={};y(OV,{resolveSessionBackend:()=>lQ,createRuntimeHost:()=>U8});import{captureSdkError as RV}from"@cline/shared";var oY={};y(oY,{HubRuntimeHost:()=>S$});import{captureSdkError as uY,createSessionId as cY,HUB_CHECKPOINT_CAPABILITY as x_,HUB_COMPACTION_CAPABILITY as m_,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as g_,HUB_HOOK_CAPABILITY_PREFIX as v_,HUB_MISTAKE_LIMIT_CAPABILITY as u_,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as c_,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as d_,isHubToolExecutorName as l_}from"@cline/shared";var vY={};y(vY,{createCoreSessionSnapshot:()=>X$,coreSessionSnapshotToRecord:()=>J5});function b_($){return $?JSON.parse(JSON.stringify($)):void 0}function k_($){return $?JSON.parse(JSON.stringify($)):void 0}function I_($){let f=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(f?.history)?f.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let X=typeof j.ref==="string"?j.ref.trim():"",H=Number(j.createdAt),Y=Number(j.runCount);if(!X||!Number.isFinite(H)||!Number.isInteger(Y))return[];return[{ref:X,createdAt:H,runCount:Y,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=Q.at(-1),W=$?.checkpointEnabled===!0?!0:void 0;if(!W&&Q.length===0)return;return{...W?{enabled:W}:{},...Z?{latest:Z}:{},history:Q}}function X$($){let{session:f}=$,J=b_(f.metadata);return{version:1,sessionId:f.sessionId,source:f.source,status:f.status,createdAt:f.startedAt,updatedAt:f.updatedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,interactive:f.interactive,workspace:{cwd:f.cwd,root:f.workspaceRoot},model:{providerId:f.provider,modelId:f.model},capabilities:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams},lineage:{...f.parentSessionId?{parentSessionId:f.parentSessionId}:{},...f.parentAgentId?{parentAgentId:f.parentAgentId}:{},...f.agentId?{agentId:f.agentId}:{},...f.conversationId?{conversationId:f.conversationId}:{},isSubagent:f.isSubagent},...f.teamName?{team:{name:f.teamName}}:{},...f.prompt?{prompt:f.prompt}:{},...J?{metadata:J}:{},...f.messagesPath?{artifacts:{messagesPath:f.messagesPath}}:{},...$.messages?{messages:k_($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=I_(J);return Q?{checkpoint:Q}:{}})()}}function J5($){return{sessionId:$.sessionId,parentSessionId:$.lineage.parentSessionId,agentId:$.lineage.agentId,parentAgentId:$.lineage.parentAgentId,conversationId:$.lineage.conversationId,isSubagent:$.lineage.isSubagent,source:$.source,startedAt:$.createdAt,endedAt:$.endedAt??void 0,exitCode:$.exitCode??void 0,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspaceRoot:$.workspace.root,teamName:$.team?.name,enableTools:$.capabilities.enableTools,enableSpawn:$.capabilities.enableSpawn,enableTeams:$.capabilities.enableTeams,prompt:$.prompt,metadata:$.metadata,updatedAt:$.updatedAt,messagesPath:$.artifacts?.messagesPath}}function A8($){if(!$)return;return JSON.parse(JSON.stringify($))}var p_=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function dY($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function lY($){if(!$)return;let{userInstructionService:f,...J}=$;return JSON.parse(JSON.stringify(J))}function pY($){let f=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof f.agentId==="string"?f.agentId:"",conversationId:typeof f.conversationId==="string"?f.conversationId:"",iteration:typeof f.iteration==="number"?f.iteration:0,metadata:f.metadata&&typeof f.metadata==="object"&&!Array.isArray(f.metadata)?f.metadata:void 0}}function f2($,f,J){$.manifest.push(f),$.handlers.set(f.capabilityName,J)}function rY($,f){let J={manifest:[],handlers:new Map};for(let Z of Object.keys(f.toolExecutors??{}).filter(l_)){let W=f.toolExecutors?.[Z];if(typeof W!=="function")continue;f2(J,{kind:"toolExecutor",executor:Z,capabilityName:`${c_}${Z}`},async({payload:j,abortSignal:X})=>{let H=Array.isArray(j.args)?[...j.args]:[],Y={...pY(j.context),signal:X};return{result:await W(...H,Y)}})}for(let Z of $?.extraTools??[])f2(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:A8(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:A8(Z.lifecycle)}:{},capabilityName:`${g_}${Z.name}`},async({payload:W,abortSignal:j,progress:X})=>{let H={...pY(W.context),signal:j};return{result:await Z.execute(W.input,{...H,emitUpdate:(V)=>{X({update:V})}})}});let Q=$?.hooks;if(Q)for(let Z of p_){let W=Q[Z];if(typeof W!=="function")continue;f2(J,{kind:"hook",name:Z,capabilityName:`${v_}${Z}`},async({payload:j})=>({control:await W(j.context)}))}if($?.compaction?.compact){let Z=$.compaction.compact;f2(J,{kind:"compaction",capabilityName:m_,config:dY($.compaction)},async({payload:W})=>({result:await Z(W.context)}))}if($?.checkpoint?.createCheckpoint){let Z=$.checkpoint.createCheckpoint;f2(J,{kind:"checkpoint",capabilityName:x_,config:dY($.checkpoint)},async({payload:W})=>({result:await Z(W.context)}))}if($?.onConsecutiveMistakeLimitReached){let Z=$.onConsecutiveMistakeLimitReached;f2(J,{kind:"mistakeLimit",capabilityName:u_},async({payload:W})=>({result:await Z(W.context)}))}if($?.userInstructionService){let Z=$.userInstructionService;f2(J,{kind:"userInstructionService",capabilityName:d_},async()=>{return await Z.start().catch(()=>{}),{snapshot:{records:{skill:Z.listRecords("skill"),rule:Z.listRecords("rule"),workflow:Z.listRecords("workflow")},runtimeCommands:Z.listRuntimeCommands()}}})}return J}function tY($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let f=$.message;if(typeof f==="string"&&f.trim())return f.trim()}return}function r_($){return tY($)??"Capability request was cancelled."}function i_($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function n_($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function a_($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=typeof f.inputTokens==="number"?f.inputTokens:void 0,Q=typeof f.outputTokens==="number"?f.outputTokens:void 0;if(J===void 0||Q===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function iY($){if(!$)return;return{inputTokens:typeof $.inputTokens==="number"?$.inputTokens:0,outputTokens:typeof $.outputTokens==="number"?$.outputTokens:0,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function MQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function B1($,f){return MQ($?.[f])??0}function t_($){let f=$?.delta&&typeof $.delta==="object"?$.delta:void 0,J=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,Z=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:B1(f,"inputTokens"),outputTokens:B1(f,"outputTokens"),cacheReadTokens:B1(f,"cacheReadTokens"),cacheWriteTokens:B1(f,"cacheWriteTokens"),cost:MQ(f?.totalCost),totalInputTokens:B1(J,"inputTokens"),totalOutputTokens:B1(J,"outputTokens"),totalCacheReadTokens:B1(J,"cacheReadTokens"),totalCacheWriteTokens:B1(J,"cacheWriteTokens"),totalCost:MQ(J?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:Z}}function s_($){let f=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,J=$?.reason??f?.finishReason,Q=n_(J)?J:J==="failed"?"error":"completed",Z=a_($?.usage??f?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof f?.text==="string"?f.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof f?.iterations==="number"?f.iterations:0,usage:Z}}function Q5($,f){return $.error?.message??`hub command failed: ${f}`}function N6($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function sY($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof f?.parentSessionId==="string"?f.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof f?.agentId==="string"?f.agentId:void 0),parentAgentId:typeof f?.parentAgentId==="string"?f.parentAgentId:void 0,conversationId:typeof f?.conversationId==="string"?f.conversationId:void 0,isSubagent:typeof f?.isSubagent==="boolean"?f.isSubagent:!1,source:typeof f?.source==="string"?f.source:F0.CORE,pid:typeof f?.pid==="number"?f.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:N6($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:N6($.status)==="completed"?0:N6($.status)==="failed"?1:void 0,status:N6($.status),interactive:f?.interactive===!0,provider:typeof f?.provider==="string"?f.provider:"hub",model:typeof f?.model==="string"?f.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof f?.teamName==="string"?f.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??f?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??f?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??f?.enableTeams===!0,prompt:typeof f?.prompt==="string"?f.prompt:void 0,metadata:f,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof f?.messagesPath==="string"?f.messagesPath:void 0,hookPath:typeof f?.hookPath==="string"?f.hookPath:void 0}}function G1($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;return f.version===1&&typeof f.sessionId==="string"?JSON.parse(JSON.stringify(f)):void 0}function o_($){let f=G1($?.snapshot);if(f)return J5(f);let J=$?.session;return J?sY(J):void 0}function nY($,f,J){let Q=J?.workspaceRoot?.trim()||f.config.workspaceRoot||f.config.cwd;return q0.parse({version:1,session_id:$,source:f.source??F0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:N6(J?.status),interactive:f.interactive===!0,provider:f.config.providerId,model:f.config.modelId,cwd:J?.cwd?.trim()||f.config.cwd,workspace_root:Q,team_name:f.config.teamName,enable_tools:f.config.enableTools,enable_spawn:f.config.enableSpawnAgent,enable_teams:f.config.enableAgentTeams,prompt:f.prompt?.trim()||void 0,metadata:f.sessionMetadata&&Object.keys(f.sessionMetadata).length>0?f.sessionMetadata:void 0})}function aY($,f){return q0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??f.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class S${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new z6;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,f){this.clientContext=f,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd},this.defaultCapabilities=D0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient($.url)}createClient($){return new a0({...this.clientOptions,url:$})}async replaceClient($){let f=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(f.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!Tf($,"session.create"))return!1;let f=await Mf({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!f)return!1;return await this.replaceClient(f),!0}registerPlannedSession($,f,J){if(this.sessionCapabilities.set($,f),J.size>0)this.sessionClientContributionHandlers.set($,J);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let f=this.resolveCapabilities($),J=rY($.localRuntime,f),Q=$.config.sessionId?.trim()||cY(),Z=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:A8({...$.config,sessionId:Q}),metadata:{...$.sessionMetadata??{},source:$.source??F0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:A8($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Q,f,J.handlers);let W;try{W=await Z()}catch(Y){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(Y)){this.registerPlannedSession(Q,f,J.handlers);try{W=await Z()}catch(V){throw this.cleanupPlannedSession(Q),V}}else throw Y}let j=G1(W.payload?.snapshot),X=W.payload?.session,H=(j?.sessionId??X?.sessionId)?.trim();if(!H)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(H!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(H,f,J.handlers);return{sessionId:H,manifest:j?aY(j,$):nY(H,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,Z=Q?this.resolveCapabilities(Q):void 0,W=Q?rY(Q.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=Q?Q.config.sessionId?.trim()||cY():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&W.handlers.size>0)this.sessionClientContributionHandlers.set(j,W.handlers),this.ensureSessionSubscription(j);let X;try{X=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:A8({...Q.config,sessionId:j}),metadata:{...Q.sessionMetadata??{},source:Q.source??F0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...W.manifest.length>0?{clientContributions:W.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:A8(Q.toolPolicies)}:{}},f)}catch(G){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw G}if(!X.ok){let G=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(G)}let H=G1(X.payload?.snapshot),Y=X.payload?.session,V=(H?.sessionId??Y?.sessionId)?.trim();if(J&&!V){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(V&&j&&V!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(V&&Z)this.sessionCapabilities.set(V,Z);if(V&&W.handlers.size>0)this.sessionClientContributionHandlers.set(V,W.handlers);if(V)this.ensureSessionSubscription(V);let A=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,B=X.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:V,startResult:V?{sessionId:V,manifest:H?aY(H,Q??{}):nY(V,Q??{},Y),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:A,checkpoint:B}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,updated:f.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,removed:f.payload?.removed===!0}}async getAccumulatedUsage($){let f=await this.client.command("session.get",{includeSnapshot:!0},$),J=G1(f.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,X=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||X?{usage:j,aggregateUsage:X}:void 0}let Q=f.payload?.session,Z=iY(Q?.usage),W=iY(Q?.aggregateUsage);return Z||W?{usage:Z,aggregateUsage:W}:void 0}async abort($,f){await this.client.command("run.abort",{sessionId:$,reason:tY(f)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,f]of this.sessionSubscriptions){f();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let f=await this.client.command("session.get",void 0,$);return o_(f.payload)}async listSessions($=100){let f=await this.client.command("session.list",{limit:$}),J=Array.isArray(f.payload?.snapshots)?f.payload.snapshots.flatMap((Z)=>{let W=G1(Z);return W?[J5(W)]:[]}):[];if(J.length>0)return J;return(f.payload?.sessions??[]).map(sY)}async listSettings($){let f=await this.client.command("settings.list",lY($));if(!f.ok)throw Error(Q5(f,"settings.list"));return f.payload?.snapshot}async toggleSetting($){let f=await this.client.command("settings.toggle",lY($));if(!f.ok)throw Error(Q5(f,"settings.toggle"));return{snapshot:f.payload?.snapshot,changedTypes:Array.isArray(f.payload?.changedTypes)?f.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,f){let J={...f.metadata??{}};if(typeof f.prompt==="string")J.prompt=f.prompt;if(typeof f.title==="string")J.title=f.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:J})).ok}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw uY(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(Q5(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:f,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(Q5(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,f){return this.events.subscribe($,f)}ensureSessionSubscription($){let f=$.trim();if(!f||this.sessionSubscriptions.has(f))return;let J=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:f});this.sessionSubscriptions.set(f,typeof J==="function"?J:()=>{})}disposeSessionSubscription($){let f=$.trim();if(!f)return;this.sessionSubscriptions.get(f)?.(),this.sessionSubscriptions.delete(f),this.agentDoneEmittedForCurrentRunBySession.delete(f)}resolveCapabilities($){return D0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:s_($.payload)}})}handleHubEvent($){let f=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",J,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",J,$)});return}if(!f)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(f);let J=G1($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!J&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:f,payload:$.payload});return}case"usage.updated":{let J=t_($.payload);this.events.emit({type:"agent_event",payload:{sessionId:f,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:f,toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=G1($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:f,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=$.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:f,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=G1($.payload?.snapshot),Q=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:f,payload:{...$.payload,reason:Q}}),J?.interactive===!0&&J0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:f,reason:Q,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,f,J){try{uY(this.telemetry,{component:"core",operation:$,error:f,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let f=$.sessionId?.trim();if(!f)return;let J=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",Z=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let W=this.sessionClientContributionHandlers.get(f)?.get(Z);if(!W){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${f}.`},f).catch(()=>{});return}let j=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Q,X);let H=(Y)=>{this.client.command("capability.progress",{requestId:Q,payload:Y},f).catch((V)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",V,$)})};try{let Y=await W({payload:j,abortSignal:X.signal,progress:H});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:Y},f)}catch(Y){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:Y instanceof Error?Y.message:String(Y)},f)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let f=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!f)return;let J=this.activeCapabilityAbortControllers.get(f);if(!J)return;J.abort(r_($.payload.error))}async handleApprovalRequested($){let f=$.sessionId?.trim();if(!f)return;let J=this.sessionCapabilities.get(f)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",W=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!Z||!W)return;let j=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=i_($.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:f,toolCallId:Z,toolName:W,toolInput:X});let H=await Promise.resolve(J({sessionId:f,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:f,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:Z,toolName:W,input:X,policy:j})).catch((Y)=>({approved:!1,reason:Y instanceof Error?Y.message:`Tool approval request failed: ${String(Y)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:H.approved,reason:H.reason},f).catch(()=>{})}}var eY={};y(eY,{RemoteRuntimeHost:()=>B8});class B8 extends S${constructor($){super({url:d$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var $V={};y($V,{SqliteSessionStore:()=>Y$});import{existsSync as e_,mkdirSync as $N}from"node:fs";import{join as fN}from"node:path";import{asBool as T6,asOptionalString as H$,asString as h$,ensureSessionSchema as JN,loadSqliteDb as QN,nowIso as Z5,toBoolInt as M6}from"@cline/shared/db";import{resolveDbDataDir as ZN}from"@cline/shared/storage";class Y${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??ZN()}init(){this.getRawDb()}ensureSessionsDir(){if(!e_(this.sessionsDirPath))$N(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return fN(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=QN(this.sessionDbPath());return JN($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}create($){let f=Z5();this.run(`INSERT OR REPLACE INTO sessions (
|
|
477
|
+
`))return{frontmatter:void 0,body:$};let J=f.slice(4),W=J.indexOf(`
|
|
478
|
+
---`);if(W===-1)return{frontmatter:void 0,body:$};let Z=J.slice(0,W),Q=J.slice(W+4);if(Q.startsWith(`
|
|
479
|
+
`))Q=Q.slice(1);return{frontmatter:Z,body:Q}}function c0($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function JT($){if(!Array.isArray($))return;let f=$.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return f.length>0?f:void 0}function i9($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function WT($){let f=i9($);if(!f)return;let J=c0(f.providerId),W=c0(f.modelId);if(J===void 0&&W===void 0)return;return{providerId:J,modelId:W}}function ZT($){if(typeof $!=="string")return;let f=$.trim().toLowerCase();if(f==="act"||f==="plan"||f==="yolo")return f;return}function DA($,f={}){let J=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!J)return;let W=[...new Set(J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0))];if(Array.isArray($)&&f.preserveEmptyArray)return W;return W.length>0?W:void 0}var QT=new Set(l$);function jT($){let f=DA($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((W)=>!QT.has(W));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return f}var HT=new Set(["rules","skills","plugins"]);function XT($){let f=DA($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((W)=>!HT.has(W));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return f}function p9($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function r9($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function n9($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((J)=>n9(J)).join(",")}]`;let f=Object.entries($).filter(([,J])=>J!==void 0);return f.sort(([J],[W])=>J<W?-1:J>W?1:0),`{${f.map(([J,W])=>`${JSON.stringify(J)}:${n9(W)}`).join(",")}}`}function LA($,f){let J=oz("sha256");return J.update(n9($)),J.update(`
|
|
480
|
+
`),J.update(f),J.digest("hex")}function YT($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var AT=["schedule","timezone"],VT=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],BT=["cwd"];function RA($,f,J,W,Z){return{externalId:$,relativePath:$,triggerKind:f,body:J,contentHash:LA(W,J),error:Z}}function V$($,f,J,W,Z,Q){return{externalId:$,relativePath:f,triggerKind:J,body:W,contentHash:Z,error:Q}}function OA($){let f=$.relativePath.replace(/\\/g,"/"),J=$T(f),{frontmatter:W,body:Z}=fT($.raw),Q={};if(W!==void 0&&W.trim().length>0)try{let U=ez.parse(W);if(U&&typeof U==="object"&&!Array.isArray(U))Q=U;else if(U!==null&&U!==void 0)return RA(f,J,Z,{},"frontmatter must be a YAML mapping")}catch(U){return RA(f,J,Z,{},U instanceof Error?`failed to parse frontmatter: ${U.message}`:"failed to parse frontmatter")}let j=LA(Q,Z),H=c0(Q.id),X=H??f;if(J!=="schedule"){for(let U of AT)if(Q[U]!==void 0)return V$(X,f,J,Z,j,`field "${U}" is only allowed on *.cron.md specs`)}for(let U of BT)if(Q[U]!==void 0)return V$(X,f,J,Z,j,`field "${U}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let U of VT)if(Q[U]!==void 0)return V$(X,f,J,Z,j,`field "${U}" is only allowed on .event.md specs`)}let Y=c0(Q.prompt),A=Z.trim(),V=Y??(A.length>0?A:void 0);if(!V)return V$(X,f,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let B=c0(Q.workspaceRoot);if(!B)return V$(X,f,J,Z,j,"workspaceRoot is required");let K,G;try{K=jT(Q.tools),G=XT(Q.extensions)}catch(U){return V$(X,f,J,Z,j,U instanceof Error?U.message:String(U))}let R=ZT(Q.mode);if(Q.mode!==void 0&&R===void 0)return V$(X,f,J,Z,j,"mode must be one of: act, plan, yolo");let P={id:H,title:c0(Q.title)??H??YT(f),prompt:V,workspaceRoot:B,mode:R??"yolo",systemPrompt:c0(Q.systemPrompt),modelSelection:WT(Q.modelSelection),maxIterations:p9(Q.maxIterations),timeoutSeconds:p9(Q.timeoutSeconds),tools:K,notesDirectory:c0(Q.notesDirectory),extensions:G,source:c0(Q.source)??"user",tags:JT(Q.tags),enabled:typeof Q.enabled==="boolean"?Q.enabled:!0,metadata:i9(Q.metadata)},F;if(J==="schedule"){let U=c0(Q.schedule);if(!U)return V$(X,f,J,Z,j,"schedule is required for *.cron.md specs");let _=c0(Q.timezone);try{e7(U,_)}catch(D){return V$(X,f,J,Z,j,D instanceof Error?D.message:String(D))}F={...P,triggerKind:"schedule",schedule:U,timezone:_}}else if(J==="event"){let U=c0(Q.event);if(!U)return V$(X,f,J,Z,j,"event is required for .event.md specs");F={...P,triggerKind:"event",event:U,filters:i9(Q.filters),debounceSeconds:r9(Q.debounceSeconds),dedupeWindowSeconds:r9(Q.dedupeWindowSeconds),cooldownSeconds:r9(Q.cooldownSeconds),maxParallel:p9(Q.maxParallel)}}else F={...P,triggerKind:"one_off"};return{externalId:X,relativePath:f,triggerKind:J,body:Z,contentHash:j,spec:F}}function DT($,f){return UT($,f).replace(/\\/g,"/")}function LT($){if(!KT($))return[];let f=[],J=[$];while(J.length>0){let W=J.pop();if(!W)continue;let Z;try{Z=GT(W,{withFileTypes:!0})}catch{continue}for(let Q of Z){let j=`${W}/${Q.name}`;if(Q.isDirectory()){if(Q.name==="reports")continue;J.push(j);continue}if(!Q.isFile())continue;if(!Q.name.endsWith(".md"))continue;f.push(j)}}return f}class a9{store;cronDir;constructor($){this.store=$.store,this.cronDir=RT($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},f=LT(this.cronDir),J=new Set;for(let Z of f){let Q=DT(this.cronDir,Z);J.add(Q),$.scanned+=1;let j=await this.reconcileFile(Q,Z);if(j){if($.changes.push(j),$.upserted+=1,j.parse.error)$.invalidParses+=1}}let W=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of W)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,f){let J=this.store.getSpecBySourcePath($),W,Z;try{W=PT(f,"utf8"),Z=FT(f).mtimeMs}catch{return}let j=OA({relativePath:$,raw:W}),H=this.store.upsertSpec({externalId:j.externalId,sourcePath:$,triggerKind:j.triggerKind,sourceMtimeMs:Z,sourceHash:j.contentHash,parseStatus:j.error?"invalid":"valid",parseError:j.error,spec:j.spec});if(!j.error&&j.triggerKind==="schedule"&&H.record.enabled)this.applyScheduleNextRunAt(H.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==H.record.scheduleExpr||J.timezone!==H.record.timezone});return{relativePath:$,result:H,parse:j}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let f of $)this.applyScheduleNextRunAt(f,{forceReset:!1})}applyScheduleNextRunAt($,f){if(!$.scheduleExpr)return;if(!f.forceReset&&$.nextRunAt)return;try{let J=Date.now(),W=$.lastRunAt?Math.max(J,new Date($.lastRunAt).getTime()):J,Z=q1($.scheduleExpr,W,$.timezone),Q=new Date(Z).toISOString();if($.nextRunAt!==Q)this.store.updateSpecNextRunAt($.specId,Q)}catch{}}}import{existsSync as OT,mkdirSync as _T,watch as zT}from"node:fs";import{relative as TT,resolve as NT}from"node:path";var MT=250;class t9{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??MT),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{_T($,{recursive:!0}),this.watcher=zT($,{recursive:!0},(f,J)=>{if(!J)return;let W=String(J).replace(/\\/g,"/");if(!W.endsWith(".md"))return;if(W.startsWith("reports/"))return;this.scheduleReconcile(W)}),this.watcher.on("error",this.onError)}catch(f){this.onError(f)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let f=this.pending.get($);if(f)clearTimeout(f);let J=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,J)}async reconcileNow($){try{let f=NT(this.reconciler.getCronDir(),$);if(!OT(f)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=TT(this.reconciler.getCronDir(),f).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,f),await this.onReconciled()}catch(f){this.onError(f)}}}class gJ{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new s2({dbPath:$.dbPath});let f=$.specs;this.reconciler=new a9({store:this.store,specs:f}),this.materializer=new l2({store:this.store}),this.eventIngress=new l9({store:this.store,logger:$.logger}),this.runner=new i2({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:f,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new t9({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let W=$.logger;if(W)if(W.error)W.error("cron.watcher.failed",{error:J});else W.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var SA={};w(SA,{manifestToSessionRecord:()=>_5,listSessionHistoryFromBackend:()=>$Q,listSessionHistory:()=>z5,hydrateSessionHistory:()=>wA});import{readdir as ST,readFile as MA}from"node:fs/promises";import{join as yA}from"node:path";import{formatDisplayUserInput as hT,normalizeUserInput as CT}from"@cline/shared";import{resolveSessionDataDir as qA}from"@cline/shared/storage";import{existsSync as yT}from"node:fs";import{readFile as qT}from"node:fs/promises";import{formatDisplayUserInput as _A}from"@cline/shared";class vJ{listeners=new Set;subscribe($,f){let J={listener:$,sessionId:f?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit($){let f=$.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==f)continue;J.listener($)}}get size(){return this.listeners.size}}async function R1($){let f=$?.trim();if(!f||!yT(f))return[];try{let J=(await qT(f,"utf8")).trim();if(!J)return[];let W=JSON.parse(J);if(Array.isArray(W))return zA(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let Z=W.messages;if(Array.isArray(Z))return zA(Z)}return[]}catch{return[]}}function wT($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:_A($.content)};return{...$,content:$.content.map((f)=>{if(f.type!=="text"||typeof f.text!=="string")return f;return{...f,text:_A(f.text)}})}}function zA($){return $.map(wT)}function s9($){return $?{...$}:void 0}async function TA($,f){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await f.queueSpawnRequest($);let W=await f.upsertSubagentSessionFromHook($);if(!W)return;await f.appendSubagentHookAudit(W,$),await f.applySubagentStatus(W,$)}function uJ($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function d0($){let f=uJ($);if(!f)return;return f.toLowerCase()==="unknown"?void 0:f}function O5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function ET($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function e9($){let f=$??200;return Number.isFinite(f)?Math.max(0,Math.floor(f)):200}function bT($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function kT($){return $.isSubagent!==!0&&!uJ($.parentSessionId)}function IT($){let f=$.match(/\d{13,}/g);if(!f||f.length===0)return 0;let J=0;for(let W of f){let Z=Number.parseInt(W,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function _5($){return{sessionId:$.session_id,source:$.source,pid:$.pid,startedAt:$.started_at,endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspace_root,teamName:$.team_name,enableTools:$.enable_tools,enableSpawn:$.enable_spawn,enableTeams:$.enable_teams,isSubagent:!1,prompt:$.prompt,metadata:$.metadata,messagesPath:$.messages_path,updatedAt:$.ended_at??$.started_at}}async function xT($){let f=e9($);if(f===0)return[];let J=qA(),Z=(await ST(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:IT(j.name.trim())})).sort((j,H)=>H.recency-j.recency||H.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let H=j.name.trim();if(!H)return;let X=yA(J,H,`${H}.json`),Y=await MA(X,"utf8").catch(()=>{return});if(!Y)return;let A;try{A=JSON.parse(Y)}catch{return}let V=M0.safeParse(A);if(!V.success)return;return _5(V.data)}))).filter((j)=>Boolean(j)).sort((j,H)=>H.startedAt.localeCompare(j.startedAt)).slice(0,f)}async function mT($,f,J){let W=e9(f);if(W===0)return await $.listSessions(0),[];let Z=J.includeSubagents?W:bT(W),Q=await $.listSessions(Z);return(J.includeSubagents?Q:Q.filter(kT)).slice(0,W)}function gT($){if(typeof $==="string")return $.trim();let f=[];for(let J of $){if(!J||typeof J!=="object")continue;let W=J;if(W.type!=="text")continue;let Z=W.text?.trim();if(Z)f.push(Z)}return f.join(`
|
|
481
|
+
`).trim()}function NA($){return $.replace(/\s+/g," ").trim()}function vT($,f){if($.length<=f)return $;return`${$.slice(0,Math.max(0,f-3)).trimEnd()}...`}function uT($){for(let f of["user","assistant"])for(let J of $){if(J.role!==f)continue;let W=NA(gT(J.content));if(!W)continue;let Z=f==="user"?NA(hT(W)):W,Q=CT(Z.split(`
|
|
482
|
+
`)[0]??Z);return vT(Q,50)}return}function cT($){let f=0;for(let J of $)f+=O5(J.metrics?.cost)??0;return f}function dT($){let f,J;for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(!f)f=d0(Z.modelInfo?.provider);if(!J)J=d0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function lT($){return d0($?.provider)??d0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function pT($){return d0($?.model)??d0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function o9($,f){let J=ET($.metadata),W=uJ(f?.title)??uJ(J?.title),Z=O5(f?.totalCost)??O5(J?.totalCost),Q=J||W!==void 0||Z!==void 0?{...J??{},...W!==void 0?{title:W}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:d0(f?.provider)??d0($.provider)??lT(J)??"",model:d0(f?.model)??d0($.model)??pT(J)??"",metadata:Q}}function rT($){let f=$.content;if(!Array.isArray(f))return!1;return f.some((J)=>!!J&&typeof J==="object"&&J.type==="tool-call")}function iT($,f){if($.status!=="running"||$.interactive!==!0)return!1;let J=f.at(-1);return J?.role==="assistant"&&!rT(J)}async function nT($,f){return await Promise.all(f.map(async(J)=>{if(J.status!=="running"||J.interactive!==!0)return J;let W=await $.readSessionMessages(J.sessionId);return iT(J,W)?{...J,status:"idle"}:J}))}async function wA($,f){return await Promise.all(f.map(async(J)=>{let W=o9(J),Z=Boolean(uJ(W.metadata?.title)),Q=Boolean(d0(W.provider)),j=Boolean(d0(W.model)),H=O5(W.metadata?.totalCost),X=H!==void 0&&H>0;if(Z&&Q&&j&&X)return W;let Y=await $.readSessionMessages(J.sessionId);if(Y.length===0)return W;let A=dT(Y),V=cT(Y);return o9(J,{title:Z?void 0:uT(Y),provider:Q?void 0:A.provider,model:j?void 0:A.model,totalCost:X||V<=0?void 0:V})}))}async function z5($,f={}){let J=e9(f.limit),W=f.includeSubagents===!0,Z=await mT($,J,{includeSubagents:W}),Q=f.includeManifestFallback===!0&&Z.length<J?await xT(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let Y of[...Z,...Q]){if(j.has(Y.sessionId))continue;j.set(Y.sessionId,Y)}let H=Q.length===0?Z:Array.from(j.values()).sort((Y,A)=>A.startedAt.localeCompare(Y.startedAt)).slice(0,J),X=await nT($,H);if(f.hydrate===!1)return X.map((Y)=>o9(Y));return await wA($,X)}async function aT($){let f=$.trim();if(!f)return;let J=yA(qA(),f,`${f}.json`),W=await MA(J,"utf8").catch(()=>{return});if(!W)return;try{let Z=M0.safeParse(JSON.parse(W));return Z.success?Z.data.messages_path:void 0}catch{return}}async function $Q($,f={}){let J=new Map;return await z5({listSessions:async(Z)=>{let Q=await $.listSessions(Z);J.clear();for(let j of Q)J.set(j.sessionId,j);return Q.map(d8)},readSessionMessages:async(Z)=>{let Q=J.get(Z)?.messagesPath??await aT(Z);return await R1(Q)}},f)}var BV={};w(BV,{resolveSessionBackend:()=>DQ,createRuntimeHost:()=>S2});import{captureSdkError as AV}from"@cline/shared";var dA={};w(dA,{HubRuntimeHost:()=>m$});import{captureSdkError as CA,createSessionId as EA,HUB_CHECKPOINT_CAPABILITY as eT,HUB_COMPACTION_CAPABILITY as $N,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as fN,HUB_HOOK_CAPABILITY_PREFIX as JN,HUB_MISTAKE_LIMIT_CAPABILITY as WN,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ZN,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as QN,isHubToolExecutorName as jN}from"@cline/shared";var hA={};w(hA,{createCoreSessionSnapshot:()=>B$,coreSessionSnapshotToRecord:()=>T5});function tT($){return $?JSON.parse(JSON.stringify($)):void 0}function sT($){return $?JSON.parse(JSON.stringify($)):void 0}function oT($){let f=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,W=(Array.isArray(f?.history)?f.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let H=typeof j.ref==="string"?j.ref.trim():"",X=Number(j.createdAt),Y=Number(j.runCount);if(!H||!Number.isFinite(X)||!Number.isInteger(Y))return[];return[{ref:H,createdAt:X,runCount:Y,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=W.at(-1),Q=$?.checkpointEnabled===!0?!0:void 0;if(!Q&&W.length===0)return;return{...Q?{enabled:Q}:{},...Z?{latest:Z}:{},history:W}}function B$($){let{session:f}=$,J=tT(f.metadata);return{version:1,sessionId:f.sessionId,source:f.source,status:f.status,createdAt:f.startedAt,updatedAt:f.updatedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,interactive:f.interactive,workspace:{cwd:f.cwd,root:f.workspaceRoot},model:{providerId:f.provider,modelId:f.model},capabilities:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams},lineage:{...f.parentSessionId?{parentSessionId:f.parentSessionId}:{},...f.parentAgentId?{parentAgentId:f.parentAgentId}:{},...f.agentId?{agentId:f.agentId}:{},...f.conversationId?{conversationId:f.conversationId}:{},isSubagent:f.isSubagent},...f.teamName?{team:{name:f.teamName}}:{},...f.prompt?{prompt:f.prompt}:{},...J?{metadata:J}:{},...f.messagesPath?{artifacts:{messagesPath:f.messagesPath}}:{},...$.messages?{messages:sT($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let W=oT(J);return W?{checkpoint:W}:{}})()}}function T5($){return{sessionId:$.sessionId,parentSessionId:$.lineage.parentSessionId,agentId:$.lineage.agentId,parentAgentId:$.lineage.parentAgentId,conversationId:$.lineage.conversationId,isSubagent:$.lineage.isSubagent,source:$.source,startedAt:$.createdAt,endedAt:$.endedAt??void 0,exitCode:$.exitCode??void 0,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspaceRoot:$.workspace.root,teamName:$.team?.name,enableTools:$.capabilities.enableTools,enableSpawn:$.capabilities.enableSpawn,enableTeams:$.capabilities.enableTeams,prompt:$.prompt,metadata:$.metadata,updatedAt:$.updatedAt,messagesPath:$.artifacts?.messagesPath}}function T2($){if(!$)return;return JSON.parse(JSON.stringify($))}var HN=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function bA($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function kA($){if(!$)return;let{userInstructionService:f,...J}=$;return JSON.parse(JSON.stringify(J))}function IA($){let f=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof f.agentId==="string"?f.agentId:"",conversationId:typeof f.conversationId==="string"?f.conversationId:"",iteration:typeof f.iteration==="number"?f.iteration:0,metadata:f.metadata&&typeof f.metadata==="object"&&!Array.isArray(f.metadata)?f.metadata:void 0}}function Kf($,f,J){$.manifest.push(f),$.handlers.set(f.capabilityName,J)}function xA($,f){let J={manifest:[],handlers:new Map};for(let Z of Object.keys(f.toolExecutors??{}).filter(jN)){let Q=f.toolExecutors?.[Z];if(typeof Q!=="function")continue;Kf(J,{kind:"toolExecutor",executor:Z,capabilityName:`${ZN}${Z}`},async({payload:j,abortSignal:H})=>{let X=Array.isArray(j.args)?[...j.args]:[],Y={...IA(j.context),signal:H};return{result:await Q(...X,Y)}})}for(let Z of $?.extraTools??[])Kf(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:T2(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:T2(Z.lifecycle)}:{},capabilityName:`${fN}${Z.name}`},async({payload:Q,abortSignal:j,progress:H})=>{let X={...IA(Q.context),signal:j};return{result:await Z.execute(Q.input,{...X,emitUpdate:(A)=>{H({update:A})}})}});let W=$?.hooks;if(W)for(let Z of HN){let Q=W[Z];if(typeof Q!=="function")continue;Kf(J,{kind:"hook",name:Z,capabilityName:`${JN}${Z}`},async({payload:j})=>({control:await Q(j.context)}))}if($?.compaction?.compact){let Z=$.compaction.compact;Kf(J,{kind:"compaction",capabilityName:$N,config:bA($.compaction)},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.checkpoint?.createCheckpoint){let Z=$.checkpoint.createCheckpoint;Kf(J,{kind:"checkpoint",capabilityName:eT,config:bA($.checkpoint)},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.onConsecutiveMistakeLimitReached){let Z=$.onConsecutiveMistakeLimitReached;Kf(J,{kind:"mistakeLimit",capabilityName:WN},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.userInstructionService){let Z=$.userInstructionService;Kf(J,{kind:"userInstructionService",capabilityName:QN},async()=>{return await Z.start().catch(()=>{}),{snapshot:{records:{skill:Z.listRecords("skill"),rule:Z.listRecords("rule"),workflow:Z.listRecords("workflow")},runtimeCommands:Z.listRuntimeCommands()}}})}return J}function uA($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let f=$.message;if(typeof f==="string"&&f.trim())return f.trim()}return}function XN($){return uA($)??"Capability request was cancelled."}function YN($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function AN($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function VN($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=typeof f.inputTokens==="number"?f.inputTokens:void 0,W=typeof f.outputTokens==="number"?f.outputTokens:void 0;if(J===void 0||W===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function mA($){if(!$)return;return{inputTokens:typeof $.inputTokens==="number"?$.inputTokens:0,outputTokens:typeof $.outputTokens==="number"?$.outputTokens:0,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function fQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function D1($,f){return fQ($?.[f])??0}function BN($){let f=$?.delta&&typeof $.delta==="object"?$.delta:void 0,J=$?.totals&&typeof $.totals==="object"?$.totals:void 0,W=$?.agent&&typeof $.agent==="object"?$.agent:void 0,Z=W?.teamRole==="teammate"||W?.teamRole==="lead"?W.teamRole:void 0;return{event:{type:"usage",agentId:typeof W?.agentId==="string"?W.agentId:void 0,conversationId:typeof W?.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W?.parentAgentId==="string"?W.parentAgentId:void 0,inputTokens:D1(f,"inputTokens"),outputTokens:D1(f,"outputTokens"),cacheReadTokens:D1(f,"cacheReadTokens"),cacheWriteTokens:D1(f,"cacheWriteTokens"),cost:fQ(f?.totalCost),totalInputTokens:D1(J,"inputTokens"),totalOutputTokens:D1(J,"outputTokens"),totalCacheReadTokens:D1(J,"cacheReadTokens"),totalCacheWriteTokens:D1(J,"cacheWriteTokens"),totalCost:fQ(J?.totalCost)},teamAgentId:typeof W?.teamAgentId==="string"?W.teamAgentId:void 0,teamRole:Z}}function KN($){let f=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,J=$?.reason??f?.finishReason,W=AN(J)?J:J==="failed"?"error":"completed",Z=VN($?.usage??f?.usage);return{type:"done",reason:W,text:typeof $?.text==="string"?$.text:typeof f?.text==="string"?f.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof f?.iterations==="number"?f.iterations:0,usage:Z}}function N5($,f){return $.error?.message??`hub command failed: ${f}`}function cJ($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function cA($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof f?.parentSessionId==="string"?f.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof f?.agentId==="string"?f.agentId:void 0),parentAgentId:typeof f?.parentAgentId==="string"?f.parentAgentId:void 0,conversationId:typeof f?.conversationId==="string"?f.conversationId:void 0,isSubagent:typeof f?.isSubagent==="boolean"?f.isSubagent:!1,source:typeof f?.source==="string"?f.source:P0.CORE,pid:typeof f?.pid==="number"?f.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:cJ($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:cJ($.status)==="completed"?0:cJ($.status)==="failed"?1:void 0,status:cJ($.status),interactive:f?.interactive===!0,provider:typeof f?.provider==="string"?f.provider:"hub",model:typeof f?.model==="string"?f.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof f?.teamName==="string"?f.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??f?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??f?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??f?.enableTeams===!0,prompt:typeof f?.prompt==="string"?f.prompt:void 0,metadata:f,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof f?.messagesPath==="string"?f.messagesPath:void 0,hookPath:typeof f?.hookPath==="string"?f.hookPath:void 0}}function L1($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;return f.version===1&&typeof f.sessionId==="string"?JSON.parse(JSON.stringify(f)):void 0}function GN($){let f=L1($?.snapshot);if(f)return T5(f);let J=$?.session;return J?cA(J):void 0}function gA($,f,J){let W=J?.workspaceRoot?.trim()||f.config.workspaceRoot||f.config.cwd;return M0.parse({version:1,session_id:$,source:f.source??P0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:cJ(J?.status),interactive:f.interactive===!0,provider:f.config.providerId,model:f.config.modelId,cwd:J?.cwd?.trim()||f.config.cwd,workspace_root:W,team_name:f.config.teamName,enable_tools:f.config.enableTools,enable_spawn:f.config.enableSpawnAgent,enable_teams:f.config.enableAgentTeams,prompt:f.prompt?.trim()||void 0,metadata:f.sessionMetadata&&Object.keys(f.sessionMetadata).length>0?f.sessionMetadata:void 0})}function vA($,f){return M0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??f.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class m${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new vJ;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,f){this.clientContext=f,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd},this.defaultCapabilities=R0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient($.url)}createClient($){return new s0({...this.clientOptions,url:$})}async replaceClient($){let f=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(f.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!d4($,"session.create"))return!1;let f=await l4({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!f)return!1;return await this.replaceClient(f),!0}registerPlannedSession($,f,J){if(this.sessionCapabilities.set($,f),J.size>0)this.sessionClientContributionHandlers.set($,J);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let f=this.resolveCapabilities($),J=xA($.localRuntime,f),W=$.config.sessionId?.trim()||EA(),Z=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:T2({...$.config,sessionId:W}),metadata:{...$.sessionMetadata??{},source:$.source??P0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:T2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(W,f,J.handlers);let Q;try{Q=await Z()}catch(Y){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(Y)){this.registerPlannedSession(W,f,J.handlers);try{Q=await Z()}catch(A){throw this.cleanupPlannedSession(W),A}}else throw Y}let j=L1(Q.payload?.snapshot),H=Q.payload?.session,X=(j?.sessionId??H?.sessionId)?.trim();if(!X)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(X!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(X,f,J.handlers);return{sessionId:X,manifest:j?vA(j,$):gA(X,$,H),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.start)throw Error("start is required when restore.messages is true");let W=$.start,Z=W?this.resolveCapabilities(W):void 0,Q=W?xA(W.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=W?W.config.sessionId?.trim()||EA():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(j,Q.handlers),this.ensureSessionSubscription(j);let H;try{H=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.config.workspaceRoot?.trim()||W.config.cwd,cwd:W.config.cwd??$.cwd,sessionConfig:T2({...W.config,sessionId:j}),metadata:{...W.sessionMetadata??{},source:W.source??P0.CORE,provider:W.config.providerId,model:W.config.modelId,enableTools:W.config.enableTools,enableSpawn:W.config.enableSpawnAgent,enableTeams:W.config.enableAgentTeams,teamName:W.config.teamName,prompt:W.prompt,interactive:W.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...W.localRuntime?.configExtensions?{configExtensions:W.localRuntime.configExtensions}:{}},toolPolicies:T2(W.toolPolicies)}:{}},f)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!H.ok){let K=typeof H.payload?.error==="string"?H.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let X=L1(H.payload?.snapshot),Y=H.payload?.session,A=(X?.sessionId??Y?.sessionId)?.trim();if(J&&!A){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(A&&j&&A!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(A&&Z)this.sessionCapabilities.set(A,Z);if(A&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(A,Q.handlers);if(A)this.ensureSessionSubscription(A);let V=Array.isArray(H.payload?.messages)?H.payload.messages:void 0,B=H.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:A,startResult:A?{sessionId:A,manifest:X?vA(X,W??{}):gA(A,W??{},Y),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:V,checkpoint:B}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,updated:f.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,removed:f.payload?.removed===!0}}async getAccumulatedUsage($){let f=await this.client.command("session.get",{includeSnapshot:!0},$),J=L1(f.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,H=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||H?{usage:j,aggregateUsage:H}:void 0}let W=f.payload?.session,Z=mA(W?.usage),Q=mA(W?.aggregateUsage);return Z||Q?{usage:Z,aggregateUsage:Q}:void 0}async abort($,f){await this.client.command("run.abort",{sessionId:$,reason:uA(f)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,f]of this.sessionSubscriptions){f();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(y$(J))return;throw J}return GN(f.payload)}async listSessions($=100){let f=await this.client.command("session.list",{limit:$}),J=Array.isArray(f.payload?.snapshots)?f.payload.snapshots.flatMap((Z)=>{let Q=L1(Z);return Q?[T5(Q)]:[]}):[];if(J.length>0)return J;return(f.payload?.sessions??[]).map(cA)}async listSettings($){let f=await this.client.command("settings.list",kA($));if(!f.ok)throw Error(N5(f,"settings.list"));return f.payload?.snapshot}async toggleSetting($){let f=await this.client.command("settings.toggle",kA($));if(!f.ok)throw Error(N5(f,"settings.toggle"));return{snapshot:f.payload?.snapshot,changedTypes:Array.isArray(f.payload?.changedTypes)?f.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,f){let J={...f.metadata??{}};if(typeof f.prompt==="string")J.prompt=f.prompt;if(typeof f.title==="string")J.title=f.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:J})).ok}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw CA(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(N5(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:f,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(N5(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,f){return this.events.subscribe($,f)}ensureSessionSubscription($){let f=$.trim();if(!f||this.sessionSubscriptions.has(f))return;let J=this.client.subscribe((W)=>{this.handleHubEvent(W)},{sessionId:f});this.sessionSubscriptions.set(f,typeof J==="function"?J:()=>{})}disposeSessionSubscription($){let f=$.trim();if(!f)return;this.sessionSubscriptions.get(f)?.(),this.sessionSubscriptions.delete(f),this.agentDoneEmittedForCurrentRunBySession.delete(f)}resolveCapabilities($){return R0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:KN($.payload)}})}handleHubEvent($){let f=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",J,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",J,$)});return}if(!f)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(f);let J=L1($.payload?.snapshot),W=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:W?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"",W=$.payload?.redacted===!0;if(!J&&!W)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:W}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:f,payload:$.payload});return}case"usage.updated":{let J=BN($.payload);this.events.emit({type:"agent_event",payload:{sessionId:f,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:f,toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=L1($.payload?.snapshot),W=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:W?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:f,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=$.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:f,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=L1($.payload?.snapshot),W=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:f,payload:{...$.payload,reason:W}}),J?.interactive===!0&&W0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:f,reason:W,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,f,J){try{CA(this.telemetry,{component:"core",operation:$,error:f,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let f=$.sessionId?.trim();if(!f)return;let J=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let W=typeof $.payload?.requestId==="string"?$.payload.requestId:"",Z=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!W)return;let Q=this.sessionClientContributionHandlers.get(f)?.get(Z);if(!Q){await this.client.command("capability.respond",{requestId:W,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${f}.`},f).catch(()=>{});return}let j=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},H=new AbortController;this.activeCapabilityAbortControllers.set(W,H);let X=(Y)=>{this.client.command("capability.progress",{requestId:W,payload:Y},f).catch((A)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",A,$)})};try{let Y=await Q({payload:j,abortSignal:H.signal,progress:X});if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!0,payload:Y},f)}catch(Y){if(H.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:Y instanceof Error?Y.message:String(Y)},f)}finally{this.activeCapabilityAbortControllers.delete(W)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let f=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!f)return;let J=this.activeCapabilityAbortControllers.get(f);if(!J)return;J.abort(XN($.payload.error))}async handleApprovalRequested($){let f=$.sessionId?.trim();if(!f)return;let J=this.sessionCapabilities.get(f)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let W=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",Q=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!W||!Z||!Q)return;let j=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},H=YN($.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:f,toolCallId:Z,toolName:Q,toolInput:H});let X=await Promise.resolve(J({sessionId:f,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:f,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:Z,toolName:Q,input:H,policy:j})).catch((Y)=>({approved:!1,reason:Y instanceof Error?Y.message:`Tool approval request failed: ${String(Y)}`}));await this.client.command("approval.respond",{approvalId:W,approved:X.approved,reason:X.reason},f).catch(()=>{})}}var lA={};w(lA,{RemoteRuntimeHost:()=>N2});class N2 extends m${constructor($){super({url:o$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var pA={};w(pA,{SqliteSessionStore:()=>G$});import{existsSync as PN,mkdirSync as FN}from"node:fs";import{join as UN}from"node:path";import{asBool as dJ,asOptionalString as K$,asString as g$,ensureSessionSchema as RN,loadSqliteDb as DN,nowIso as M5,toBoolInt as lJ}from"@cline/shared/db";import{resolveDbDataDir as LN}from"@cline/shared/storage";class G${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??LN()}init(){this.getRawDb()}ensureSessionsDir(){if(!PN(this.sessionsDirPath))FN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return UN(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=DN(this.sessionDbPath());return RN($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}create($){let f=M5();this.run(`INSERT OR REPLACE INTO sessions (
|
|
483
483
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
484
484
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
485
485
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
486
486
|
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
487
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,
|
|
487
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,lJ($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,lJ($.enableTools),lJ($.enableSpawn),lJ($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,lJ($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,f])}update($){let f=[],J=[];if($.endedAt!==void 0)f.push("ended_at = ?"),J.push($.endedAt);if($.exitCode!==void 0)f.push("exit_code = ?"),J.push($.exitCode);if($.status!==void 0)f.push("status = ?"),J.push($.status);if($.prompt!==void 0)f.push("prompt = ?"),J.push($.prompt);if($.metadata!==void 0)f.push("metadata_json = ?"),J.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)f.push("parent_session_id = ?"),J.push($.parentSessionId);if($.parentAgentId!==void 0)f.push("parent_agent_id = ?"),J.push($.parentAgentId);if($.agentId!==void 0)f.push("agent_id = ?"),J.push($.agentId);if($.conversationId!==void 0)f.push("conversation_id = ?"),J.push($.conversationId);if(f.length===0)return;f.push("updated_at = ?"),J.push(M5()),J.push($.sessionId),this.run(`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`,J)}updateStatus($,f,J){this.update({sessionId:$,status:f,endedAt:W0(f)?null:M5(),exitCode:W0(f)?null:J??(f==="failed"?1:0)})}get($){let f=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
|
|
488
488
|
provider, model, cwd, workspace_root, team_name,
|
|
489
489
|
enable_tools, enable_spawn, enable_teams,
|
|
490
490
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
|
|
491
491
|
prompt, metadata_json, hook_path, messages_path, updated_at
|
|
492
|
-
FROM sessions WHERE session_id = ?`,[$]);if(!f)return;return{sessionId:
|
|
493
|
-
`,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let f=this.artifacts.sessionManifestPath($,!1);if(!
|
|
494
|
-
`;if(
|
|
495
|
-
`,"utf8")}}import{appendFileSync as
|
|
496
|
-
`,"utf8")}}import{formatUserInputBlock as
|
|
492
|
+
FROM sessions WHERE session_id = ?`,[$]);if(!f)return;return{sessionId:g$(f.session_id),source:g$(f.source),pid:Number(f.pid??0),startedAt:g$(f.started_at),endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:g$(f.status),interactive:dJ(f.interactive),provider:g$(f.provider),model:g$(f.model),cwd:g$(f.cwd),workspaceRoot:g$(f.workspace_root),teamName:K$(f.team_name),enableTools:dJ(f.enable_tools),enableSpawn:dJ(f.enable_spawn),enableTeams:dJ(f.enable_teams),parentSessionId:K$(f.parent_session_id),parentAgentId:K$(f.parent_agent_id),agentId:K$(f.agent_id),conversationId:K$(f.conversation_id),isSubagent:dJ(f.is_subagent),prompt:K$(f.prompt),metadata:(()=>{let J=K$(f.metadata_json);if(!J)return;try{let W=JSON.parse(J);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return})(),hookPath:K$(f.hook_path),messagesPath:K$(f.messages_path),updatedAt:K$(f.updated_at)??M5()}}list($=200){let f=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),J=[];for(let W of f){let Z=this.get(g$(W.session_id));if(Z)J.push(Z)}return J}delete($,f=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}}x4();import{existsSync as KQ,mkdirSync as gN,readFileSync as JV,renameSync as vN,writeFileSync as uN}from"node:fs";import{join as WV}from"node:path";import{resolveSessionDataDir as cN}from"@cline/shared/storage";import{dirname as xN}from"node:path";import{nanoid as mN}from"nanoid";import{appendFileSync as ON,existsSync as _N,mkdirSync as rA,readFileSync as zN,writeFileSync as iA}from"node:fs";import{dirname as nA,join as TN}from"node:path";import{ensureHookLogDir as NN}from"@cline/shared/storage";class JQ{adapter;messagesArtifactUploader;logger;artifacts;constructor($,f,J){this.adapter=$;this.messagesArtifactUploader=f;this.logger=J;this.artifacts=new R9(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,f,J){cH(f,J,EZ($))}writeSessionManifest($,f){rA(nA($),{recursive:!0}),iA($,`${JSON.stringify(M0.parse(f),null,2)}
|
|
493
|
+
`,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let f=this.artifacts.sessionManifestPath($,!1);if(!_N(f))return{path:f};try{return{path:f,manifest:M0.parse(JSON.parse(zN(f,"utf8")))}}catch{return{path:f}}}async resolveArtifactPath($,f,J){let Z=(await this.adapter.getSession($))?.[f];return typeof Z==="string"&&Z.trim().length>0?Z:J($)}async persistSessionMessages($,f,J){let W=await this.resolveArtifactPath($,"messagesPath",(j)=>this.artifacts.sessionMessagesPath(j)),Z=bZ({updatedAt:s(),context:EZ($),messages:f,systemPrompt:J}),Q=`${JSON.stringify(Z,null,2)}
|
|
494
|
+
`;if(rA(nA(W),{recursive:!0}),iA(W,Q,"utf8"),!this.messagesArtifactUploader)return;try{let j=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:W,contents:Q,row:j})}catch(j){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:j})}}appendStaleSessionHookLog($,f,J,W,Z){let j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??TN(NN(),"hooks.jsonl");ON(j,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:W,sessionId:f,pid:J,source:Z})}
|
|
495
|
+
`,"utf8")}}import{appendFileSync as MN}from"node:fs";import{join as yN}from"node:path";import{resolveRootSessionId as aA}from"@cline/shared";import{ensureHookLogDir as qN}from"@cline/shared/storage";import{z as WQ}from"zod";var wN="subagent",SN=WQ.looseObject({task:WQ.string().optional(),systemPrompt:WQ.string().optional()});class y5{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,f,J,W){this.adapter=$;this.manifestStore=f;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=W}teamTaskQueueKey($,f){return`${$}::${f}`}activeTeamTaskSessionId($,f){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,f))?.at(-1)}buildSubsessionRow($,f){return{sessionId:f.sessionId,source:wN,pid:process.ppid,startedAt:f.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:f.parentSessionId,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId??null,isSubagent:!0,prompt:f.prompt,metadata:l8({prompt:f.prompt}),hookPath:"",messagesPath:f.messagesPath,updatedAt:f.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let f=aA($.sessionContext);if(!f)return;let J=SN.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:f,parentAgentId:$.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession($){let f=$.rootSessionId;if(!f)return;let J=await this.adapter.getSession(f);if(!J)return;let W=nf(f,$.agentId),Z=await this.adapter.getSession(W),Q=s(),j=this.manifestStore.artifacts.subagentArtifactPaths(W,$.agentId,this.activeTeamTaskSessionId(f,$.parentAgentId)),H=$.prompt??Z?.prompt??void 0;if(!H)H=await this.adapter.claimSpawnRequest(f,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!Z)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:W,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:H,startedAt:Q,...j})),this.manifestStore.initializeMessagesFile(W,j.messagesPath,Q),W;return await this.adapter.updateSession({sessionId:W,setRunning:!0,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Z.prompt??H??null,metadata:l8({metadata:Z.metadata??void 0,prompt:Z.prompt??H??null}),expectedStatusLock:Z.statusLock}),W}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let f=aA($.sessionContext);if(!f)return;if($.hookName==="session_shutdown"){let J=nf(f,$.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:f})}async applySubagentStatus($,f){await this.applySubagentStatusBySessionId($,u8(f))}async applySubagentStatusBySessionId($,f){let J=await this.adapter.getSession($);if(!J)return;let W=W0(f)?null:s(),Z=W0(f)?null:f==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:f,endedAt:W,exitCode:Z,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions($,f){if(!$)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let W of J)await this.applySubagentStatusBySessionId(W.sessionId,f)}async onTeamTaskStart($,f,J){let W=await this.adapter.getSession($);if(!W)return;let Z=g8($,f),Q=s(),{messagesPath:j}=this.manifestStore.artifacts.subagentArtifactPaths(Z,f);await this.adapter.upsertSession(this.buildSubsessionRow(W,{sessionId:Z,parentSessionId:$,parentAgentId:"lead",agentId:f,prompt:J||`Team task for ${f}`,startedAt:Q,messagesPath:j})),this.manifestStore.initializeMessagesFile(Z,j,Q);let H=this.teamTaskQueueKey($,f),X=this.teamTaskSessionsByAgent.get(H)??[];X.push(Z),this.teamTaskSessionsByAgent.set(H,X)}async onTeamTaskEnd($,f,J,W,Z,Q){let j=this.teamTaskQueueKey($,f),H=this.teamTaskSessionsByAgent.get(j);if(!H||H.length===0)return;let X=H.shift();if(H.length===0)this.teamTaskSessionsByAgent.delete(j);if(!X)return;let Y=Z?.messages??Q,A=this.toPersistedMessages(Y,Z,Q);if(A)await this.manifestStore.persistSessionMessages(X,A);await this.applySubagentStatusBySessionId(X,J),this.teamTaskLastHeartbeatBySession.delete(X),this.teamTaskLastProgressLineBySession.delete(X)}async onTeamTaskProgress($,f,J,W){let Z=this.teamTaskQueueKey($,f),Q=this.teamTaskSessionsByAgent.get(Z)?.[0];if(!Q)return;let j=J.trim();if(!j)return;let H=W?.kind??"progress";if(H==="heartbeat"){let Y=Date.now(),A=this.teamTaskLastHeartbeatBySession.get(Q)??0;if(Y-A<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(Q,Y)}let X=H==="heartbeat"?"[progress] heartbeat":H==="text"?`[progress] text: ${j}`:`[progress] ${j}`;if(this.teamTaskLastProgressLineBySession.get(Q)===X)return;this.teamTaskLastProgressLineBySession.set(Q,X)}async handleSubAgentStart($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;if(f.error){await this.applySubagentStatusBySessionId(J,"failed");return}let W=this.toPersistedMessages(f.agentResult?.messages,f.agentResult);if(W)await this.manifestStore.persistSessionMessages(J,W);let Z=f.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,Z==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??yN(qN(),"hooks.jsonl");MN(J,`${JSON.stringify({ts:s(),...$})}
|
|
496
|
+
`,"utf8")}}import{formatUserInputBlock as IN}from"@cline/shared";var fV={};w(fV,{toTeamProgressLifecycleEvent:()=>y2,sanitizeTeamName:()=>CH,reviveTeamStateDates:()=>Z6,createWorkerReviewerTeam:()=>$V,createSpawnAgentTool:()=>Q1,createDelegatedAgentConfigProvider:()=>df,createDelegatedAgent:()=>lf,createAgentTeamsTools:()=>d1,createAgentTeam:()=>QQ,buildTeamProgressSummary:()=>M2,buildDelegatedAgentConfig:()=>u1,bootstrapAgentTeams:()=>rf,AgentTeamsRuntime:()=>Gf,AgentTeam:()=>w2});function P$(){return new Date().toISOString()}function tA($,f){if(f<=0)return 0;return Math.round($/f*100)}function hN($,f){let J=new Set;for(let Z of f)if(Z.status==="reviewed")J.add(`${Z.outcomeId}:${Z.section}`);let W=new Set;for(let Z of $){if(Z.status==="finalized")continue;for(let Q of Z.requiredSections)if(!J.has(`${Z.id}:${Q}`))W.add(`${Z.id}:${Q}`)}return[...W].sort((Z,Q)=>Z.localeCompare(Q))}function M2($,f){let J={idle:0,running:0,stopped:0},W={pending:0,in_progress:0,blocked:0,completed:0},Z={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},Q={draft:0,in_review:0,finalized:0},j={draft:0,reviewed:0,rejected:0},H=0,X=0;for(let P of f.members)if(J[P.status]+=1,P.role==="lead")H+=1;else X+=1;let Y=[],A=[],V=f.tasks.filter((P)=>P.status==="completed").length,B=new Map(f.tasks.map((P)=>[P.id,P]));for(let P of f.tasks){if(W[P.status]+=1,P.status==="blocked"){Y.push(P.id);continue}if(P.status!=="pending")continue;if(P.dependsOn.every((U)=>{return B.get(U)?.status==="completed"}))A.push(P.id)}let K=[],G,R=0;for(let P of f.runs){if(Z[P.status]+=1,P.status==="queued"||P.status==="running")K.push(P.id);let F=P.startedAt.getTime();if(F>=R)R=F,G=P.id}for(let P of f.outcomes)Q[P.status]+=1;for(let P of f.outcomeFragments)j[P.status]+=1;return{teamName:$,updatedAt:P$(),members:{total:f.members.length,byStatus:J,leadCount:H,teammateCount:X},tasks:{total:f.tasks.length,byStatus:W,blockedTaskIds:Y,readyTaskIds:A,completionPct:tA(V,f.tasks.length)},runs:{total:f.runs.length,byStatus:Z,activeRunIds:K,latestRunId:G},outcomes:{total:f.outcomes.length,byStatus:Q,finalizedPct:tA(Q.finalized,f.outcomes.length),missingRequiredSections:hN(f.outcomes,f.outcomeFragments)},fragments:{total:f.outcomeFragments.length,byStatus:j}}}function y2($){let{event:f}=$;switch(f.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),taskId:f.task.id,agentId:f.task.assignee??f.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),outcomeId:f.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),outcomeId:f.fragment.outcomeId,fragmentId:f.fragment.id,agentId:f.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),taskId:f.message.taskId,agentId:f.message.fromAgentId,message:f.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),taskId:f.entry.taskId,agentId:f.entry.agentId,message:f.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),agentId:f.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$()}}import{sanitizeFileName as CN,TeamMessageType as b}from"@cline/shared";import{nanoid as EN}from"nanoid";import{TeamMessageType as sg}from"@cline/shared";function ZQ($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function sA($,f){return $?.status==="stopped"&&ZQ(f)}var bN=600000,oA="recovered_queued";function kN($){return`This is an automatic recovery of interrupted team run ${$.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
|
|
497
497
|
|
|
498
|
-
${$.message}`}class
|
|
499
|
-
${
|
|
498
|
+
${$.message}`}class w2{agents=new Map;configs=new Map;onTeamEvent;constructor($,f){if(this.onTeamEvent=f,$)for(let[J,W]of Object.entries($))this.addAgent(J,W)}addAgent($,f){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let J={...f,onEvent:(Z)=>{f.onEvent?.(Z),this.emitEvent({type:b.AgentEvent,agentId:$,event:Z})}},W=new Z1(J);if(J.onEvent)W.subscribeEvents(J.onEvent);this.agents.set($,W),this.configs.set($,f)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:b.TaskStart,agentId:$,message:f});try{let W=await J.run(f);return this.emitEvent({type:b.TaskEnd,agentId:$,result:W}),W}catch(W){let Z=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:b.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),W}}async continueTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:b.TaskStart,agentId:$,message:f});try{let W=await J.continue(f);return this.emitEvent({type:b.TaskEnd,agentId:$,result:W}),W}catch(W){let Z=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:b.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),W}}async runParallel($){let f=$.map(async(J)=>{let W=this.agents.get(J.agentId);if(!W)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:b.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await W.run(J.message);return this.emitEvent({type:b.TaskEnd,agentId:J.agentId,result:Z}),{agentId:J.agentId,result:Z,metadata:J.metadata}}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));return this.emitEvent({type:b.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),{agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata}}});return Promise.all(f)}async runSequential($){let f=[];for(let J of $){let W=this.agents.get(J.agentId);if(!W){f.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:b.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await W.run(J.message);this.emitEvent({type:b.TaskEnd,agentId:J.agentId,result:Z}),f.push({agentId:J.agentId,result:Z,metadata:J.metadata})}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));this.emitEvent({type:b.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),f.push({agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata})}}return f}async runPipeline($,f,J){let W=[],Z=f;for(let Q of $){let j=this.agents.get(Q);if(!j){W.push({agentId:Q,result:void 0,error:Error(`Agent "${Q}" not found in team`)});break}this.emitEvent({type:b.TaskStart,agentId:Q,message:Z});try{let H=await j.run(Z);this.emitEvent({type:b.TaskEnd,agentId:Q,result:H}),W.push({agentId:Q,result:H});let X=$.indexOf(Q)+1;if(X<$.length){let Y=$[X];Z=J?J(H,Y):`Previous agent output:
|
|
499
|
+
${H.text}
|
|
500
500
|
|
|
501
|
-
Please continue from here.`}}catch(
|
|
501
|
+
Please continue from here.`}}catch(H){let X=H instanceof Error?H:Error(String(H));this.emitEvent({type:b.TaskEnd,agentId:Q,error:X,messages:j.getMessages()}),W.push({agentId:Q,result:void 0,error:X});break}}return W}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function QQ($,f){return new w2($,f)}function $V($){let f=QQ({worker:$.worker,reviewer:$.reviewer}),J=f;return J.doAndReview=async(W)=>{let Z=await f.routeTo("worker",W),Q=await f.routeTo("reviewer",`Please review this work:
|
|
502
502
|
|
|
503
|
-
${Z.text}`);return{workerResult:Z,reviewResult:
|
|
503
|
+
${Z.text}`);return{workerResult:Z,reviewResult:Q}},J}class Gf{teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor($){this.teamName=$.teamName,this.teamId=`t_${CN(EN(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let f=$.leadAgentId??"lead";this.members.set(f,{agentId:f,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((f)=>{let J=this.getUnresolvedDependencies(f);return{...f,blockedBy:J,isReady:f.status==="pending"&&!f.assignee&&J.length===0}}).filter((f)=>{if($?.status&&f.status!==$.status)return!1;if($?.assignee&&f.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,f){let J=f?.unreadOnly??!0,W=f?.markRead??!0,Z=f?.limit,Q=this.mailbox.filter((H)=>H.toAgentId===$&&(!J||!H.readAt)),j=typeof Z==="number"&&Z>0?Q.slice(Math.max(0,Q.length-Z)):Q;if(W){let H=new Date;for(let X of j)if(!X.readAt)X.readAt=H}return j.map((H)=>({...H}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())$[J.status]++;let f={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())f[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:$,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:f}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of $.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of $.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of $.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of $.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let f=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of f)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of $.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,q2($.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,q2($.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,q2($.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,q2(($.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,q2(($.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,q2(($.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive($){let f=this.members.get($);return!!f&&f.role==="teammate"&&!!f.agent}spawnTeammate({agentId:$,config:f}){let J=this.members.get($);if(J&&J.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let W={...f,apiTimeoutMs:bN,consumePendingUserMessage:()=>{let j=this.members.get($);if(!j||!j.pendingSteerMessage)return;let H=j.pendingSteerMessage;return j.pendingSteerMessage=void 0,H},onEvent:(j)=>{f.onEvent?.(j),this.emitEvent({type:b.AgentEvent,agentId:$,event:j}),this.trackMeaningfulEvent($,j)}},Z=new Z1(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);let Q={agentId:$,role:"teammate",description:f.role,status:"idle",agent:Z,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,Q),this.emitEvent({type:b.TeammateSpawned,agentId:$,role:f.role,teammate:{rolePrompt:f.systemPrompt,modelId:f.modelId,maxIterations:f.maxIterations,runtimeAgentId:Z.getAgentId(),conversationId:Z.getConversationId(),parentAgentId:null}}),{agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status}}shutdownTeammate($,f){let J=this.members.get($);if(!J||J.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{J.agent?.abort()}catch(W){if(!ZQ(W))throw W}J.status="stopped",this.emitEvent({type:b.TeammateShutdown,agentId:$,reason:f})}updateTeammateConnections($){for(let f of this.members.values()){if(f.role!=="teammate"||!f.agent)continue;f.agent.updateConnection($)}}createTask($){let f=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,W={id:f,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(f,W),this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),{...W}}claimTask($,f){let J=this.requireTask($);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=f,J.updatedAt=new Date,this.emitEvent({type:b.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:f,taskId:$,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask($,f,J){let W=this.requireTask($);return W.status="blocked",W.updatedAt=new Date,W.summary=J,this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:f,taskId:$,kind:"blocked",summary:J}),{...W}}completeTask($,f,J){let W=this.requireTask($);if(W.status="completed",W.updatedAt=new Date,W.summary=J,!W.assignee)W.assignee=f;return this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:f,taskId:$,kind:"done",summary:J}),{...W}}async routeToTeammate($,f,J){let W=this.members.get($);if(!W||W.role!=="teammate"||!W.agent)throw Error(`Teammate "${$}" was not found`);if(!W.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");W.runningCount++,W.status="running",this.emitEvent({type:b.TaskStart,agentId:$,message:f});try{let Z=this.listMailbox($,{unreadOnly:!0,markRead:!0}),Q=Z.length>0?`${this.buildMailboxNotification(Z)}
|
|
504
504
|
|
|
505
|
-
${f}`:f,j=J?.continueConversation?await Q.agent.continue(W):await Q.agent.run(W);return this.emitEvent({type:E.TaskEnd,agentId:$,result:j}),this.recordProgressStep($,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:E.TaskEnd,agentId:$,error:W,messages:Q.agent.getMessages()}),!jV(Q,W))this.appendMissionLog({agentId:$,taskId:J?.taskId,kind:"error",summary:W.message});throw W}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get($)?.status!=="stopped")Q.status="idle"}}startTeammateRun($,f,J){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:Q,agentId:$,taskId:J?.taskId,status:"queued",message:f,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,Z),this.runQueue.push(Q),this.emitEvent({type:E.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let f=this.selectNextDispatchableQueuedRun();$=f.nextDelayedAttemptAt;let J=f.index;if(J<0){this.scheduleQueuedRunDispatch($);return}let[Q]=this.runQueue.splice(J,1),Z=Q?this.runs.get(Q):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,f=Number.NEGATIVE_INFINITY,J,Q=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let W=this.runs.get(this.runQueue[Z]);if(!W||W.status!=="queued")continue;if(W.nextAttemptAt&&W.nextAttemptAt.getTime()>Q){if(!J||W.nextAttemptAt<J)J=W.nextAttemptAt;continue}if(W.priority>f)f=W.priority,$=Z}return{index:$,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch($){if(!$)return;let f=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},f)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let f of this.runs.values())if(f.status==="running")$++;return $}async executeQueuedRun($){let f=$.currentActivity===XV;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:E.RunStarted,run:{...$}});let J=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Q=f?RN($):$.message,Z=await this.routeToTeammate($.agentId,Q,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=Z,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:E.RunCompleted,run:{...$}})}catch(Q){let Z=Q instanceof Error?Q.message:String(Q??"Unknown error");$.error=Z,$.endedAt=new Date;let W=this.members.get($.agentId);if(jV(W,Q))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:E.RunCancelled,run:{...$},reason:Z});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:E.RunFailed,run:{...$}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns($){let f=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!f&&!["running","queued"].includes(J.status))return!1;if($?.status&&J.status!==$.status)return!1;if($?.agentId&&J.agentId!==$.agentId)return!1;return!0}).map((J)=>({...J}))}getRun($){let f=this.runs.get($);return f?{...f}:void 0}async awaitRun($,f=250){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);while(J.status==="queued"||J.status==="running")await HV(f);return{...J}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))await HV($);return this.listRuns()}cancelRun($,f){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=f,J.endedAt=new Date,J.currentActivity="cancelled";let Q=this.runQueue.indexOf($);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:E.RunCancelled,run:{...J},reason:f}),{...J}}recoverActiveRuns($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let Q=this.members.get(J.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:E.RunInterrupted,run:{...J},reason:J.error});continue}let Z=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=Z,J.lastProgressAt=Z,J.lastProgressMessage=$,J.currentActivity=XV,!this.runQueue.includes(J.id))this.runQueue.push(J.id);f.push({...J}),this.emitEvent({type:E.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),f}markStaleRunsInterrupted($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=$,J.endedAt=new Date,J.currentActivity="interrupted",f.push({...J}),this.emitEvent({type:E.RunInterrupted,run:{...J},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),f}sendMessage($,f,J,Q,Z){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let W=this.members.get(f);if(!W)throw Error(`Unknown recipient "${f}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:f,subject:J,body:Q,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:E.TeamMessage,message:{...j}}),W.role==="teammate"&&W.runningCount>0&&W.agent)W.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast($,f,J,Q){let Z=[];for(let W of this.members.values()){if(W.agentId===$)continue;if(W.role==="lead")continue;Z.push(this.sendMessage($,W.agentId,f,J,Q?.taskId))}return Z}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let f={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(f);let J=this.members.get($.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:E.TeamMissionLog,entry:{...f}}),{...f}}createOutcome($){let f={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(f.id,f),this.emitEvent({type:E.OutcomeCreated,outcome:{...f}}),{...f}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let f=this.outcomes.get($.outcomeId);if(!f)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!f.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),f.status==="draft")f.status="in_review";return this.emitEvent({type:E.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment($){let f=this.outcomeFragments.get($.fragmentId);if(!f)throw Error(`Fragment "${$.fragmentId}" was not found`);return f.status=$.approved?"reviewed":"rejected",f.reviewedBy=$.reviewedBy,f.reviewedAt=new Date,this.emitEvent({type:E.OutcomeFragmentReviewed,fragment:{...f}}),{...f}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((f)=>f.outcomeId===$).map((f)=>({...f}))}finalizeOutcome($){let f=this.outcomes.get($);if(!f)throw Error(`Outcome "${$}" was not found`);let J=this.listOutcomeFragments($);for(let Q of f.requiredSections)if(!J.some((W)=>W.section===Q&&W.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return f.status="finalized",f.finalizedAt=new Date,this.emitEvent({type:E.OutcomeFinalized,outcome:{...f}}),{...f}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(f){if(!wQ(f))throw f}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,f]of this.members.entries())if(f.role==="teammate")this.members.delete($)}requireTask($){let f=this.tasks.get($);if(!f)throw Error(`Task "${$}" was not found`);return f}assertDependenciesResolved($){let f=this.getUnresolvedDependencies($);if(f.length>0)throw Error(`Task "${$.id}" is blocked by "${f[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((f)=>{let J=this.tasks.get(f);return!J||J.status!=="completed"})}trackMeaningfulEvent($,f){if(this.recordRunActivityFromAgentEvent($,f),f.type==="iteration_end"&&f.hadToolCalls){this.recordProgressStep($,`Completed iteration ${f.iteration} with ${f.toolCallCount} tool call(s)`);return}if(f.type==="content_end"&&f.contentType==="tool"&&!f.error){this.recordProgressStep($,`Finished tool "${f.toolName??"unknown"}"`);return}if(f.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${f.iterations} iterations)`});return}if(f.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:f.error.message})}recordRunActivityFromAgentEvent($,f){let J;switch(f.type){case"iteration_start":J=`iteration_${f.iteration}_started`;break;case"content_start":if(f.contentType==="tool")J=`running_tool_${f.toolName??"unknown"}`;break;case"content_end":if(f.contentType==="tool")J=f.error?this.formatProgressErrorActivity(`tool_${f.toolName??"unknown"}_error`,f.error):`finished_tool_${f.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",f.error.message);break;default:break}if(!J)return;for(let Q of this.runs.values()){if(Q.agentId!==$||Q.status!=="running")continue;this.recordRunProgress(Q,J)}}recordRunProgress($,f){let J=new Date;$.heartbeatAt=J,$.lastProgressAt=J,$.lastProgressMessage=f,$.currentActivity=f,this.emitEvent({type:E.RunProgress,run:{...$},message:f})}formatProgressErrorActivity($,f){let J=f.replace(/\s+/g," ").trim();if(J.length===0)return $;let Q=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${$}: ${Q}`}recordProgressStep($,f,J,Q=!1){this.missionStepCounter++;let Z=this.members.get($);if(!Z)return;let W=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!Q&&W<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:J,kind:"progress",summary:f})}buildMailboxNotification($){if($.length===0)return"";let f=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let J of $)f.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),f.push(J.body);return f.push("---"),f.join(`
|
|
506
|
-
`)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function
|
|
505
|
+
${f}`:f,j=J?.continueConversation?await W.agent.continue(Q):await W.agent.run(Q);return this.emitEvent({type:b.TaskEnd,agentId:$,result:j}),this.recordProgressStep($,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:b.TaskEnd,agentId:$,error:Q,messages:W.agent.getMessages()}),!sA(W,Q))this.appendMissionLog({agentId:$,taskId:J?.taskId,kind:"error",summary:Q.message});throw Q}finally{if(W.runningCount--,W.runningCount<=0&&this.members.get($)?.status!=="stopped")W.status="idle"}}startTeammateRun($,f,J){let W=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:W,agentId:$,taskId:J?.taskId,status:"queued",message:f,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(W,Z),this.runQueue.push(W),this.emitEvent({type:b.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let f=this.selectNextDispatchableQueuedRun();$=f.nextDelayedAttemptAt;let J=f.index;if(J<0){this.scheduleQueuedRunDispatch($);return}let[W]=this.runQueue.splice(J,1),Z=W?this.runs.get(W):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,f=Number.NEGATIVE_INFINITY,J,W=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let Q=this.runs.get(this.runQueue[Z]);if(!Q||Q.status!=="queued")continue;if(Q.nextAttemptAt&&Q.nextAttemptAt.getTime()>W){if(!J||Q.nextAttemptAt<J)J=Q.nextAttemptAt;continue}if(Q.priority>f)f=Q.priority,$=Z}return{index:$,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch($){if(!$)return;let f=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},f)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let f of this.runs.values())if(f.status==="running")$++;return $}async executeQueuedRun($){let f=$.currentActivity===oA;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:b.RunStarted,run:{...$}});let J=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let W=f?kN($):$.message,Z=await this.routeToTeammate($.agentId,W,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=Z,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:b.RunCompleted,run:{...$}})}catch(W){let Z=W instanceof Error?W.message:String(W??"Unknown error");$.error=Z,$.endedAt=new Date;let Q=this.members.get($.agentId);if(sA(Q,W))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:b.RunCancelled,run:{...$},reason:Z});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:b.RunFailed,run:{...$}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns($){let f=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!f&&!["running","queued"].includes(J.status))return!1;if($?.status&&J.status!==$.status)return!1;if($?.agentId&&J.agentId!==$.agentId)return!1;return!0}).map((J)=>({...J}))}getRun($){let f=this.runs.get($);return f?{...f}:void 0}async awaitRun($,f=250){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);while(J.status==="queued"||J.status==="running")await eA(f);return{...J}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))await eA($);return this.listRuns()}cancelRun($,f){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=f,J.endedAt=new Date,J.currentActivity="cancelled";let W=this.runQueue.indexOf($);if(W>=0)this.runQueue.splice(W,1);return this.emitEvent({type:b.RunCancelled,run:{...J},reason:f}),{...J}}recoverActiveRuns($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let W=this.members.get(J.agentId);if(!W||W.role!=="teammate"||!W.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:b.RunInterrupted,run:{...J},reason:J.error});continue}let Z=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=Z,J.lastProgressAt=Z,J.lastProgressMessage=$,J.currentActivity=oA,!this.runQueue.includes(J.id))this.runQueue.push(J.id);f.push({...J}),this.emitEvent({type:b.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),f}markStaleRunsInterrupted($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=$,J.endedAt=new Date,J.currentActivity="interrupted",f.push({...J}),this.emitEvent({type:b.RunInterrupted,run:{...J},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),f}sendMessage($,f,J,W,Z){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let Q=this.members.get(f);if(!Q)throw Error(`Unknown recipient "${f}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:f,subject:J,body:W,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:b.TeamMessage,message:{...j}}),Q.role==="teammate"&&Q.runningCount>0&&Q.agent)Q.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast($,f,J,W){let Z=[];for(let Q of this.members.values()){if(Q.agentId===$)continue;if(Q.role==="lead")continue;Z.push(this.sendMessage($,Q.agentId,f,J,W?.taskId))}return Z}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let f={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(f);let J=this.members.get($.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:b.TeamMissionLog,entry:{...f}}),{...f}}createOutcome($){let f={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(f.id,f),this.emitEvent({type:b.OutcomeCreated,outcome:{...f}}),{...f}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let f=this.outcomes.get($.outcomeId);if(!f)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!f.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),f.status==="draft")f.status="in_review";return this.emitEvent({type:b.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment($){let f=this.outcomeFragments.get($.fragmentId);if(!f)throw Error(`Fragment "${$.fragmentId}" was not found`);return f.status=$.approved?"reviewed":"rejected",f.reviewedBy=$.reviewedBy,f.reviewedAt=new Date,this.emitEvent({type:b.OutcomeFragmentReviewed,fragment:{...f}}),{...f}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((f)=>f.outcomeId===$).map((f)=>({...f}))}finalizeOutcome($){let f=this.outcomes.get($);if(!f)throw Error(`Outcome "${$}" was not found`);let J=this.listOutcomeFragments($);for(let W of f.requiredSections)if(!J.some((Q)=>Q.section===W&&Q.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${W}" is missing a reviewed fragment.`);return f.status="finalized",f.finalizedAt=new Date,this.emitEvent({type:b.OutcomeFinalized,outcome:{...f}}),{...f}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(f){if(!ZQ(f))throw f}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,f]of this.members.entries())if(f.role==="teammate")this.members.delete($)}requireTask($){let f=this.tasks.get($);if(!f)throw Error(`Task "${$}" was not found`);return f}assertDependenciesResolved($){let f=this.getUnresolvedDependencies($);if(f.length>0)throw Error(`Task "${$.id}" is blocked by "${f[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((f)=>{let J=this.tasks.get(f);return!J||J.status!=="completed"})}trackMeaningfulEvent($,f){if(this.recordRunActivityFromAgentEvent($,f),f.type==="iteration_end"&&f.hadToolCalls){this.recordProgressStep($,`Completed iteration ${f.iteration} with ${f.toolCallCount} tool call(s)`);return}if(f.type==="content_end"&&f.contentType==="tool"&&!f.error){this.recordProgressStep($,`Finished tool "${f.toolName??"unknown"}"`);return}if(f.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${f.iterations} iterations)`});return}if(f.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:f.error.message})}recordRunActivityFromAgentEvent($,f){let J;switch(f.type){case"iteration_start":J=`iteration_${f.iteration}_started`;break;case"content_start":if(f.contentType==="tool")J=`running_tool_${f.toolName??"unknown"}`;break;case"content_end":if(f.contentType==="tool")J=f.error?this.formatProgressErrorActivity(`tool_${f.toolName??"unknown"}_error`,f.error):`finished_tool_${f.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",f.error.message);break;default:break}if(!J)return;for(let W of this.runs.values()){if(W.agentId!==$||W.status!=="running")continue;this.recordRunProgress(W,J)}}recordRunProgress($,f){let J=new Date;$.heartbeatAt=J,$.lastProgressAt=J,$.lastProgressMessage=f,$.currentActivity=f,this.emitEvent({type:b.RunProgress,run:{...$},message:f})}formatProgressErrorActivity($,f){let J=f.replace(/\s+/g," ").trim();if(J.length===0)return $;let W=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${$}: ${W}`}recordProgressStep($,f,J,W=!1){this.missionStepCounter++;let Z=this.members.get($);if(!Z)return;let Q=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!W&&Q<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:J,kind:"progress",summary:f})}buildMailboxNotification($){if($.length===0)return"";let f=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let J of $)f.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),f.push(J.body);return f.push("---"),f.join(`
|
|
506
|
+
`)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function eA($){return new Promise((f)=>setTimeout(f,$))}function q2($,f){let J=0;for(let W of $){if(!W.startsWith(f))continue;let Z=Number.parseInt(W.slice(f.length),10);if(Number.isFinite(Z))J=Math.max(J,Z)}return J}function jQ($,f){switch(f.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(f.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if(f.type==="run_failed")J=f.run.error;else if(f.type==="run_cancelled"||f.type==="run_interrupted")J=f.run.error??f.reason;$.activeTeamRunIds.delete(f.run.id),$.pendingTeamRunUpdates.push({runId:f.run.id,agentId:f.run.agentId,taskId:f.run.taskId,status:f.type.replace("run_",""),error:J,iterations:f.run.result?.iterations}),q5($);break}default:break}}async function HQ($,f,J){switch(f.type){case"run_progress":await J("onTeamTaskProgress",$,f.run.agentId,f.message,{kind:f.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(f.event.type==="content_start"&&f.event.contentType==="text"&&typeof f.event.text==="string"){let W=f.event.text.replace(/\s+/g," ").trim().slice(0,120);if(W)await J("onTeamTaskProgress",$,f.agentId,W,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",$,f.agentId,f.message);break;case"task_end":{if(f.error)await J("onTeamTaskEnd",$,f.agentId,"failed",`[error] ${f.error.message}`,void 0,f.messages);else if(f.result?.finishReason==="aborted")await J("onTeamTaskEnd",$,f.agentId,"cancelled","[done] aborted",f.result,f.result.messages);else await J("onTeamTaskEnd",$,f.agentId,"completed",`[done] ${f.result?.finishReason??"completed"}`,f.result,f.result?.messages);break}default:break}}function XQ($,f,J,W){if(!$.runtime.teamRuntime)return;let Z=$.runtime.teamRuntime.getTeamName();W({type:"team_progress",payload:{sessionId:f,teamName:Z,lifecycle:y2({teamName:Z,sessionId:f,event:J}),summary:M2(Z,$.runtime.teamRuntime.exportState())}})}function pJ($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function YQ($,f){if($.aborting)return!1;if(!(f==="completed"||f==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&pJ($)}function q5($){let f=$.teamRunWaiters.splice(0);for(let J of f)J()}async function AQ($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let f=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,f}if($.activeTeamRunIds.size===0)return[];await new Promise((f)=>{$.teamRunWaiters.push(f)})}}function VQ($,f){let J=f.map((Q)=>{let j=[`- ${Q.runId} (${Q.agentId}) -> ${Q.status}`];if(Q.taskId)j.push(` task=${Q.taskId}`);if(typeof Q.iterations==="number")j.push(` iterations=${Q.iterations}`);if(Q.error)j.push(` error=${Q.error}`);return j.join("")}),W=$.activeTeamRunIds.size,Z=W>0?`There are still ${W} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return rJ(`System-delivered teammate async run updates:
|
|
507
507
|
${J.join(`
|
|
508
508
|
`)}
|
|
509
509
|
|
|
510
|
-
${Z}`,$.config.mode)}function
|
|
511
|
-
`,"utf8"),
|
|
510
|
+
${Z}`,$.config.mode)}function rJ($,f){return IN($,f==="plan"?"plan":f==="yolo"?"yolo":"act")}var BQ=4;class v${adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,f={}){this.adapter=$;this.manifestStore=new JQ($,f.messagesArtifactUploader,f.logger),this.teamChildren=new y5($,this.manifestStore,(J,W,Z)=>this.toPersistedMessages(J,W,Z),v$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,f,J){if(!$)return;return f?Y6(f.messages,f,J):X6($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,f){this.manifestStore.writeSessionManifest($,f)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let f=$.startedAt??s(),J=$.sessionId.trim(),W=J.length>0?J:`${Date.now()}_${mN(5)}`,Z=this.manifestStore.artifacts.sessionMessagesPath(W),Q=this.manifestStore.artifacts.sessionManifestPath(W),j=l8({metadata:$.metadata,prompt:$.prompt}),H={version:1,session_id:W,source:$.source,pid:$.pid,started_at:f,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:j,messages_path:Z};return await this.adapter.upsertSession({sessionId:W,source:$.source,pid:$.pid,startedAt:f,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:H.prompt??null,metadata:j1(H.metadata),hookPath:"",messagesPath:Z,updatedAt:s()}),this.manifestStore.initializeMessagesFile(W,Z,f),this.manifestStore.writeSessionManifest(Q,H),{manifestPath:Q,messagesPath:Z,manifest:H}}async updateSessionStatus($,f,J){let W;if((await lH(()=>this.adapter.getSession($),async(Q)=>{return W=W0(f)?void 0:s(),this.adapter.updateSession({sessionId:$,status:f,endedAt:W??null,exitCode:W0(f)?null:typeof J==="number"?J:null,expectedStatusLock:Q.statusLock})},BQ)).updated){if(f==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:W}}return{updated:!1}}async updateSession($){for(let f=0;f<BQ;f++){let J=await this.adapter.getSession($.sessionId);if(!J)return{updated:!1};let W=J.metadata??void 0,Z=$.metadata!==void 0?j1($.metadata)??{}:j1(W)??{},Q=i1(typeof W?.title==="string"?W.title:void 0),j=$.title!==void 0?i1($.title):Q??CZ($.prompt);if(j)Z.title=j;else delete Z.title;let H=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:H?Object.keys(Z).length>0?Z:null:void 0,title:j,expectedStatusLock:J.statusLock})).updated)continue;let{path:Y,manifest:A}=this.manifestStore.readManifestFile($.sessionId);if(A){if($.prompt!==void 0)A.prompt=$.prompt??void 0;let V=$.metadata!==void 0?j1($.metadata)??{}:j1(A.metadata)??{};if(j)V.title=j;A.metadata=Object.keys(V).length>0?V:void 0,this.manifestStore.writeSessionManifest(Y,A)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,f){return this.teamChildren.appendSubagentHookAudit(f),Promise.resolve()}persistSessionMessages($,f,J){let W=X6(f);return this.manifestStore.persistSessionMessages($,W,J)}applySubagentStatus($,f){return this.teamChildren.applySubagentStatus($,f)}applySubagentStatusBySessionId($,f){return this.teamChildren.applySubagentStatusBySessionId($,f)}applyStatusToRunningChildSessions($,f){return this.teamChildren.applyStatusToRunningChildSessions($,f)}onTeamTaskStart($,f,J){return this.teamChildren.onTeamTaskStart($,f,J)}onTeamTaskEnd($,f,J,W,Z,Q){return this.teamChildren.onTeamTaskEnd($,f,J,W,Z,Q)}onTeamTaskProgress($,f,J,W){return this.teamChildren.onTeamTaskProgress($,f,J,W)}handleSubAgentStart($,f){return this.teamChildren.handleSubAgentStart($,f)}handleSubAgentEnd($,f){return this.teamChildren.handleSubAgentEnd($,f)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="EPERM"}}async reconcileDeadRunningSession($){if(W0($.status)===!1||this.isPidAlive($.pid))return $;let f=s(),J=v$.STALE_REASON;for(let W=0;W<BQ;W++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return;if(W0(Z.status)===!1)return Z;let Q={...Z.metadata??{},terminal_marker:J,terminal_marker_at:f,terminal_marker_pid:Z.pid,terminal_marker_source:v$.STALE_SOURCE},j=await this.adapter.updateSession({sessionId:Z.sessionId,status:"failed",endedAt:f,exitCode:1,metadata:Q,expectedStatusLock:Z.statusLock});if(!j.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(Z.sessionId,"failed");let H=dH(Z,{status:"failed",endedAt:f,exitCode:1,metadata:Q}),{path:X}=this.manifestStore.readManifestFile(Z.sessionId);return this.manifestStore.writeSessionManifest(X,H),this.manifestStore.appendStaleSessionHookLog(f,Z.sessionId,Z.pid,J,v$.STALE_SOURCE),{...Z,status:"failed",endedAt:f,exitCode:1,metadata:Q,statusLock:j.statusLock,updatedAt:f}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let f=Math.max(1,Math.floor($)),J=Math.min(f*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,f).map((Z)=>{let Q=j1(Z.metadata??void 0),j=this.manifestStore.readSessionManifest(Z.sessionId),H=i1(typeof j?.metadata?.title==="string"?j.metadata.title:void 0),X=H?{...Q??{},title:H}:Q;return{...Z,metadata:X}})}async reconcileDeadSessions($=2000){let f=Math.max(1,Math.floor($)),J=(await Promise.all(["idle","running","pending"].map((Z)=>this.adapter.listSessions({limit:f,status:Z})))).flat(),W=0;for(let Z of J){let Q=await this.reconcileDeadRunningSession(Z);if(Q&&Q.status!==Z.status)W++}return W}async deleteSession($){let f=$.trim();if(!f)throw Error("session id is required");let J=await this.adapter.getSession(f);if(!J)return{deleted:!1};if(await this.adapter.deleteSession(f,!1),!J.isSubagent){let W=await this.adapter.listSessions({limit:2000,parentSessionId:f});await this.adapter.deleteSession(f,!0),await Promise.allSettled(W.map(async(Z)=>{await eZ(Z.cwd,Z.sessionId),VJ(Z.messagesPath),VJ(this.manifestStore.artifacts.sessionManifestPath(Z.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(Z.sessionId)}))}if(await eZ(J.cwd,f),VJ(J.messagesPath),VJ(this.manifestStore.artifacts.sessionManifestPath(f,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(f);else{let W=new Set([this.manifestStore.artifacts.sessionArtifactsDir(f)]);for(let Z of[J.messagesPath])if(typeof Z==="string"&&Z.trim().length>0)W.add(xN(Z));for(let Z of W)this.manifestStore.artifacts.removeDir(Z)}return{deleted:!0}}}function GQ(){return new Date().toISOString()}function ZV($,f){let J=`${$}.tmp`;uN(J,`${JSON.stringify(f,null,2)}
|
|
511
|
+
`,"utf8"),vN(J,$)}class QV{sessionsDirPath;constructor($=cN()){this.sessionsDirPath=$}ensureSessionsDir(){if(!KQ(this.sessionsDirPath))gN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return WV(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return WV(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!KQ($))return{version:1,sessions:{}};try{let f=JSON.parse(JV($,"utf8"));if(f?.version===1&&f.sessions)return f}catch{}return{version:1,sessions:{}}}writeIndex($){ZV(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!KQ($))return{version:1,nextId:1,requests:[]};try{let f=JSON.parse(JV($,"utf8"));if(f?.version===1&&typeof f.nextId==="number"&&Array.isArray(f.requests))return f}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){ZV(this.spawnQueuePath(),$)}async upsertSession($){let f=this.readIndex();f.sessions[$.sessionId]=$,this.writeIndex(f)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((f)=>$.parentSessionId!==void 0?f.parentSessionId===$.parentSessionId:!0).filter((f)=>$.status!==void 0?f.status===$.status:!0).sort((f,J)=>J.startedAt.localeCompare(f.startedAt)).slice(0,$.limit)}async updateSession($){let f=this.readIndex(),J=f.sessions[$.sessionId];if(!J)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&J.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let W=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:J.statusLock,Z={...J,status:$.status??J.status,endedAt:$.endedAt!==void 0?$.endedAt:J.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:J.exitCode??null,prompt:$.prompt!==void 0?$.prompt:J.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:J.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:J.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:J.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:J.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:J.conversationId??null,statusLock:W,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:GQ()};if($.setRunning)Z.status="running",Z.endedAt=null,Z.exitCode=null;return f.sessions[$.sessionId]=Z,this.writeIndex(f),{updated:!0,statusLock:Z.statusLock}}async deleteSession($,f){let J=this.readIndex();if(!J.sessions[$])return!1;if(delete J.sessions[$],f){for(let Z of Object.values(J.sessions))if(Z.parentSessionId===$)delete J.sessions[Z.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest($){let f=this.readQueue();f.requests.push({id:f.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:GQ()}),f.nextId+=1,this.writeQueue(f)}async claimSpawnRequest($,f){let J=this.readQueue(),W=J.requests.find((Z)=>Z.rootSessionId===$&&Z.parentAgentId===f&&!Z.consumedAt);if(!W)return;return W.consumedAt=GQ(),this.writeQueue(J),W.task}}class PQ extends v${constructor($,f={}){super(new QV($),f)}ensureSessionsDir(){return super.ensureSessionsDir()}}var XV={};w(XV,{CoreSessionService:()=>F$});import{existsSync as dN,mkdirSync as lN}from"node:fs";import{resolveSessionDataDir as pN}from"@cline/shared/storage";var FQ=`
|
|
512
512
|
session_id AS sessionId,
|
|
513
513
|
source,
|
|
514
514
|
pid,
|
|
@@ -535,32 +535,32 @@ ${Z}`,$.config.mode)}function y6($,f){return LN($,f==="plan"?"plan":f==="yolo"?"
|
|
|
535
535
|
metadata_json AS metadata,
|
|
536
536
|
hook_path AS hookPath,
|
|
537
537
|
messages_path AS messagesPath,
|
|
538
|
-
updated_at AS updatedAt`;function
|
|
538
|
+
updated_at AS updatedAt`;function UQ($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let f=$.metadata;if(typeof f==="string"&&f.trim())try{let J=JSON.parse(f);$.metadata=J&&typeof J==="object"&&!Array.isArray(J)?J:null}catch{$.metadata=null}else $.metadata=null;return $}function RQ($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function jV($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class HV{store;sessionsDirPath;constructor($,f=pN()){this.store=$;this.sessionsDirPath=f}ensureSessionsDir(){if(!dN(this.sessionsDirPath))lN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
539
539
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
540
540
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
541
541
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
542
542
|
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
543
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.isSubagent?1:0,$.prompt??null,
|
|
543
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.isSubagent?1:0,$.prompt??null,RQ($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let f=this.store.queryOne(`SELECT ${FQ} FROM sessions WHERE session_id = ?`,[$]);return f?UQ(f):void 0}async listSessions($){let f=[],J=[];if($.parentSessionId)f.push("parent_session_id = ?"),J.push($.parentSessionId);if($.status)f.push("status = ?"),J.push($.status);let W=f.length>0?`WHERE ${f.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${FQ}
|
|
544
544
|
FROM sessions
|
|
545
|
-
${
|
|
545
|
+
${W}
|
|
546
546
|
ORDER BY started_at DESC
|
|
547
|
-
LIMIT ?`,[...J,$.limit]).map(
|
|
547
|
+
LIMIT ?`,[...J,$.limit]).map(UQ)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
|
|
548
548
|
SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
|
|
549
549
|
parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
|
|
550
550
|
prompt = COALESCE(prompt, ?)
|
|
551
|
-
WHERE session_id = ? AND status_lock = ?`,[s(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let f=[],J=[];if($.status!==void 0)f.push("status = ?"),J.push($.status);if($.endedAt!==void 0)f.push("ended_at = ?"),J.push($.endedAt);if($.exitCode!==void 0)f.push("exit_code = ?"),J.push($.exitCode);if($.prompt!==void 0)f.push("prompt = ?"),J.push($.prompt??null);if($.metadata!==void 0)f.push("metadata_json = ?"),J.push(
|
|
551
|
+
WHERE session_id = ? AND status_lock = ?`,[s(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let f=[],J=[];if($.status!==void 0)f.push("status = ?"),J.push($.status);if($.endedAt!==void 0)f.push("ended_at = ?"),J.push($.endedAt);if($.exitCode!==void 0)f.push("exit_code = ?"),J.push($.exitCode);if($.prompt!==void 0)f.push("prompt = ?"),J.push($.prompt??null);if($.metadata!==void 0)f.push("metadata_json = ?"),J.push(RQ($.metadata));if($.parentSessionId!==void 0)f.push("parent_session_id = ?"),J.push($.parentSessionId??null);if($.parentAgentId!==void 0)f.push("parent_agent_id = ?"),J.push($.parentAgentId??null);if($.agentId!==void 0)f.push("agent_id = ?"),J.push($.agentId??null);if($.conversationId!==void 0)f.push("conversation_id = ?"),J.push($.conversationId??null);if(f.length===0){let j=await this.getSession($.sessionId);return{updated:!!j,statusLock:j?.statusLock??0}}let W=0;if($.expectedStatusLock!==void 0)W=$.expectedStatusLock+1,f.push("status_lock = ?"),J.push(W);f.push("updated_at = ?"),J.push(s());let Z=`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`;if(J.push($.sessionId),$.expectedStatusLock!==void 0)Z+=" AND status_lock = ?",J.push($.expectedStatusLock);if((this.store.run(Z,J).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)W=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:W}}async deleteSession($,f){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
|
|
552
552
|
VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,s()])}async claimSpawnRequest($,f){let J=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
|
|
553
553
|
WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
|
|
554
|
-
ORDER BY id ASC LIMIT 1`,[$,f]);if(!J||typeof J.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[s(),J.id]),J.task??void 0}}class
|
|
554
|
+
ORDER BY id ASC LIMIT 1`,[$,f]);if(!J||typeof J.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[s(),J.id]),J.task??void 0}}class F$ extends v${store;constructor($,f={}){super(new HV($,f.sessionArtifactsDir),f);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
555
555
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
556
556
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
557
557
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
558
558
|
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
559
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"","",$.messagesPath,s()])}}function
|
|
560
|
-
`).map((W)=>W.trim()).filter(Boolean).filter((W)=>W.startsWith("HOOK_CONTROL\t")).map((W)=>W.slice(13)),Z=Q.length>0?Q[Q.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse subprocess stdout JSON"}}}function xN($,f){let J=$ instanceof Error?$:Error(String($)),Q=J,Z=f.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${Z}": ${J.message}`)}async function mN($,f){let J=$.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,Z)=>{let W=(j)=>{J.off("error",W);let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Q();return}Z(j)};J.once("error",W),J.end(f,(j)=>{if(J.off("error",W),j){let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Q();return}Z(j);return}Q()})})}async function D8($,f){let J=bN(f.command,{env:f.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!f.detached,Z=EN(J[0],J.slice(1),{cwd:f.cwd,env:kN(f.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q}),W=new Promise((B)=>{Z.once("spawn",()=>{try{f.onSpawn?.({command:J,pid:Z.pid??void 0,detached:Q})}catch{}B()})}),j=new Promise((B,G)=>{Z.once("error",(K)=>{G(xN(K,J))})});if(await mN(Z,JSON.stringify($)),Q){await Promise.race([W,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",H="",Y=!1,V;Z.stdout.on("data",(B)=>{X+=B.toString()}),Z.stderr.on("data",(B)=>{H+=B.toString()});let A=new Promise((B)=>{if((f.timeoutMs??0)>0)V=setTimeout(()=>{Y=!0,Z.kill("SIGKILL")},f.timeoutMs);Z.once("close",(G)=>{if(V)clearTimeout(V);let{parsedJson:K,parseError:D}=IN(X);B({exitCode:G,stdout:X,stderr:H,parsedJson:K,parseError:D,timedOut:Y})})});return await Promise.race([A,j])}var vN=Q2.object({contextModification:Q2.string().optional(),cancel:Q2.boolean().optional(),review:Q2.boolean().optional(),errorMessage:Q2.string().optional(),context:Q2.string().optional(),overrideInput:Q2.unknown().optional()}).passthrough();var uN=["agent","hook"];async function L8($,f={}){let J=f.command??uN;return await D8($,{command:J,cwd:f.cwd,env:f.env,detached:f.detached,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn})}function TV($){return $ instanceof Error?$:Error(String($))}function cN($){if(!$||typeof $!=="object")return;let f=vN.safeParse($);if(!f.success)return;let J=f.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let Z=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Z,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function NV($){if(!$||typeof $!=="object")return{};let f={};for(let[J,Q]of Object.entries($))if(typeof Q==="string")f[J]=Q;else f[J]=JSON.stringify(Q);return f}function E$($,f,J){let Q=J.env??process.env,Z=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",W=J.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:gN(J.sessionContext,{hookName:$,conversationId:f.conversationId,agentId:f.agentId,parentAgentId:f.parentAgentId}),workspaceRoots:W?[W]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function dN($){return{name:$.name,message:$.message,stack:$.stack}}function lN($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function pN($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function rN($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function iN($){return{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}function nN($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}async function Z2($,f){try{let J=await L8($,{command:f.command,cwd:f.cwd,env:f.env,detached:!0,onSpawn:f.onSpawn});f.onDispatch?.({payload:$,result:J,detached:!0})}catch(J){f.onDispatchError?.(TV(J),$)}}function Y5($={}){return{hooks:{beforeRun:async(X)=>{let H=pN(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let V={...E$("agent_resume",H,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await Z2(V,$)}else{let V={...E$("agent_start",H,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await Z2(V,$)}return},beforeTool:async(X)=>{let H={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},Y={...E$("tool_call",H,$),hookName:"tool_call",iteration:X.snapshot.iteration,tool_call:{id:X.toolCall.toolCallId,name:X.toolCall.toolName,input:X.input},preToolUse:{toolName:X.toolCall.toolName,parameters:NV(X.input)}};try{let V=await L8(Y,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:Y,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 nN(cN(V?.parsedJson))}catch(V){$.onDispatchError?.(TV(V),Y);return}},afterTool:async(X)=>{let H=iN(X),Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...E$("tool_result",Y,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:H,postToolUse:{toolName:H.name,parameters:NV(H.input),result:typeof H.output==="string"?H.output:JSON.stringify(H.output),success:!H.error,executionTimeMs:H.durationMs}};await Z2(V,$);return},afterRun:async({snapshot:X,result:H})=>{let Y={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(H.status==="completed"){let B={...E$("agent_end",Y,$),hookName:"agent_end",iteration:H.iterations,turn:{outputText:H.outputText,status:H.status},taskComplete:{taskMetadata:{}}};await Z2(B,$);return}let V=H.status==="aborted"||lN(H.error?.message)?"agent_abort":"agent_error",A=V==="agent_error"?{...E$(V,Y,$),hookName:V,iteration:H.iterations,error:dN(H.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...E$(V,Y,$),hookName:V,reason:H.error?.message,taskCancel:{taskMetadata:{}}};await Z2(A,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let H={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},Y={...E$("prompt_submit",H,$),hookName:"prompt_submit",userPromptSubmit:{prompt:rN(X.message.content),attachments:[]}};await Z2(Y,$)}},shutdown:async({agentId:X,conversationId:H,parentAgentId:Y,reason:V})=>{let A={...E$("session_shutdown",{agentId:X,conversationId:H,parentAgentId:Y},$),hookName:"session_shutdown",reason:V};await Z2(A,$)}}}pQ();var yV={};y(yV,{registerRemoteConfigSessionBlobUpload:()=>B5,readRemoteConfigSessionBlobUploadMetadata:()=>rQ,prepareRemoteConfigCoreIntegration:()=>nQ,createRemoteConfigSessionMessagesArtifactUploader:()=>iQ,buildRemoteConfigSessionBlobUploadMetadata:()=>V5,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>A5});import{buildRemoteConfigSessionBlobUploadMetadata as V5,clearRemoteConfigSessionBlobUpload as aN,createClineTelemetryServiceConfig as tN,createSessionId as sN,createRemoteConfigSessionMessagesArtifactUploader as oN,prepareRemoteConfigRuntime as eN,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as A5,readRemoteConfigSessionBlobUploadMetadata as rQ,registerRemoteConfigSessionBlobUpload as B5}from"@cline/shared";function $T($,f){let J=$.telemetry||f.telemetryService?{...f.telemetryService??{},...$.telemetry??{}}:void 0;if(!J)return;return z$(tN(J)).telemetry}function iQ(){let $=oN();return{async uploadMessagesFile(f){await $.uploadMessagesFile(f)}}}async function nQ($){let f=await eN($),J=$T(f,$),Q=[f.pluginDefinition],Z=f.claims?.subject,W=V5(f.bundle?.remoteConfig,Z),j;return{prepared:f,extensions:Q,telemetry:J,applyToStartSessionInput(X){let H=X.config.extensions??[],Y=X.config.telemetry,V=W?X.config.sessionId?.trim()||sN():X.config.sessionId;if(V&&W)j=V;let A=V&&W?B5(V,f.bundle?.remoteConfig,Z):void 0,B=A?{...X.sessionMetadata??{},[A5]:A}:X.sessionMetadata;return{...X,...B?{sessionMetadata:B}:{},config:{...X.config,...V?{sessionId:V}:{},extensions:[...H,...Q],telemetry:J??Y}}},async dispose(){if(j)aN(j)}}}var IV={};y(IV,{createTeamName:()=>G5,DefaultRuntimeBuilder:()=>_8});import{hasRuntimeConfigExtension as KT}from"@cline/shared";import{nanoid as FT}from"nanoid";O$();var bV={};y(bV,{createLocalTeamStore:()=>oQ,SqliteTeamStore:()=>W2,FileTeamStore:()=>C6});import{appendFileSync as fT,existsSync as O8,mkdirSync as wV,readdirSync as JT,readFileSync as SV,renameSync as QT,writeFileSync as ZT}from"node:fs";import{join as aQ}from"node:path";import{resolveTeamDataDir as WT}from"@cline/shared/storage";function hV(){return new Date().toISOString()}function tQ($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function CV($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class C6{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??WT()}init(){this.ensureTeamDir()}listTeamNames(){if(!O8(this.teamDirPath))return[];return JT(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>O8(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let f=this.readEnvelope($);return f?.teamState?CV(f.teamState):void 0}readHistory($,f=200){let J=this.historyPath($);if(!O8(J))return[];return SV(J,"utf8").split(`
|
|
561
|
-
`).map((
|
|
562
|
-
`,"utf8")}persistRuntime($,f,J){this.ensureTeamSubdir($);let
|
|
563
|
-
`,"utf8"),
|
|
559
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"","",$.messagesPath,s()])}}function rN($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let f=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(f==="local"||f==="hub"||f==="remote")return f;return"auto"}var iJ,nJ;function iN($,f){if($!=="auto"&&$!=="hub")return;if(f.hub?.endpoint?.trim())return;c4(f.hub?.workspaceRoot?.trim()||f.hub?.cwd?.trim()||process.cwd())}async function nN($){await $.reconcileDeadSessions?.().catch(()=>{})}function VV($){try{let f=new G$;return f.init(),new F$(f,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(f){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),AV($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:f,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new PQ(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function YV($,f,J){return new U$({sessionService:J??$.sessionService??VV($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:f,fetch:$.fetch})}async function DQ($){if(iJ)return iJ;if(nJ)return await nJ;return nJ=(async()=>{return iJ=VV($),await nN(iJ),iJ})().finally(()=>{nJ=void 0}),await nJ}async function S2($){let f=h1($.distinctId);$.telemetry?.setDistinctId(f);let J=rN($);if(iN(J,$),J==="remote"){let W=$.remote?.endpoint?.trim();if(!W)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:W}),new N2({endpoint:W,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(J==="hub"){let W=$.hub?.endpoint?.trim(),Z=W||await b1({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!Z)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:Z,explicitEndpoint:W||void 0}),new m$({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(J==="auto"){let W=await G8({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(W){$.logger?.log("Using discovered local hub runtime host",{url:W});let Z=new m$({url:W,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await Z.connect(),Z}catch(Q){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:Q}),AV($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:Q,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),YV($,f)}return YV($,f)}class aJ{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,f,J,W,Z,Q,j,H,X){this.clientName=f,this.runtimeAddress=J,this.host=$,this.prepare=W,this.capabilities=Z,this.logger=Q,this.telemetry=j,this.distinctId=H,this.settings=BA($),this.pendingPrompts=KA($),this.automation=new S9(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=X?new gJ({workspaceRoot:X.workspaceRoot??process.cwd(),specs:{cronSpecsDir:X.cronSpecsDir??X.cronDir,scope:TY(X.cronScope),workspaceRoot:X.workspaceRoot},runtimeHandlers:NY({host:$,getExtensionContext:()=>J5({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:X.dbPath,logger:X.logger,pollIntervalMs:X.pollIntervalMs,claimLeaseSeconds:X.claimLeaseSeconds,globalMaxConcurrency:X.globalMaxConcurrency,watcherDebounceMs:X.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((Y)=>{if(Y.type!=="ended")return;this.disposeSessionBootstrap(Y.payload.sessionId)})}static async create($={}){let f=R0($.capabilities),J=await S2({...$,capabilities:f}),W=zY($.automation),Z=new aJ(J,$.clientName,J.runtimeAddress,$.prepare,f,$.logger,$.telemetry,$.distinctId,W?{...W,logger:$.logger}:void 0);if(W&&W.autoStart!==!1)await Z.automation.start();return Z}async disposeSessionBootstrap($){let f=this.activeSessionBootstraps.get($);if(!f)return;this.activeSessionBootstraps.delete($),await Promise.resolve(f.dispose?.())}async start($){let f=GA($),J=await this.prepare?.(f);try{let W=J?await J.applyToStartSessionInput(f):f,Z=await this.host.startSession(u9(W,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>J5({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(Z.sessionId))this.activeSessionBootstraps.set(Z.sessionId,J);else await Promise.resolve(J.dispose?.());return PA({input:W,sessionId:Z.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),Z}catch(W){throw await Promise.resolve(J?.dispose?.()),W}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let f=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(f.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await z5(this.host,$);list=async($=200,f={})=>await this.listHistory({...f,limit:$});delete=async($)=>{let f=await this.host.deleteSession($);if(f)await this.disposeSessionBootstrap($);return f};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let f=$.start?u9($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>J5({automationService:this.automationService,automation:this.automation,context:J,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:f})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,f){return this.host.subscribe($,f)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}var GV={};w(GV,{resolvePluginSkillDirectoriesFromPaths:()=>e1,resolvePluginConfigSearchPaths:()=>t8,resolveAndLoadAgentPlugins:()=>Q2,resolveAgentPluginPaths:()=>o1,loadAgentPluginsFromPathsWithDiagnostics:()=>s1,loadAgentPluginsFromPaths:()=>K6,loadAgentPluginFromPath:()=>n8,discoverPluginModulePaths:()=>s8});var UV={};w(UV,{toHookConfigFileName:()=>$J,runSubprocessEvent:()=>h2,runHook:()=>E2,resolveHooksConfigSearchPaths:()=>o8,parseHookEventPayload:()=>C2,mergeAgentHooks:()=>Wf,listHookConfigFiles:()=>Y1,createSubprocessHooks:()=>h5,createHookConfigFileHooks:()=>fJ,createHookConfigFileExtension:()=>Y2,createHookAuditHooks:()=>X2,createAgentHooksExtension:()=>j2,HookEventPayloadSchema:()=>S5,HookEventNameSchema:()=>w5,HookConfigFileName:()=>H2,HOOK_CONFIG_FILE_EVENT_MAP:()=>e8,HOOKS_CONFIG_DIRECTORY_NAME:()=>L6});import{HookEventNameSchema as w5,HookEventPayloadSchema as S5,parseHookEventPayload as C2,resolveHookSessionContext as fM}from"@cline/shared";import{z as Pf}from"zod";import{spawn as aN}from"node:child_process";import{augmentNodeCommandForDebug as tN,withResolvedClineBuildEnv as sN}from"@cline/shared";function oN($){let f=$.trim();if(!f)return{};let W=f.split(`
|
|
560
|
+
`).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),Z=W.length>0?W[W.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse subprocess stdout JSON"}}}function eN($,f){let J=$ instanceof Error?$:Error(String($)),W=J,Z=f.join(" ");if(W.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${Z}": ${J.message}`)}async function $M($,f){let J=$.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((W,Z)=>{let Q=(j)=>{J.off("error",Q);let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){W();return}Z(j)};J.once("error",Q),J.end(f,(j)=>{if(J.off("error",Q),j){let H=j.code;if(H==="EPIPE"||H==="ERR_STREAM_DESTROYED"){W();return}Z(j);return}W()})})}async function h2($,f){let J=tN(f.command,{env:f.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!f.detached,Z=aN(J[0],J.slice(1),{cwd:f.cwd,env:sN(f.env),stdio:W?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W}),Q=new Promise((B)=>{Z.once("spawn",()=>{try{f.onSpawn?.({command:J,pid:Z.pid??void 0,detached:W})}catch{}B()})}),j=new Promise((B,K)=>{Z.once("error",(G)=>{K(eN(G,J))})});if(await $M(Z,JSON.stringify($)),W){await Promise.race([Q,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let H="",X="",Y=!1,A;Z.stdout.on("data",(B)=>{H+=B.toString()}),Z.stderr.on("data",(B)=>{X+=B.toString()});let V=new Promise((B)=>{if((f.timeoutMs??0)>0)A=setTimeout(()=>{Y=!0,Z.kill("SIGKILL")},f.timeoutMs);Z.once("close",(K)=>{if(A)clearTimeout(A);let{parsedJson:G,parseError:R}=oN(H);B({exitCode:K,stdout:H,stderr:X,parsedJson:G,parseError:R,timedOut:Y})})});return await Promise.race([V,j])}var JM=Pf.object({contextModification:Pf.string().optional(),cancel:Pf.boolean().optional(),review:Pf.boolean().optional(),errorMessage:Pf.string().optional(),context:Pf.string().optional(),overrideInput:Pf.unknown().optional()}).passthrough();var WM=["agent","hook"];async function E2($,f={}){let J=f.command??WM;return await h2($,{command:J,cwd:f.cwd,env:f.env,detached:f.detached,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn})}function FV($){return $ instanceof Error?$:Error(String($))}function ZM($){if(!$||typeof $!=="object")return;let f=JM.safeParse($);if(!f.success)return;let J=f.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let Z=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Z,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function PV($){if(!$||typeof $!=="object")return{};let f={};for(let[J,W]of Object.entries($))if(typeof W==="string")f[J]=W;else f[J]=JSON.stringify(W);return f}function u$($,f,J){let W=J.env??process.env,Z=W.CLINE_USER_ID?.trim()||W.USER?.trim()||"unknown",Q=J.cwd||process.cwd();return{clineVersion:W.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:fM(J.sessionContext,{hookName:$,conversationId:f.conversationId,agentId:f.agentId,parentAgentId:f.parentAgentId}),workspaceRoots:Q?[Q]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function QM($){return{name:$.name,message:$.message,stack:$.stack}}function jM($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function HM($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function XM($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function YM($){return{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}function AM($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}async function Ff($,f){try{let J=await E2($,{command:f.command,cwd:f.cwd,env:f.env,detached:!0,onSpawn:f.onSpawn});f.onDispatch?.({payload:$,result:J,detached:!0})}catch(J){f.onDispatchError?.(FV(J),$)}}function h5($={}){return{hooks:{beforeRun:async(H)=>{let X=HM(H);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let A={...u$("agent_resume",X,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await Ff(A,$)}else{let A={...u$("agent_start",X,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await Ff(A,$)}return},beforeTool:async(H)=>{let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},Y={...u$("tool_call",X,$),hookName:"tool_call",iteration:H.snapshot.iteration,tool_call:{id:H.toolCall.toolCallId,name:H.toolCall.toolName,input:H.input},preToolUse:{toolName:H.toolCall.toolName,parameters:PV(H.input)}};try{let A=await E2(Y,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:Y,result:A,detached:!1}),A?.timedOut)throw Error("tool_call hook command timed out");if(A?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${A.parseError}`);return AM(ZM(A?.parsedJson))}catch(A){$.onDispatchError?.(FV(A),Y);return}},afterTool:async(H)=>{let X=YM(H),Y={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},A={...u$("tool_result",Y,$),hookName:"tool_result",iteration:H.snapshot.iteration,tool_result:X,postToolUse:{toolName:X.name,parameters:PV(X.input),result:typeof X.output==="string"?X.output:JSON.stringify(X.output),success:!X.error,executionTimeMs:X.durationMs}};await Ff(A,$);return},afterRun:async({snapshot:H,result:X})=>{let Y={agentId:H.agentId,conversationId:H.conversationId??H.runId??H.agentId,parentAgentId:H.parentAgentId??null};if(X.status==="completed"){let B={...u$("agent_end",Y,$),hookName:"agent_end",iteration:X.iterations,turn:{outputText:X.outputText,status:X.status},taskComplete:{taskMetadata:{}}};await Ff(B,$);return}let A=X.status==="aborted"||jM(X.error?.message)?"agent_abort":"agent_error",V=A==="agent_error"?{...u$(A,Y,$),hookName:A,iteration:X.iterations,error:QM(X.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...u$(A,Y,$),hookName:A,reason:X.error?.message,taskCancel:{taskMetadata:{}}};await Ff(V,$)},onEvent:async(H)=>{if(H.type!=="message-added"||H.message.role!=="user")return;let X={agentId:H.snapshot.agentId,conversationId:H.snapshot.conversationId??H.snapshot.runId??H.snapshot.agentId,parentAgentId:H.snapshot.parentAgentId??null},Y={...u$("prompt_submit",X,$),hookName:"prompt_submit",userPromptSubmit:{prompt:XM(H.message.content),attachments:[]}};await Ff(Y,$)}},shutdown:async({agentId:H,conversationId:X,parentAgentId:Y,reason:A})=>{let V={...u$("session_shutdown",{agentId:H,conversationId:X,parentAgentId:Y},$),hookName:"session_shutdown",reason:A};await Ff(V,$)}}}LQ();var DV={};w(DV,{registerRemoteConfigSessionBlobUpload:()=>b5,readRemoteConfigSessionBlobUploadMetadata:()=>OQ,prepareRemoteConfigCoreIntegration:()=>zQ,createRemoteConfigSessionMessagesArtifactUploader:()=>_Q,buildRemoteConfigSessionBlobUploadMetadata:()=>C5,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>E5});import{buildRemoteConfigSessionBlobUploadMetadata as C5,clearRemoteConfigSessionBlobUpload as VM,createClineTelemetryServiceConfig as BM,createSessionId as KM,createRemoteConfigSessionMessagesArtifactUploader as GM,prepareRemoteConfigRuntime as PM,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as E5,readRemoteConfigSessionBlobUploadMetadata as OQ,registerRemoteConfigSessionBlobUpload as b5}from"@cline/shared";function FM($,f){let J=$.telemetry||f.telemetryService?{...f.telemetryService??{},...$.telemetry??{}}:void 0;if(!J)return;return N$(BM(J)).telemetry}function _Q(){let $=GM();return{async uploadMessagesFile(f){await $.uploadMessagesFile(f)}}}async function zQ($){let f=await PM($),J=FM(f,$),W=[f.pluginDefinition],Z=f.claims?.subject,Q=C5(f.bundle?.remoteConfig,Z),j;return{prepared:f,extensions:W,telemetry:J,applyToStartSessionInput(H){let X=H.config.extensions??[],Y=H.config.telemetry,A=Q?H.config.sessionId?.trim()||KM():H.config.sessionId;if(A&&Q)j=A;let V=A&&Q?b5(A,f.bundle?.remoteConfig,Z):void 0,B=V?{...H.sessionMetadata??{},[E5]:V}:H.sessionMetadata;return{...H,...B?{sessionMetadata:B}:{},config:{...H.config,...A?{sessionId:A}:{},extensions:[...X,...W],telemetry:J??Y}}},async dispose(){if(j)VM(j)}}}var yV={};w(yV,{createTeamName:()=>I5,DefaultRuntimeBuilder:()=>I2});import{hasRuntimeConfigExtension as SM}from"@cline/shared";import{nanoid as hM}from"nanoid";Z$();var NV={};w(NV,{createLocalTeamStore:()=>yQ,SqliteTeamStore:()=>Uf,FileTeamStore:()=>tJ});import{appendFileSync as UM,existsSync as b2,mkdirSync as LV,readdirSync as RM,readFileSync as OV,renameSync as DM,writeFileSync as LM}from"node:fs";import{join as TQ}from"node:path";import{resolveTeamDataDir as OM}from"@cline/shared/storage";function _V(){return new Date().toISOString()}function NQ($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function zV($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class tJ{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??OM()}init(){this.ensureTeamDir()}listTeamNames(){if(!b2(this.teamDirPath))return[];return RM(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>b2(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let f=this.readEnvelope($);return f?.teamState?zV(f.teamState):void 0}readHistory($,f=200){let J=this.historyPath($);if(!b2(J))return[];return OV(J,"utf8").split(`
|
|
561
|
+
`).map((W)=>W.trim()).filter(Boolean).map((W)=>{try{return JSON.parse(W)}catch{return}}).filter((W)=>W!==void 0).reverse().slice(0,f)}loadRuntime($){let f=this.readEnvelope($);return{state:f?.teamState?zV(f.teamState):void 0,teammates:f?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,f){this.ensureTeamSubdir($),UM(this.historyPath($),`${JSON.stringify({ts:_V(),eventType:f.type,payload:f})}
|
|
562
|
+
`,"utf8")}persistRuntime($,f,J){this.ensureTeamSubdir($);let W={version:1,updatedAt:_V(),teamState:f,teammates:J},Z=this.statePath($),Q=`${Z}.tmp`;LM(Q,`${JSON.stringify(W,null,2)}
|
|
563
|
+
`,"utf8"),DM(Q,Z)}markInProgressRunsInterrupted($,f){let J=this.readEnvelope($);if(!J?.teamState?.runs?.length)return[];let W=J.teamState.runs.filter((Q)=>Q.status==="queued"||Q.status==="running").map((Q)=>Q.id);if(W.length===0)return[];let Z=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((Q)=>Q.status==="queued"||Q.status==="running"?{...Q,status:"interrupted",error:f,endedAt:Z}:Q)},this.persistRuntime($,J.teamState,J.teammates),W}ensureTeamDir(){if(!b2(this.teamDirPath))LV(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let f=TQ(this.ensureTeamDir(),NQ($));if(!b2(f))LV(f,{recursive:!0});return f}statePath($){return TQ(this.ensureTeamDir(),NQ($),"state.json")}historyPath($){return TQ(this.ensureTeamDir(),NQ($),"task-history.jsonl")}readEnvelope($){let f=this.statePath($);if(!b2(f))return;try{let J=JSON.parse(OV(f,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as _M,mkdirSync as zM}from"node:fs";import{join as TM}from"node:path";import{safeJsonParse as TV}from"@cline/shared";import{loadSqliteDb as NM,nowIso as MQ}from"@cline/shared/db";import{resolveDbDataDir as MM}from"@cline/shared/storage";function yM(){return MM()}function k2($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function qM($){let f=TV($);if(!Array.isArray(f))return[];let J=[];for(let W of f){if(!W||typeof W!=="object")continue;let Z=W,Q=Z.agentId,j=Z.rolePrompt;if(typeof Q!=="string"||!Q.trim())continue;if(typeof j!=="string"||!j.trim())continue;let H={agentId:Q.trim(),rolePrompt:j};if(typeof Z.modelId==="string"&&Z.modelId.trim())H.modelId=Z.modelId.trim();if(typeof Z.maxIterations==="number"&&Number.isFinite(Z.maxIterations))H.maxIterations=Math.max(1,Math.floor(Z.maxIterations));J.push(H)}return J}function wM($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class Uf{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??yM()}init(){this.getRawDb()}ensureTeamDir(){if(!_M(this.teamDirPath))zM(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return TM(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=NM(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
|
|
564
564
|
CREATE TABLE IF NOT EXISTS team_store_schema_version (
|
|
565
565
|
lock INTEGER PRIMARY KEY CHECK (lock = 1),
|
|
566
566
|
version INTEGER NOT NULL
|
|
@@ -644,13 +644,13 @@ ${Z}`,$.config.mode)}function y6($,f){return LN($,f==="plan"?"plan":f==="yolo"?"
|
|
|
644
644
|
version INTEGER NOT NULL DEFAULT 1,
|
|
645
645
|
PRIMARY KEY(team_name, fragment_id)
|
|
646
646
|
);
|
|
647
|
-
`)}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}withTransaction($){let f=this.getRawDb();f.exec("BEGIN IMMEDIATE;");try{$(),f.exec("COMMIT;")}catch(J){try{f.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let f=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[
|
|
648
|
-
VALUES (?, ?, ?, ?, NULL, ?)`,[
|
|
647
|
+
`)}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}withTransaction($){let f=this.getRawDb();f.exec("BEGIN IMMEDIATE;");try{$(),f.exec("COMMIT;")}catch(J){try{f.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let f=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[k2($)]);if(!f)return;let J=TV(f.state_json);if(!J)return;try{return wM(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 ?",[k2($),f]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime($){let f=k2($),J=this.readState(f),W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[f]),Z=W?qM(W.teammates_json):[];return{state:J,teammates:Z,interruptedRunIds:[]}}appendTeamEvent($,f,J,W){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
|
|
648
|
+
VALUES (?, ?, ?, ?, NULL, ?)`,[k2($),MQ(),f,JSON.stringify(J),W??null])}persistRuntime($,f,J){let W=k2($),Z=MQ();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
|
|
649
649
|
VALUES (?, ?, ?, ?)
|
|
650
650
|
ON CONFLICT(team_name) DO UPDATE SET
|
|
651
651
|
state_json = excluded.state_json,
|
|
652
652
|
teammates_json = excluded.teammates_json,
|
|
653
|
-
updated_at = excluded.updated_at`,[
|
|
653
|
+
updated_at = excluded.updated_at`,[W,JSON.stringify(f),JSON.stringify(J),Z]);for(let Q of f.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
|
|
654
654
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
|
|
655
655
|
ON CONFLICT(team_name, task_id) DO UPDATE SET
|
|
656
656
|
title = excluded.title,
|
|
@@ -660,7 +660,7 @@ ${Z}`,$.config.mode)}function y6($,f){return LN($,f==="plan"?"plan":f==="yolo"?"
|
|
|
660
660
|
depends_on_json = excluded.depends_on_json,
|
|
661
661
|
summary = excluded.summary,
|
|
662
662
|
version = team_tasks.version + 1,
|
|
663
|
-
updated_at = excluded.updated_at`,[Q
|
|
663
|
+
updated_at = excluded.updated_at`,[W,Q.id,Q.title,Q.description,Q.status,Q.assignee??null,JSON.stringify(Q.dependsOn??[]),Q.summary??null,Q.updatedAt.toISOString()]);for(let Q of f.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
|
|
664
664
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
|
|
665
665
|
ON CONFLICT(team_name, run_id) DO UPDATE SET
|
|
666
666
|
agent_id = excluded.agent_id,
|
|
@@ -672,14 +672,14 @@ ${Z}`,$.config.mode)}function y6($,f){return LN($,f==="plan"?"plan":f==="yolo"?"
|
|
|
672
672
|
error = excluded.error,
|
|
673
673
|
lease_owner = excluded.lease_owner,
|
|
674
674
|
heartbeat_at = excluded.heartbeat_at,
|
|
675
|
-
version = team_runs.version + 1`,[Q
|
|
675
|
+
version = team_runs.version + 1`,[W,Q.id,Q.agentId,Q.taskId??null,Q.status,Q.message,Q.startedAt?Q.startedAt.toISOString():null,Q.endedAt?Q.endedAt.toISOString():null,Q.error??null,Q.leaseOwner??null,Q.heartbeatAt?Q.heartbeatAt.toISOString():null]);for(let Q of f.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
|
|
676
676
|
VALUES (?, ?, ?, ?, ?, ?, 1)
|
|
677
677
|
ON CONFLICT(team_name, outcome_id) DO UPDATE SET
|
|
678
678
|
title = excluded.title,
|
|
679
679
|
status = excluded.status,
|
|
680
680
|
schema_json = excluded.schema_json,
|
|
681
681
|
finalized_at = excluded.finalized_at,
|
|
682
|
-
version = team_outcomes.version + 1`,[Q
|
|
682
|
+
version = team_outcomes.version + 1`,[W,Q.id,Q.title,Q.status,JSON.stringify({requiredSections:Q.requiredSections}),Q.finalizedAt?Q.finalizedAt.toISOString():null]);for(let Q of f.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
|
|
683
683
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
|
|
684
684
|
ON CONFLICT(team_name, fragment_id) DO UPDATE SET
|
|
685
685
|
outcome_id = excluded.outcome_id,
|
|
@@ -690,30 +690,30 @@ ${Z}`,$.config.mode)}function y6($,f){return LN($,f==="plan"?"plan":f==="yolo"?"
|
|
|
690
690
|
status = excluded.status,
|
|
691
691
|
reviewed_by = excluded.reviewed_by,
|
|
692
692
|
reviewed_at = excluded.reviewed_at,
|
|
693
|
-
version = team_outcome_fragments.version + 1`,[Q
|
|
694
|
-
WHERE team_name = ? AND status IN ('queued', 'running')`,[f,Z,J]),
|
|
695
|
-
`,"utf8");let
|
|
696
|
-
`,"utf8")}async function
|
|
697
|
-
`,"utf8")}function lV($,f){return{id:$,name:f.name??$,supportsAttachments:f.capabilities?.includes("files"),supportsVision:f.capabilities?.includes("images"),supportsReasoning:f.capabilities?.includes("reasoning")||f.thinkingConfig!=null}}function pV($){if(!$||$.length===0)return;let f=new Set;if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("tools"))f.add("tools");return f.size>0?[...f]:void 0}function rV($){let f=new Set;if(!$||$.length===0)return[...f];if($.includes("streaming"))f.add("streaming");if($.includes("tools"))f.add("tools");if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("vision"))f.add("images"),f.add("files");return[...f]}function pT($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function iV($,f){return $??f??"openai-chat"}function nV($,f,J){return $??J??(f==="openai-responses"?"openai":"openai-compatible")}function aV($,f,J){let Q=new Set(f?.capabilities??J??[]);if(f?.supportsVision)Q.add("images");if(f?.supportsAttachments)Q.add("files");if(f?.supportsReasoning)Q.add("reasoning");return{id:$,name:f?.name??$,maxTokens:f?.maxTokens,contextWindow:f?.contextWindow,maxInputTokens:f?.maxInputTokens,capabilities:Q.size>0?[...Q]:void 0}}function rT($,f){for(let[J,Q]of Object.entries(f??{})){let Z=Q.id?.trim()||J.trim();if(!Z)continue;w0.registerModel($,Z,aV(Z,Q))}}function iT($,f,J){return{...f??{},id:$,name:f?.name??$,capabilities:f?.capabilities??J}}function nT($){return Object.assign({},...w0.resolveProviderModelCatalogKeys($).map((J)=>w0.getGeneratedModelsForProvider(J)))}function aT($){let f=$.provider.trim();if(!f||w0.isBuiltInProviderId(f))return;let J=$.baseUrl?.trim();if(!J)return;let Q=w0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=nT(f),W=rV($.capabilities),j=W.length>0?W:void 0,X=$.model?.trim(),H={...Z,...Q?.models??{}};if(X)H[X]=iT(X,H[X],j);let Y=Object.keys(H).filter(Boolean),V=X||Y[0];if(!V)return;let A=iV($.protocol,Q?.provider.protocol),B=nV($.client,A,Q?.provider.client);w0.registerProvider({provider:{id:f,name:Q?.provider.name??uV(f),description:Q?.provider.description,protocol:A,client:B,baseUrl:J,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:V,capabilities:pV($.capabilities)??Q?.provider.capabilities,source:"file"},models:H})}function U5($){for(let f of Object.values($.providers))aT(f.settings)}function E6($,f){let J=f.models??{};if(!pT(f.provider)){rT($,J);return}let Q=rV(f.provider.capabilities),Z=Object.entries(J).map(([Y,V])=>({id:V.id?.trim()||Y.trim(),model:V})).filter(({id:Y})=>Y.length>0),W=f.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=iV(f.provider.protocol,void 0),X=nV(f.provider.client,j,void 0),H=Object.fromEntries(Z.map(({id:Y,model:V})=>[Y,{...aV(Y,V,Q.length>0?Q:void 0),status:"active"}]));w0.registerProvider({provider:{id:$,name:f.provider.name.trim()||uV($),protocol:j,client:X,baseUrl:f.provider.baseUrl,modelsSourceUrl:f.provider.modelsSourceUrl,defaultModelId:W,capabilities:pV(f.provider.capabilities),source:"file"},models:H})}function tV($){let f=j2($);if(K5.has(f))return;let J=ZZ(f);for(let[Q,Z]of Object.entries(J.providers))E6(Q,Z);K5.add(f)}async function D5($){let f=j2($);if(K5.has(f))return;let J=await N8(f);for(let[Q,Z]of Object.entries(J.providers))E6(Q,Z);K5.add(f)}function sT($){return $.apiKey??$.auth?.apiKey}function oT($){return($.auth?.accessToken?.trim()??"").length>0}function sV($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function eT($){let f=$.split(/\s+/).filter(Boolean);if(f.length===0)return"?";if(f.length===1)return f[0].slice(0,2).toUpperCase();return`${f[0][0]}${f[1][0]}`.toUpperCase()}function $M($){let f=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let Q of $)J=J*31+Q.charCodeAt(0)>>>0;return f[J%f.length]}function oV($){return Object.entries($).sort(([f],[J])=>f.localeCompare(J)).map(([f,J])=>lV(f,J))}async function fM($,f){let J=await N0.getModelsForProvider($);if(!f)return J;let Q=await c4($,{loadPrivateOnAuth:!0,failOnError:!1},f);return Q?.knownModels?{...J,...Q.knownModels}:J}function WZ($){return[...new Set(($??[]).map((f)=>f.trim()).filter(Boolean))]}function JM($){if(!$?.length)return;return[...new Set($)]}function QM($,f){return JM([...$??[],...f??[]])}function ZM($){let f=$?.popularRank;return typeof f==="number"&&Number.isFinite(f)?f:Number.MAX_SAFE_INTEGER}function eV($){let f=Object.entries($??{}).filter(([J])=>J.trim().length>0);return f.length>0?Object.fromEntries(f):void 0}function jZ($,f){let J=f?.includes("vision")??!1,Q=f?.includes("reasoning")??!1;return Object.fromEntries($.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:Q}]))}async function $A($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let f=$.modelsSourceUrl?await jJ($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...f])]}function fA($,f){let J=$.read(),Q=!1;if(J.providers[f])delete J.providers[f],Q=!0;if(J.lastUsedProvider===f)delete J.lastUsedProvider,Q=!0;if(Q)$.write(J);N0.unregisterProvider(f)}async function XZ($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=f.baseUrl.trim(),Z=f.apiKey?.trim()??"";if(!Q&&!Z){let K=j2($);if((await N8(K)).providers[J]){let F=await L5($,{providerId:J});return{providerId:J,settingsPath:F.settingsPath,modelsPath:F.modelsPath,modelsCount:0}}return fA($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:K,modelsCount:0}}if(N0.hasProvider(J))throw Error(`provider "${J}" already exists`);let W=f.name.trim();if(!W)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let j=WZ(f.models),X=f.modelsSourceUrl?.trim(),H=await $A({providerId:J,explicitModels:j,modelsSourceUrl:X,shouldRecompute:!0});if(H.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let Y=f.defaultModelId?.trim()&&H.includes(f.defaultModelId.trim())?f.defaultModelId.trim():H[0],V=f.capabilities?.length?[...new Set(f.capabilities)]:void 0,A=eV(f.headers);$.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:Q,headers:A,timeout:f.timeoutMs,model:Y,protocol:f.protocol,client:f.client},{setLastUsed:!1});let B=j2($),G=await N8(B);return G.providers[J]={provider:{name:W,baseUrl:Q,defaultModelId:Y,protocol:f.protocol,client:f.client,capabilities:V,modelsSourceUrl:X},models:jZ(H,V)},await P5(B,G),E6(J,G.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:B,modelsCount:H.length}}async function R5($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=j2($),Z=await N8(Q),W=Z.providers[J];if(!W){let _=$.getProviderSettings(J);if(!_)throw Error(`provider "${J}" does not exist`);let R=f.modelsSourceUrl?.trim(),L=WZ(f.models)[0]??_.model?.trim();if(!L&&!R)throw Error(`provider "${J}" cannot be updated because no model is configured`);W={provider:{name:f.name?.trim()||sV(J),baseUrl:f.baseUrl?.trim()??_.baseUrl?.trim()??"",defaultModelId:L,protocol:_.protocol,client:_.client,capabilities:_.capabilities},models:L?jZ([L],_.capabilities):{}}}if(!W.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=f.name?.trim()??W.provider.name.trim();if(!j)throw Error("name is required");let X=f.baseUrl?.trim()??W.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let H=f.capabilities===void 0?W.provider.capabilities:f.capabilities===null?void 0:[...new Set(f.capabilities)],Y=f.protocol===void 0?W.provider.protocol:f.protocol??void 0,V=f.client===void 0?W.provider.client:f.client??void 0,A=WZ(f.models),B=f.modelsSourceUrl===void 0?W.provider.modelsSourceUrl:f.modelsSourceUrl?.trim()||void 0,G=f.models!==void 0||f.modelsSourceUrl!==void 0&&!!B,K=Object.keys(W.models??{}).map((_)=>_.trim()).filter(Boolean),D=await $A({providerId:J,explicitModels:A,modelsSourceUrl:B,fallbackModelIds:K,shouldRecompute:G});if(D.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let F=f.defaultModelId===void 0?W.provider.defaultModelId?.trim():f.defaultModelId?.trim(),P=F&&D.includes(F)?F:D[0],z={...$.getProviderSettings(J)??{},provider:J,baseUrl:X,model:P};if(Y)z.protocol=Y;else delete z.protocol;if(V)z.client=V;else delete z.client;if(f.apiKey!==void 0){let _=f.apiKey?.trim()??"";if(_)z.apiKey=_;else delete z.apiKey}if(f.headers!==void 0){let _=eV(f.headers);if(_)z.headers=_;else delete z.headers}if(f.timeoutMs!==void 0)if(typeof f.timeoutMs==="number")z.timeout=f.timeoutMs;else delete z.timeout;return $.saveProviderSettings(z,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:X,defaultModelId:P,protocol:Y,client:V,capabilities:H,modelsSourceUrl:B},models:jZ(D,H)},await P5(Q,Z),E6(J,Z.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:Q,modelsCount:D.length}}async function L5($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=j2($),Z=await N8(Q);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await P5(Q,Z),N0.unregisterProvider(J),fA($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:Q}}async function HZ($){let f=$.read(),J=N0.getProviderIds(),Q=await Promise.all(J.map(async(W)=>{let[j,X]=await Promise.all([N0.getProvider(W),N0.getModelsForProvider(W)]),H=oV(X),Y=f.providers[W]?.settings,V=j?.name??sV(W),A=QM(j?.capabilities,Y?.capabilities);return{provider:{id:W,name:V,models:H.length,color:$M(W),letter:eT(V),enabled:Boolean(Y),apiKey:Y?sT(Y):void 0,oauthAccessTokenPresent:Y?oT(Y):void 0,baseUrl:Y?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:Y?.protocol??j?.protocol,client:Y?.client??j?.client,capabilities:A,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",modelList:H},rank:ZM(j?.metadata)}}));return Q.sort((W,j)=>{if(W.rank!==j.rank)return W.rank-j.rank;return W.provider.name.localeCompare(j.provider.name)||W.provider.id.localeCompare(j.provider.id)}),{providers:Q.map((W)=>W.provider),settingsPath:$.getFilePath()}}async function YZ($,f){let J=$.trim(),Q=await fM(J,f),Z=oV(Q);return{providerId:J,models:Z}}function VZ($,f){let J=f.providerId.trim();if(f.enabled===!1){let W=$.read();if(delete W.providers[J],W.lastUsedProvider===J)delete W.lastUsedProvider;return $.write(W),{providerId:J,enabled:!1,settingsPath:$.getFilePath()}}let Z={...$.getProviderSettings(J)??{},provider:J};for(let W of["apiKey","baseUrl","model","region"])if(Object.hasOwn(f,W)&&typeof f[W]==="string")if(f[W].trim().length===0)delete Z[W];else Z[W]=f[W];for(let W of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(f,W))Z[W]=f[W];for(let W of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(f,W)&&f[W]!=null)Z[W]={...typeof Z[W]==="object"&&Z[W]!=null?Z[W]:{},...f[W]};return $.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:$.getFilePath()}}async function AZ($,f){let J=f.trim(),Q=$.getProviderSettings(J),W=N0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=Q?.baseUrl?.trim()||W?.baseUrl?.trim(),X=XJ(j,W?.baseUrl,W?.modelsSourceUrl);if(!Q||!W||!j||!X)return{providerId:J,refreshed:!1};let H=await R5($,{providerId:J,name:W.name,baseUrl:j,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:X,protocol:Q.protocol??W.protocol??null,client:Q.client??W.client??null,capabilities:Q.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:H.modelsCount}}function BZ($){let f=$.trim().toLowerCase();if(f==="codex"||f==="openai-codex")return"openai-codex";if(f==="cline"||f==="oca")return f;throw Error(`provider "${$}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function WM($,f){if($==="cline")return f.access.startsWith("workos:")?f.access:`workos:${f.access}`;return f.access}async function GZ($,f,J,Q){let Z=a4({onPrompt:async(W)=>W.defaultValue??"",openUrl:J,onOpenUrlError:({error:W})=>{throw W instanceof Error?W:Error(String(W))}});if($==="cline")return Z8({apiBaseUrl:f?.baseUrl?.trim()||tT().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:Q});if($==="oca")return o2({mode:f?.oca?.mode,callbacks:Z,telemetry:Q});return W8({onAuth:Z.onAuth,onPrompt:Z.onPrompt,onProgress:Z.onProgress,onManualCodeInput:Z.onManualCodeInput,telemetry:Q})}function KZ($,f,J,Q){let Z={...J?.auth??{},accessToken:WM(f,Q),refreshToken:Q.refresh,accountId:Q.accountId,expiresAt:Q.expires},W={...J??{provider:f},provider:f,auth:Z};return $.saveProviderSettings(W,{tokenSource:"oauth"}),W}function FZ($){let f=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return f&&f.length>0?f:void 0}var QA={};y(QA,{getProviderConfigFields:()=>PZ});import*as O5 from"@cline/llms";import{isOAuthProviderId as jM}from"@cline/shared";var XM=["apiKey","baseUrl","awsRegion","awsProfile"],HM={bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}}};function YM($,f){let J={};for(let Q of XM){let Z=$[Q],W=f[Q];if(Z||W)J[Q]={...Z,...W}}return J}function VM($){let f=HM[$.providerId];if(!f)return $;return{...$,description:f.description??$.description,fields:f.mode==="replace"?f.fields:YM($.fields,f.fields)}}var AM=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function BM($,f){if(!f?.provider.baseUrl)return!1;if(f.provider.source!=="system")return!0;return AM.has($)}function PZ($){let f=O5.normalizeProviderId($);if(jM(f))return{providerId:f,authMethod:"oauth",fields:{}};let J=O5.MODEL_COLLECTIONS_BY_PROVIDER_ID[f];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:f,authMethod:"local",fields:{}};let Q=J?.provider.baseUrl,Z={apiKey:{}};if(BM(f,J))Z.baseUrl={defaultValue:Q};return VM({providerId:f,authMethod:"api-key",fields:Z})}var HA={};y(HA,{resolveLegacyClineAuth:()=>XA,migrateLegacyProviderSettings:()=>b6});import{existsSync as GM,readFileSync as KM}from"node:fs";import{dirname as FM,join as UZ}from"node:path";import*as _5 from"@cline/llms";import{resolveClineDataDir as PM}from"@cline/shared/storage";var z5="openai",jA=_5.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,ZA=128000;function XA($){let f=$?.trim();if(!f)return;try{let J=JSON.parse(f);if(!J)return;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:J.expiresAt,accountId:J.userInfo?.id}}catch{return}}function k($){let f=$?.trim();return f?f:void 0}function WA($){if(!GM($))return;try{let f=KM($,"utf8"),J=JSON.parse(f);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function UM($){let f=$.dataDir??PM(),J=$.globalStatePath??UZ(f,"globalState.json"),Q=$.secretsPath??UZ(f,"secrets.json"),Z=WA(J),W=WA(Q);if(!Z&&!W)return;return{globalState:Z??{},secrets:W??{}}}function DZ($){if($===z5)return jA;return $}function DM($,f,J,Q){let Z=J==="plan"?"planMode":"actMode",W=f===Q?k(J==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${Z}OpenRouterModelId`,cline:`${Z}ClineModelId`,openai:`${Z}OpenAiModelId`,ollama:`${Z}OllamaModelId`,lmstudio:`${Z}LmStudioModelId`,litellm:`${Z}LiteLlmModelId`,requesty:`${Z}RequestyModelId`,together:`${Z}TogetherModelId`,fireworks:`${Z}FireworksModelId`,sapaicore:`${Z}SapAiCoreModelId`,groq:`${Z}GroqModelId`,baseten:`${Z}BasetenModelId`,huggingface:`${Z}HuggingFaceModelId`,"huawei-cloud-maas":`${Z}HuaweiCloudMaasModelId`,oca:`${Z}OcaModelId`,aihubmix:`${Z}AihubmixModelId`,hicap:`${Z}HicapModelId`,nousResearch:`${Z}NousResearchModelId`,"vercel-ai-gateway":`${Z}VercelAiGatewayModelId`}[f];return(X?k(typeof $[X]==="string"?$[X]:void 0):void 0)??W}function RM($,f,J){let Q=J==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,Z=J==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,W=J==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,j=(f==="gemini"?Z:void 0)??Q,X=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,H=typeof W==="number"&&Number.isInteger(W)&&W>0?W:void 0;if(!X&&H===void 0)return;return{...X?{effort:X}:{},...H!==void 0?{budgetTokens:H}:{}}}function LM($){let f=$["openai-codex-oauth-credentials"];if(!f)return;try{let J=JSON.parse(f),Q=k(J.access_token),Z=k(J.refresh_token),W=k(J.accountId);if(!Q&&!Z&&!W)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...Z?{refreshToken:Z}:{},...W?{accountId:W}:{}}}}catch{return}}function OM($){let f=_5.getGeneratedModelsForProvider($);return Object.keys(f)[0]??void 0}function zM($,f,J,Q){let Z=DZ($),W=k(Q==="plan"?f.planModeApiProvider:f.actModeApiProvider),j=DM(f,$,Q,W)??OM(Z),X=RM(f,Z,Q),H=typeof f.requestTimeoutMs==="number"&&Number.isInteger(f.requestTimeoutMs)&&f.requestTimeoutMs>0?f.requestTimeoutMs:void 0,Y={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($==="openai-codex")Object.assign(V,LM(J));if($==="cline")try{let P=k(J["cline:clineAccountId"]);if(P)V.auth={...V.auth??{},...XA(P)}}catch{}if($===z5&&f.openAiHeaders)V.headers=f.openAiHeaders;if($==="bedrock"){let P=f.awsAuthentication==="profile"||f.awsUseProfile===!0;V.aws={accessKey:k(J.awsAccessKey),secretKey:k(J.awsSecretKey),sessionToken:k(J.awsSessionToken),region:k(f.awsRegion),authentication:f.awsAuthentication,profile:P?k(f.awsProfile):void 0,usePromptCache:f.awsBedrockUsePromptCache,useCrossRegionInference:f.awsUseCrossRegionInference,useGlobalInference:f.awsUseGlobalInference,endpoint:k(f.awsBedrockEndpoint),customModelBaseId:k(Q==="plan"?f.planModeAwsBedrockCustomModelBaseId:f.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")V.gcp={projectId:k(f.vertexProjectId),region:k(f.vertexRegion)};if($===z5&&(f.azureApiVersion||f.azureIdentity!==void 0))V.azure={apiVersion:k(f.azureApiVersion),useIdentity:f.azureIdentity};if($==="sapaicore")V.sap={clientId:k(J.sapAiCoreClientId),clientSecret:k(J.sapAiCoreClientSecret),tokenUrl:k(f.sapAiCoreTokenUrl),resourceGroup:k(f.sapAiResourceGroup),deploymentId:k(Q==="plan"?f.planModeSapAiCoreDeploymentId:f.actModeSapAiCoreDeploymentId),useOrchestrationMode:f.sapAiCoreUseOrchestrationMode};if($==="oca"){V.oca={mode:f.ocaMode};let P=k(J.ocaRefreshToken);if(P)V.auth={...V.auth??{},refreshToken:P}}if($==="qwen")V.apiLine=f.qwenApiLine;if($==="moonshot")V.apiLine=f.moonshotApiLine;if($==="zai")V.apiLine=f.zaiApiLine;if($==="minimax")V.apiLine=f.minimaxApiLine;let A={anthropic:f.anthropicBaseUrl,openai:f.openAiBaseUrl,ollama:f.ollamaBaseUrl,lmstudio:f.lmStudioBaseUrl,litellm:f.liteLlmBaseUrl,gemini:f.geminiBaseUrl,requesty:f.requestyBaseUrl,asksage:f.asksageApiUrl,dify:f.difyBaseUrl,oca:f.ocaBaseUrl,aihubmix:f.aihubmixBaseUrl,sapaicore:f.sapAiCoreBaseUrl},B=k(Y[$]),G=k(A[$]),K={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...G?{baseUrl:G}:{},...X?{reasoning:X}:{},...H?{timeout:H}:{},...V},D=p4.safeParse(K);if(!D.success)return;return Object.keys(K).filter((P)=>P!=="provider").length>0?D.data:void 0}function _M($,f){if($!==jA)return;if(!f.baseUrl||!f.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:f.baseUrl,defaultModelId:f.model},models:{[f.model]:{id:f.model,name:f.model,contextWindow:ZA,maxInputTokens:ZA,capabilities:["streaming","tools","images"]}}}}function NM($,f){let J=new Set;for(let Q of[$.actModeApiProvider,$.planModeApiProvider]){let Z=k(Q);if(Z)J.add(Z)}if(k(f.apiKey))J.add("anthropic");if(k(f.openRouterApiKey))J.add("openrouter");if(k(f.openAiApiKey))J.add(z5);if(k(f.openAiNativeApiKey))J.add("openai-native");if(k(f["openai-codex-oauth-credentials"]))J.add("openai-codex");if(k(f.geminiApiKey))J.add("gemini");if(k(f.ollamaApiKey))J.add("ollama");if(k(f.awsAccessKey)||k(f.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||k($.awsProfile))J.add("bedrock");if(k($.vertexProjectId)||k($.vertexRegion))J.add("vertex");if(k(f.clineApiKey))J.add("cline");if(k(f.ocaApiKey))J.add("oca");return J}function b6($){let f=$.providerSettingsManager.read(),J=UM($);if(!J)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let{globalState:Q,secrets:Z}=J,W=Q.mode==="plan"?"plan":"act",j=NM(Q,Z),X=X1();X.providers={...f.providers},X.lastUsedProvider=f.lastUsedProvider;let H=new Date().toISOString(),Y=0,V=UZ(FM($.providerSettingsManager.getFilePath()),"models.json"),A=ZZ(V),B=0;for(let D of j){let F=DZ(D);if(X.providers[F])continue;let P=zM(D,Q,Z,W);if(!P)continue;X.providers[F]={settings:P,updatedAt:H,tokenSource:"migration"},Y+=1;let U=_M(F,P);if(U&&!A.providers[F])A.providers[F]=U,B+=1}if(Y===0&&B===0)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let G=k(W==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),K=G?DZ(G):void 0;if(X.lastUsedProvider=f.lastUsedProvider??(K&&X.providers[K]?K:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),B>0)dV(V,A);return{migrated:Y>0||B>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}L0();Lf();var AA={};y(AA,{trimMessagesToCheckpoint:()=>VA,trimMessagesBeforeCheckpoint:()=>LZ,readSessionCheckpointHistory:()=>k6,createRestoredCheckpointMetadata:()=>RZ,createCheckpointRestorePlan:()=>OZ,applyCheckpointToWorktree:()=>zZ});import{execFile as TM}from"node:child_process";import{promisify as MM}from"node:util";var T8=MM(TM);function k6($){let f=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(f?.history)?f.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let Z=String(Q.ref??"").trim(),W=Number(Q.createdAt??0),j=Number(Q.runCount??0);if(Z.length===0||!Number.isFinite(W)||!Number.isInteger(j)||j<1)return[];let X=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:Z,createdAt:W,runCount:j,...X?{kind:X}:{}}]})}function RZ($,f){let J=k6($).filter((Z)=>Z.runCount<=f),Q=J.at(-1);return Q?{latest:Q,history:J}:void 0}function qM($,f){return $.reduce((J,Q)=>{if(Q.runCount>f)return J;if(!J||Q.runCount>J.runCount)return Q;return J},void 0)}function YA($,f){let J=0;for(let Q=0;Q<$.length;Q+=1){let Z=$[Q];if(Z?.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===f)return Q}throw Error(`Could not find user message for checkpoint run ${f}`)}function VA($,f){let J=YA($,f);return $.slice(0,J+1)}function LZ($,f){let J=YA($,f);return $.slice(0,J)}function OZ($){let f=$.checkpointRunCount;if(!Number.isInteger(f)||f<1)throw Error("checkpointRunCount must be a positive integer");let J=qM(k6($.session),f);if(!J)throw Error(`No checkpoint found at or before run ${f} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:Q,...$.restoreMessages!==!1?{messages:VA($.messages??[],f)}:{}}}async function zZ($,f){if((await T8("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await T8("git",["-C",$,"cat-file","-e",`${f.ref}^{commit}`],{windowsHide:!0}),await T8("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await T8("git",["-C",$,"clean","-fd"],{windowsHide:!0}),f.kind==="commit"){await T8("git",["-C",$,"reset","--hard",f.ref],{windowsHide:!0});return}await T8("git",["-C",$,"stash","apply",f.ref],{windowsHide:!0})}var BA={};y(BA,{SessionVersioningService:()=>K1,SessionVersioningError:()=>S0});class S0 extends Error{code;constructor($,f){super(f);this.code=$;this.name="SessionVersioningError"}}function yM($){let f=$.sessionId.trim();if(!f)throw new S0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new S0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new S0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new S0("invalid_restore","checkpointRunCount must be a positive integer");return f}class K1{async restoreCheckpoint($){let f=$.restore?.messages!==!1,J=$.restore?.workspace!==!1,Q=yM({sessionId:$.sessionId,restoreMessages:f,restoreWorkspace:J,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),Z=await $.getSession(Q);if(!Z)throw new S0("session_not_found",`Session ${Q} not found`);let W=f?await $.readMessages(Q):void 0;if(f&&W?.length===0)throw new S0("session_messages_not_found",`No messages found for session ${Q}`);let j=OZ({session:Z,messages:W,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:f});if(J)await($.applyWorkspaceCheckpoint??zZ)(j.cwd,j.checkpoint);let X=X$({session:Z,messages:W});if(!f)return{checkpoint:j.checkpoint,sourceSnapshot:X};let H=RZ(Z,$.checkpointRunCount),Y=$.restore?.omitCheckpointMessageFromSession?LZ(W??[],$.checkpointRunCount):j.messages??[],V={sourceSession:Z,sourceMessages:W,sourceSnapshot:X,plan:j,restoredCheckpointMetadata:H,initialMessages:Y,restoreMessages:f,restoreWorkspace:J,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new S0("invalid_restore","start is required when restore.messages is true");let A=$.buildStartInput?await $.buildStartInput(V,$.start):$.start,B=await $.startSession(A),G=$.getStartedSessionId?.(B);if(G)await($.retainCheckpointRefs??yX)(j.cwd,G,H?.history??[]);let K=G&&$.readRestoredSession?await $.readRestoredSession(G):void 0;return{sessionId:G,startResult:B,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:X,...K?{restoredSnapshot:X$({session:K,messages:Y})}:{}}}}var GA={};y(GA,{FileTeamPersistenceStore:()=>N5});import{appendFileSync as wM,existsSync as _Z,mkdirSync as SM,readFileSync as hM,renameSync as CM,unlinkSync as EM,writeFileSync as bM}from"node:fs";import{join as NZ}from"node:path";import{resolveTeamDataDir as kM}from"@cline/shared/storage";function IM($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class N5{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let f=IM($.teamName),J=$.baseDir?.trim()||kM();this.dirPath=NZ(J,f),this.statePath=NZ(this.dirPath,"state.json"),this.taskHistoryPath=NZ(this.dirPath,"task-history.jsonl")}loadState(){if(!_Z(this.statePath))return;try{let $=hM(this.statePath,"utf8"),f=JSON.parse($);if(f.version!==1||!f.teamState)return;for(let J of f.teammates??[])this.teammateSpecs.set(J.agentId,J);return FV(f.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let f={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;bM(J,`${JSON.stringify(f,null,2)}
|
|
698
|
-
`,"utf8"),
|
|
699
|
-
`,"utf8")}ensureDir(){if(!_Z(this.dirPath))SM(this.dirPath,{recursive:!0})}hasPersistableState($){let f=$.exportState();if(this.teammateSpecs.size>0)return!0;if(f.members.some((J)=>J.role==="teammate"))return!0;return f.tasks.length>0||f.mailbox.length>0||f.missionLog.length>0}clearPersistedState(){if(_Z(this.statePath))EM(this.statePath)}}var KA={};y(KA,{ChatViewStateSchema:()=>TZ,ChatSummarySchema:()=>w5,ChatSessionStatusSchema:()=>M5,ChatSessionConfigSchema:()=>T5,ChatMessageSchema:()=>y5,ChatMessageRoleSchema:()=>q5});import{z as h}from"zod";var T5=h.object({workspaceRoot:h.string().min(1),cwd:h.string().optional(),provider:h.string().min(1),model:h.string().min(1),mode:h.enum(["act","plan"]).default("act"),apiKey:h.string(),systemPrompt:h.string().optional(),rules:h.string().optional(),maxIterations:h.number().int().positive().optional(),enableTools:h.boolean(),enableSpawn:h.boolean().optional(),enableTeams:h.boolean().optional(),autoApproveTools:h.boolean().optional(),missionStepInterval:h.number().int().positive().optional(),missionTimeIntervalMs:h.number().int().positive().optional()}),M5=h.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),q5=h.enum(["user","assistant","tool","system","status","error"]),y5=h.object({id:h.string().min(1),sessionId:h.string().nullable(),role:q5,content:h.string(),createdAt:h.number().int().nonnegative(),meta:h.object({stream:h.enum(["stdout","stderr"]).optional(),toolName:h.string().optional(),iteration:h.number().int().nonnegative().optional(),agentId:h.string().optional(),conversationId:h.string().optional(),hookEventName:h.string().optional(),inputTokens:h.number().int().nonnegative().optional(),outputTokens:h.number().int().nonnegative().optional(),checkpoint:h.object({ref:h.string(),createdAt:h.number().int().nonnegative(),runCount:h.number().int().positive(),kind:h.enum(["stash","commit"]).optional()}).optional()}).optional()}),w5=h.object({toolCalls:h.number().int().nonnegative(),tokensIn:h.number().int().nonnegative(),tokensOut:h.number().int().nonnegative()}),TZ=h.object({sessionId:h.string().nullable(),status:M5,config:T5,messages:h.array(y5),rawTranscript:h.string(),error:h.string().nullable(),summary:w5});var FA={};y(FA,{CORE_BUILD_VERSION:()=>MZ});var MZ=v3;import{Agent as Dq,createAgentRuntime as Rq}from"@cline/agents";var UA={};y(UA,{fetchClineRecommendedModels:()=>qZ,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>S5});import{getClineEnvironmentConfig as xM}from"@cline/shared";var mM=5000,S5={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 gM($){return{recommended:$.recommended.map((f)=>({...f,tags:[...f.tags]})),free:$.free.map((f)=>({...f,tags:[...f.tags]}))}}function PA($){if(!$||typeof $!=="object")return null;let f=$;if(typeof f.id!=="string"||f.id.length===0)return null;return{id:f.id,name:typeof f.name==="string"&&f.name.length>0?f.name:f.id,description:typeof f.description==="string"?f.description:"",tags:Array.isArray(f.tags)?f.tags.filter((J)=>typeof J==="string"):[]}}function vM($){if(!$||typeof $!=="object")return null;let f=$,J=Array.isArray(f.recommended)?f.recommended:[],Q=Array.isArray(f.free)?f.free:[],Z=J.map(PA).filter((j)=>j!==null),W=Q.map(PA).filter((j)=>j!==null);if(Z.length===0&&W.length===0)return null;return{recommended:Z,free:W}}function uM($){let f=$.baseUrl?.trim();if(f)return f;let J=xM().apiBaseUrl;try{return($.providerSettingsManager??new G$).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function cM($,f,J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await $(f,{signal:Q.signal})}finally{clearTimeout(Z)}}async function qZ($={}){try{let f=uM($),J=$.fetchImpl??fetch,Q=await cM(J,`${f}/api/v1/ai/cline/recommended-models`,$.timeoutMs??mM);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let Z=await Q.json(),W=vM(Z);if(W)return W}catch{}return gM(S5)}var DA={};y(DA,{loadLlmsConfigFromFile:()=>wZ,defineLlmsConfig:()=>yZ});import{readFile as dM}from"node:fs/promises";import lM from"node:path";function yZ($){return $}async function wZ($){let f=lM.resolve($),J=await dM(f,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${f}": ${W}`)}return pM(Q,f)}function pM($,f){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${f}": expected an object.`);let Q=$.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${f}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${f}": "providers" cannot be empty.`);return $}var NA={};y(NA,{createLlmsSdk:()=>hZ,DefaultLlmsSdk:()=>I6});import{BUILT_IN_PROVIDER_IDS as OA,createHandler as nM,createHandlerAsync as aM,getProviderCollection as tM,hasProvider as zA,registerAsyncHandler as sM,registerHandler as oM,registerModel as eM,registerProvider as _A}from"@cline/llms";function RA($){return $?{...$}:{}}function rM($,f){if($)return $;if(!f)return;let J=globalThis.process;if(!J?.env)return;return J.env[f]}function iM($,f){if(!f.length)throw Error(`Provider "${$}" must include at least one model.`)}function LA($){let f=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:f,defaultModel:$.collection.provider.defaultModelId,modelCount:f.length}}class SZ{providers=new Map;register($){iM($.id,$.models);let f=$.defaultModel??$.models[0];if(!f)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(f))throw Error(`Default model "${f}" is not included in configured models for "${$.id}".`);let J=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...J?.models??[],...$.models]),defaultModel:f,defaults:{...J?.defaults??{},...RA($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:rM($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...RA($.settings)}})}registerModel($,f){let J=this.providers.get($);if(!J){this.providers.set($,{id:$,models:new Set([f]),defaultModel:f,defaults:{}});return}J.models.add(f)}createHandlerConfig($){let f=this.require($.providerId),J=$.modelId??f.defaultModel;if(!f.models.has(J))throw Error(`Model "${J}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:J,...f.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,f){return this.providers.get($)?.models.has(f)??!1}require($){let f=this.providers.get($);if(!f)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return f}}class I6{configuredProviders=new SZ;constructor($){this.applyConfig($)}createHandler($){return nM(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return aM(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(_A($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)oM($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)sM($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let f=$.exposeModels??Object.keys($.models),J=$.defaultModel??f[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);_A({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:J,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:f,defaultModel:J,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){eM($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...OA]}async getBuiltInProviders(){return(await Promise.all(OA.map((f)=>tM(f)))).filter((f)=>f!==void 0).map((f)=>LA({collection:f}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,f){return this.configuredProviders.hasModel($,f)}applyConfig($){for(let f of $.providers)this.configuredProviders.registerSelectionConfig(f);for(let f of $.models??[])this.registerModel(f);for(let f of $.customProviders??[])this.registerProvider(f);for(let f of this.configuredProviders.list()){let J=zA(f.id),Q=this.configuredProviders.createHandlerConfig({providerId:f.id,modelId:f.defaultModel}).routingProviderId,Z=typeof Q==="string"&&zA(Q);if(!J&&!Z)throw Error(`Provider "${f.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function hZ($){return new I6($)}e5();async function $q(){return Promise.resolve().then(() => (pQ(),qV))}function Nq(){return new Date().toISOString()}function Tq($){if(CA($)!=="providers.json")return;let f=EZ($);if(CA(f)!=="settings")return;return EZ(f)}class G${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??_q(),this.dataDir=$.dataDir??Tq(this.filePath),this.dataDir||!$.filePath)b6({providerSettingsManager:this,dataDir:this.dataDir});if(tV(this),U5(this.read()),CZ(this.filePath))try{hA(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!CZ(this.filePath))return X1();try{let $=Oq(this.filePath,"utf8"),f=JSON.parse($),J=f8.safeParse(f);if(J.success)return U5(J.data),J.data}catch{}return X1()}write($){let f=f8.parse($),J=EZ(this.filePath);if(!CZ(J))Lq(J,{recursive:!0,mode:448});zq(this.filePath,`${JSON.stringify(f,null,2)}
|
|
700
|
-
`,"utf8");try{hA(this.filePath,384)}catch{}U5(f)}saveProviderSettings($,f={}){let J=p4.parse($),Q=this.read(),Z=J.provider,W=f.setLastUsed!==!1,j=Q.providers[Z],X=f.tokenSource??j?.tokenSource??"manual",H={...Q,providers:{...Q.providers,[Z]:{settings:J,updatedAt:Nq(),tokenSource:X}},lastUsedProvider:W?Z:Q.lastUsedProvider};return this.write(H),H}getProviderSettings($){return this.read().providers[$]?.settings}getLastUsedProviderSettings(){let $=this.read(),f=$.lastUsedProvider;if(!f)return;return $.providers[f]?.settings}getProviderConfig($,f){let J=this.getProviderSettings($);if(!J)return;return u0(J,f)}getLastUsedProviderConfig($){let f=this.getLastUsedProviderSettings();if(!f)return;return u0(f,$)}async refreshCatalog(){try{await e2({})}catch{}}}L0();Rf();import{getClineEnvironmentConfig as Mq,isOAuthProviderId as qq}from"@cline/shared";var bZ="workos:";function yq($,f){if($==="cline")return`${bZ}${f}`;return f}function wq($,f){if($==="cline"&&f.toLowerCase().startsWith(bZ))return f.slice(bZ.length);return f}function Sq($){let J=z0($)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function hq($,f){let J=$.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let Q=Sq(f);if(Q)return Q;return Date.now()-1}function Cq($,f){let J=f.auth?.accessToken?.trim(),Q=f.auth?.refreshToken?.trim();if(!J||!Q)return null;let Z=wq($,J);if(!Z)return null;return{access:Z,refresh:Q,expires:hq(f,Z),accountId:f.auth?.accountId}}function Eq($,f){let J=$?.expiresAt,Q=f?.expiresAt;return $?.accessToken===f?.accessToken&&$?.refreshToken===f?.refreshToken&&$?.accountId===f?.accountId&&J===Q}class C5 extends Error{providerId;constructor($){super(`OAuth credentials for provider "${$}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=$}}class kZ{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new G$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){if(!qq($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,f=!1){let J=this.refreshInFlight.get($);if(J)return J;let Q=this.resolveProviderApiKeyInternal($,f).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,Q),Q}async resolveProviderApiKeyInternal($,f){let J=this.providerSettingsManager.getProviderSettings($);if(!J)return null;let Q=Cq($,J);if(!Q)return null;let Z=await this.resolveCredentials($,J,Q,f);if(!Z)throw new C5($);let W=yq($,Z.access),j={...J.auth??{},accessToken:W,refreshToken:Z.refresh,accountId:Z.accountId};j.expiresAt=Z.expires;let X={...J,auth:j},H=!Eq(J.auth,X.auth);if(H)this.providerSettingsManager.saveProviderSettings(X,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:W,accountId:Z.accountId,refreshed:H}}async resolveCredentials($,f,J,Q){if($==="cline")return s4(J,{apiBaseUrl:f.baseUrl?.trim()||Mq().apiBaseUrl,telemetry:this.telemetry},{forceRefresh:Q});if($==="oca")return g4(J,{forceRefresh:Q,telemetry:this.telemetry},{mode:f.oca?.mode,telemetry:this.telemetry});return e4(J,{forceRefresh:Q,telemetry:this.telemetry})}}import{normalizeUserInput as bq}from"@cline/shared";import{nanoid as kq}from"nanoid";class EA{list($){return $?p0($):[]}update($,f){if(!$)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=f.promptId.trim(),Q=$.pendingPrompts.findIndex((H)=>H.id===J);if(Q<0)return{sessionId:f.sessionId,prompts:p0($),updated:!1};let Z=$.pendingPrompts[Q];if(!Z)return{sessionId:f.sessionId,prompts:p0($),updated:!1};let W=f.prompt===void 0?Z.prompt:bq(f.prompt).trim();if(!W)throw Error("prompt cannot be empty");let j=f.delivery??Z.delivery,X={...Z,prompt:W,mode:f.mode??Z.mode,delivery:j};return $.pendingPrompts.splice(Q,1),Iq($,X,Q,Z.delivery),{sessionId:f.sessionId,prompts:p0($),prompt:E5(X),updated:!0}}delete($,f){if(!$)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=f.promptId.trim(),Q=$.pendingPrompts.findIndex((W)=>W.id===J);if(Q<0)return{sessionId:f.sessionId,prompts:p0($),removed:!1};let[Z]=$.pendingPrompts.splice(Q,1);return{sessionId:f.sessionId,prompts:p0($),prompt:Z?E5(Z):void 0,removed:!0}}enqueue($,f){let{prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j}=f,X=$.pendingPrompts.findIndex((H)=>H.prompt===J);if(X>=0){let[H]=$.pendingPrompts.splice(X,1),Y={...H,prompt:J,mode:Q??H.mode,userImages:W??H.userImages,userFiles:j??H.userFiles};if(Z==="steer"||H.delivery==="steer")$.pendingPrompts.unshift({...Y,delivery:"steer"});else $.pendingPrompts.push(Y)}else{let H={id:`pending_${Date.now()}_${kq(5)}`,prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j};if(Z==="steer")$.pendingPrompts.unshift(H);else $.pendingPrompts.push(H)}return p0($)}consumeSteer($){let f=$.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if(f<0)return{prompts:p0($)};let[J]=$.pendingPrompts.splice(f,1);return{entry:J,prompts:p0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:p0($)}}requeueFront($,f){return $.pendingPrompts.unshift(f),p0($)}clear($){return $.pendingPrompts.length=0,[]}}class IZ{deps;service=new EA;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=this.service.update(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}delete($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=this.service.delete(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}enqueue($,f){let J=this.deps.getSession($);if(!J||J.aborting)return;this.service.enqueue(J,f),this.emitPrompts(J),this.scheduleDrain($,J)}consumeSteer($){let f=this.deps.getSession($);if(!f)return;let{entry:J}=this.service.consumeSteer(f);if(!J)return;return this.emitPrompts(f),this.emitSubmitted(f,J),J}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:p0($)}})}scheduleDrain($,f){if(f.pendingPrompts.length===0||f.aborting||f.drainingPendingPrompts||!f.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let f=this.deps.getSession($);if(!f)return;if(f.aborting||f.drainingPendingPrompts)return;if(!f.agent.canStartRun())return;let{entry:J}=this.service.shiftNext(f);if(!J)return;this.emitPrompts(f),this.emitSubmitted(f,J),f.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:$,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{Q=!1,this.service.requeueFront(f,J),this.emitPrompts(f)}finally{if(f.drainingPendingPrompts=!1,Q&&f.pendingPrompts.length>0&&f.status!=="failed"&&f.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,f){let J=E5(f);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function E5($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function p0($){return $.pendingPrompts.map(E5)}function Iq($,f,J,Q){if(f.delivery==="steer")$.pendingPrompts.unshift(f);else if(Q==="steer")$.pendingPrompts.push(f);else $.pendingPrompts.splice(J,0,f)}L0();class mZ{deps;constructor($){this.deps=$}dispatchAgentEvent($,f,J){let Q=this.deps.getSession($),Z={sessionId:$,config:f,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},W=V7(J),j=!!Q&&(!W.agentId||W.agentId===xZ(Q.agent));A7(Z,J,j?{isPrimaryAgentEvent:!0,agentId:xZ(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,f){let J=this.deps.getSession($);if(J){if(hQ(J,f),f.type==="agent_event"){let Q={sessionId:$,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};A7(Q,f.event,{agentId:f.agentId,teamRole:"teammate",teamAgentId:f.agentId,isPrimaryAgentEvent:!1})}if(f.type==="teammate_spawned"){let Q=y$({agentId:f.teammate.runtimeAgentId??f.agentId,conversationId:f.teammate.conversationId,parentAgentId:f.teammate.parentAgentId,createdByAgentId:xZ(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:f.agentId});if(Q)v$(J.config.telemetry,{ulid:$,modelId:f.teammate.modelId??J.config.modelId,provider:J.config.providerId,...Q})}}if(await CQ($,f,this.deps.invokeBackendOptional),J)EQ(J,$,f,this.deps.emit)}async handlePluginEvent($,f,J){if(f.name==="plugin_log"){this.handlePluginLog($,f.payload);return}if(f.name==="automation_event"){let H=this.deps.getSession($)?.config.extensionContext?.automation??J;if(!H)return;let Y=f.payload&&typeof f.payload==="object"?f.payload:void 0;if(!Y)return;await H.ingestEvent(Y);return}if(f.name!=="steer_message"&&f.name!=="queue_message"&&f.name!=="pending_prompt")return;let Q=f.payload&&typeof f.payload==="object"?f.payload:void 0,Z=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():$,W=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!W)return;let j=f.name==="steer_message"?"steer":f.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:W,delivery:j})}handlePluginLog($,f,J){let Q=this.deps.getSession($),Z=J??Q?.config.extensionContext?.logger??Q?.config.logger;if(!Z||!f||typeof f!=="object")return;let W=f,j=typeof W.message==="string"?W.message:"";if(!j)return;let X=W.metadata&&typeof W.metadata==="object"?{...W.metadata}:{};if(X.sessionId??=$,typeof W.pluginName==="string"&&W.pluginName)X.pluginName=W.pluginName;if(W.level==="debug"){Z.debug(j,X);return}if(W.level==="error"){if(Z.error)Z.error(j,X);else Z.log(j,{...X,severity:"error"});return}Z.log(j,X)}}function xZ($){return $.getAgentId()}function gZ($){return{sessionId:$.sessionId,source:$.source,pid:process.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:$1($.config),teamName:$.config.teamName?.trim()||void 0,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,parentSessionId:typeof $.sessionMetadata?.parentSessionId==="string"?$.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof $.sessionMetadata?.parentAgentId==="string"?$.sessionMetadata.parentAgentId:void 0,agentId:typeof $.sessionMetadata?.agentId==="string"?$.sessionMetadata.agentId:void 0,conversationId:typeof $.sessionMetadata?.conversationId==="string"?$.sessionMetadata.conversationId:void 0,isSubagent:typeof $.sessionMetadata?.isSubagent==="boolean"?$.sessionMetadata.isSubagent:!1,prompt:$.pendingPrompt,metadata:$.sessionMetadata,messagesPath:$.artifacts?.messagesPath,updatedAt:$.updatedAt??$.endedAt??$.startedAt}}function vZ($,f){let J=$[f];return typeof J==="function"?J:null}async function bA($,f,...J){let Q=vZ($,f);if(!Q)throw Error(`session service method not available: ${f}`);return Promise.resolve(Q.apply($,J))}async function kA($,f,...J){let Q=vZ($,f);if(!Q)return;await Promise.resolve(Q.apply($,J))}async function IA($,f,...J){let Q=vZ($,f);if(!Q)return;return await Promise.resolve(Q.apply($,J))}O$();L0();function uZ($,f,J,Q){return o$({configProvider:{getRuntimeConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:f.hooks,extensions:f.extensions,logger:f.logger,telemetry:f.telemetry},getConnectionConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let W=f.enableTools?E1({cwd:f.cwd,...g0[M$({mode:f.mode})],executors:Q}):[];if(f.enableSpawnAgent)W.push(uZ($,f,J,Q));return O1(W)},onSubAgentEvent:(W)=>$.onAgentEvent(J,f,W),onSubAgentStart:(W)=>{let j=$.getSession(J)?.runtime.teamRuntime;$.subAgentStarts.set(W.subAgentId,{startedAt:Date.now(),rootSessionId:J});let X=y$({agentId:W.subAgentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:W.parentAgentId});if(X)v$(f.telemetry,{ulid:J,modelId:f.modelId,provider:f.providerId,...X});g8(f.telemetry,{event:"started",ulid:J,durationMs:0,parentId:W.parentAgentId,agentId:W.subAgentId,...X}),$.invokeBackendOptional("handleSubAgentStart",J,W)},onSubAgentEnd:(W)=>{let j=$.getSession(J)?.runtime.teamRuntime,X=$.subAgentStarts.get(W.subAgentId),H=X?Date.now()-X.startedAt:0,Y=W.result?.text?W.result.text.split(`
|
|
701
|
-
`).length:0;g8(f.telemetry,{event:"ended",ulid:J,durationMs:H,outputLines:Y,errorMessage:W.error?String(W.error):void 0,agentId:W.subAgentId,parentId:W.parentAgentId,...y$({agentId:W.subAgentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:W.parentAgentId})}),$.subAgentStarts.delete(W.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",J,W)}})}import{readFile as xq,stat as mq}from"node:fs/promises";var gq=20480000;async function xA($){let f=await mq($);if(!f.isFile())throw Error("Path is not a file");if(f.size>gq)throw Error("File is too large to read into context.");let J=await xq($,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var mA=5000;function u6($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function iq($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=u6(f.inputTokens),Q=u6(f.outputTokens),Z=u6(f.cacheReadTokens),W=u6(f.cacheWriteTokens),j=u6(f.totalCost);if(J===void 0||Q===void 0||Z===void 0||W===void 0||j===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:Z,cacheWriteTokens:W,totalCost:j}}function nq($,f){return{inputTokens:Math.max($.inputTokens,f.inputTokens),outputTokens:Math.max($.outputTokens,f.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,f.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,f.cacheWriteTokens),totalCost:Math.max($.totalCost,f.totalCost)}}class B${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new z6;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new K1;constructor($){let f=uq();if(f)rq(f);let J=z1($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new _8,this.createAgentInstance=$.createAgent??((Q)=>new s$(Q)),this.defaultCapabilities=D0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new G$,this.oauthTokenManager=$.oauthTokenManager??new kZ({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=$.fetch,this.pendingPromptsController=new IZ({getSession:(Q)=>this.sessions.get(Q),emit:(Q)=>this.emit(Q),send:(Q)=>this.runTurn(Q)}),this.pendingPrompts={list:async(Q)=>this.pendingPromptsController.list(Q.sessionId),update:async(Q)=>this.pendingPromptsController.update(Q),delete:async(Q)=>this.pendingPromptsController.delete(Q)},this.eventBridge=new mZ({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,Z,W)=>{this.invoke("persistSessionMessages",Q,Z,W)},enqueuePendingPrompt:(Q,Z)=>this.pendingPromptsController.enqueue(Q,Z),invokeBackendOptional:(Q,...Z)=>this.invokeOptional(Q,...Z)})}async startSession($){let f=$.source??F0.CLI,J=s(),Q=$.config.sessionId?.trim()??"",Z=Q||dq(),W=$,j=W.initialMessages??[],X=j.length>0?g2(j):A0(),H=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!H)throw Error("session service method not available: ensureSessionsDir");let Y=cZ(H,Z),V=cZ(Y,`${Z}.messages.json`),A=cZ(Y,`${Z}.json`),B=$1($.config),G=q0.parse({version:1,session_id:Z,source:f,pid:process.pid,started_at:J,status:"running",interactive:$.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:W.config.cwd,workspace_root:B,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,messages_path:V}),K;if(Q.length>0&&j.length>0&&!W.prompt?.trim()){let b=await this.invokeOptionalValue("readSessionManifest",Z);if(b)G=b,K={manifestPath:A,messagesPath:b.messages_path||V,manifest:b}}let F=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:Y,rootMessagesPath:K?.messagesPath??V,manifest:G});this.usageBySession.set(Z,X),this.aggregateUsageBySession.set(Z,F);let P=D0(this.defaultCapabilities,$.capabilities),U=P?.toolExecutors??this.toolExecutors,z=$.localRuntime,_=z?.extensionContext?.logger??z?.logger,R=z?.extensionContext?.automation,L;L=await KH({input:W,localRuntime:$.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:P,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(b)=>{if(b.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,b.payload,_);return}this.eventBridge.handlePluginEvent(Z,b,R)},onTeamEvent:(b)=>{this.eventBridge.handleTeamEvent(Z,b),L.config.onTeamEvent?.(b)},createSpawnTool:()=>uZ({getSession:(b)=>this.sessions.get(b),subAgentStarts:this.subAgentStarts,onAgentEvent:(b,i,C0)=>this.eventBridge.dispatchAgentEvent(b,i,C0),invokeBackendOptional:(b,...i)=>this.invokeOptional(b,...i)},L.config,Z,U),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(b)=>{await this.persistSessionMetadata(Z,()=>b)}});let N=await this.runtimeBuilder.build(L.runtimeBuilderInput),w=L.config,Q0=L.providerConfig;if(N.teamRuntime&&!w.teamName?.trim())w.teamName=N.teamRuntime.getTeamName();let Z0=[...N.tools,...w.extraTools??[]],o=N.extensions??L.extensions,d={sessionId:Z,providerId:Q0.providerId,modelId:Q0.modelId,apiKey:Q0.apiKey,baseUrl:Q0.baseUrl,headers:Q0.headers,knownModels:Q0.knownModels,providerConfig:Q0,thinking:w.thinking,reasoningEffort:w.reasoningEffort??Q0.reasoningEffort,systemPrompt:w.systemPrompt,maxIterations:w.maxIterations,execution:w.execution,prepareTurn:Q4(w),tools:Z0,hooks:L.hooks,extensions:o,hookErrorMode:w.hookErrorMode,initialMessages:L.effectiveInput.initialMessages,userFileContentLoader:xA,toolPolicies:L.toolPolicies,requestToolApproval:L.requestToolApproval?async(b)=>{let i=L.requestToolApproval,C0=this.sessions.get(Z);if(C0)await this.markTurnPending(C0);try{if(!i)return{approved:!1,reason:"Tool approval callback is not configured."};return await i(b)}finally{let T0=this.sessions.get(Z);if(T0?.status==="pending")await this.markTurnRunning(T0)}}:void 0,telemetry:w.telemetry,onConsecutiveMistakeLimitReached:w.onConsecutiveMistakeLimitReached,completionPolicy:N.completionPolicy,consumePendingUserMessage:()=>{let b=this.pendingPromptsController.consumeSteer(Z);return b?y6(b.prompt,b.mode??w.mode):void 0},logger:N.logger??w.logger,extensionContext:w.extensionContext,onEvent:(b)=>this.eventBridge.dispatchAgentEvent(Z,w,b)};d.hooks={...d.hooks,onEvent:async(b)=>{if(await L.hooks?.onEvent?.(b),b.type!=="assistant-message")return;let i=this.sessions.get(Z);if(!i)return;let C0=i.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,C0,w.systemPrompt)}catch(T0){w.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:T0}),X2(w.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:T0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:w.providerId,modelId:w.modelId}})}}};let R0=this.createAgentInstance(d);if(d.onEvent)R0.subscribeEvents(d.onEvent);N.registerLeadAgent?.(R0);let b$=y$({agentId:R0.getAgentId(),conversationId:R0.getConversationId(),teamId:N.teamRuntime?.getTeamId(),teamName:N.teamRuntime?.getTeamName(),teamRole:N.teamRuntime?"lead":void 0});if(PH(w,Z,Q.length>0,B,b$),b$)v$(w.telemetry,{ulid:Z,modelId:w.modelId,provider:w.providerId,...b$});if(N.teamRuntime)Yf(w.telemetry,{ulid:Z,teamId:N.teamRuntime.getTeamId(),teamName:N.teamRuntime.getTeamName(),leadAgentId:R0.getAgentId(),restoredFromPersistence:N.teamRestoredFromPersistence===!0});let l={sessionId:Z,config:w,sessionMetadata:W.sessionMetadata,...K?{artifacts:K}:{},source:f,startedAt:K?.manifest.started_at??J,updatedAt:K?.manifest.ended_at??K?.manifest.started_at??J,pendingPrompt:G.prompt,runtime:N,agent:R0,started:!1,status:K?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:L.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,l),this.emitStatus(Z,"running"),j.length>0&&!K){if(await this.ensureSessionPersisted(l),await this.invoke("persistSessionMessages",l.sessionId,j,l.config.systemPrompt),!W.prompt?.trim())await this.updateStatus(l,"completed",0)}let K$;try{if(W.prompt?.trim())if(K$=await this.executeTurn(l,{prompt:W.prompt,userImages:W.userImages,userFiles:W.userFiles}),!l.interactive)await this.finalizeSingleRun(l,K$.finishReason);else await this.completeInteractiveTurn(l,K$.finishReason)}catch(b){if(l.interactive&&l.aborting)K$=await this.completeAbortedInteractiveTurn(l);else throw X2(l.config.telemetry,{component:"core",operation:"session.start",error:b,severity:"error",handled:!1,context:{sessionId:l.sessionId,providerId:l.config.providerId,modelId:l.config.modelId}}),await this.failSession(l),b}return{sessionId:Z,manifest:G,manifestPath:A,messagesPath:V,result:K$}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(f)=>this.getSession(f),readMessages:(f)=>this.readSessionMessages(f),buildStartInput:(f,J)=>{let Q=f.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:f.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...Q?{sessionMetadata:Q}:{},initialMessages:f.initialMessages}},startSession:(f)=>this.startSession(f),getStartedSessionId:(f)=>f.sessionId,readRestoredSession:(f)=>this.getSession(f)})}async runTurn($){let f=this.getSessionOrThrow($.sessionId),J=f.agent.canStartRun(),Q=$.delivery??(f.interactive&&!J?"queue":void 0);if(f.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Q,userImages:$.userImages,userFiles:$.userFiles});return}try{let Z=await this.executeTurn(f,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!f.interactive)await this.finalizeSingleRun(f,Z.finishReason);else await this.completeInteractiveTurn(f,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),Z}catch(Z){if(f.interactive&&f.aborting)return await this.completeAbortedInteractiveTurn(f);throw X2(f.config.telemetry,{component:"core",operation:"session.submit",error:Z,severity:"error",handled:!1,context:{sessionId:f.sessionId,providerId:f.config.providerId,modelId:f.config.modelId}}),await this.failSession(f),Z}}async getAccumulatedUsage($){let f=zQ(this.usageBySession.get($)),J=zQ(this.aggregateUsageBySession.get($));return f||J?{usage:f,aggregateUsage:J}:void 0}async abort($,f){let J=this.sessions.get($);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort(f)}async stopSession($){let f=this.sessions.get($);if(!f)return;if(f.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),f.interactive&&!J0(f.status)){await this.releaseSessionRuntime(f,"session_stop");return}if(f.interactive&&f.agent.canStartRun()){await this.shutdownSession(f,{status:this.resolveInteractiveStopStatus(f),exitCode:this.resolveInteractiveStopExitCode(f),shutdownReason:"session_stop",endReason:"stopped"});return}f.aborting=!0,f.agent.abort(Error("session_stop")),await this.shutdownSession(f,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let f=[...this.sessions.values()];if(f.length===0)return;await Promise.allSettled(f.map((J)=>J.interactive&&!J0(J.status)?this.releaseSessionRuntime(J,$):J.interactive&&J.agent.canStartRun()?this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let f=this.sessions.get($);if(f)return gZ(f);let J=$.trim();if(!J)return;let Q=await this.getRow(J);if(Q)return T4(Q);let Z=await this.readManifest(J);return Z?$5(Z):void 0}async listSessions($=200){let J=(await this.listRows($)).map(T4),Q=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(Q.has(Z.sessionId))continue;J.unshift(gZ(Z))}return J.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let f=await this.invoke("deleteSession",$);if(f.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return f.deleted}async updateSession($,f){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:f.prompt,metadata:f.metadata,title:f.title}))?.updated===!0}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.getRow(f);if(J?.messagesPath)return A1(J.messagesPath);let Q=await this.readManifest(f);return A1(Q?.messages_path)}async dispatchHookEvent($){await EY($,{queueSpawnRequest:(f)=>this.invokeOptional("queueSpawnRequest",f),upsertSubagentSessionFromHook:(f)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",f),appendSubagentHookAudit:(f,J)=>this.invokeOptional("appendSubagentHookAudit",f,J),applySubagentStatus:(f,J)=>this.invokeOptional("applySubagentStatus",f,J)})}subscribe($,f){return this.events.subscribe($,f)}async updateSessionModel($,f){let J=this.getSessionOrThrow($);J.config.modelId=f,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:f}),J.agent.updateConnection({modelId:f})}handlePluginEvent($,f,J){return this.eventBridge.handlePluginEvent($,f,J)}async executeTurn($,f){let J=await this.prepareTurnInput($,f),Q=J.prompt.trim();if(!Q)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Q;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let Z=await this.executeAgentTurn($,Q,J.userImages,J.userFiles);while(bQ($,Z.finishReason)){let W=await kQ($);if(W.length===0)break;let j=IQ($,W);Z=await this.executeAgentTurn($,j)}return Z}async completeInteractiveTurn($,f){if(q6($))return;$.lastInteractiveTurnFinishReason=f,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let f=$.lastInteractiveTurnFinishReason;if(!f)return"cancelled";switch(f){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return f}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let f=new Date,J=$.agent.getMessages(),Q=A0();return $.persistedMessages=J,$.started=$.started||J.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Q,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:f,endedAt:f,durationMs:0}}async executeAgentTurn($,f,J,Q){let Z=$.started||$.agent.getMessages().length>0,W=$.persistedMessages??$.agent.getMessages(),j=this.usageBySession.get($.sessionId)??A0(),X=this.aggregateUsageBySession.get($.sessionId)??j;$.turnUsageBaseline=j,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=A0(),$.turnUsageByAgent=new Map,Jf($.config.telemetry,$.sessionId,$.config.mode),U2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let H=Z?()=>$.agent.continue(f,J,Q):()=>$.agent.run(f,J,Q),Y=await this.runWithAuthRetry($,H,W);$.started=!0;let V=lf(Y.messages,Y,W);$.persistedMessages=V;let A=q4($.turnUsageByAgent?.values()??[]),B=H0(j,Y.usage),G=H0(H0(A0(),Y.usage),A),K=H0(X,G);return this.usageBySession.set($.sessionId,B),this.aggregateUsageBySession.set($.sessionId,K),await this.persistSessionMetadata($.sessionId,(D)=>({...D??{},totalCost:B.totalCost,aggregatedAgentsCost:K.totalCost,usage:B,aggregateUsage:K})),await this.invoke("persistSessionMessages",$.sessionId,V,$.config.systemPrompt),this.observeTaskCompletionTool($,Y),Y}catch(H){throw X2($.config.telemetry,{component:"core",operation:"session.turn",error:H,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),H}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,f){if($.submitAndExitObserved)return;if(!f.toolCalls.some((Q)=>Q.name===f0.SUBMIT_AND_EXIT&&Q.error===void 0))return;$.submitAndExitObserved=!0,x8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,f){let J=$1($.config),Q=pq(f.prompt).trim();if(!Q)return{prompt:"",userImages:f.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles)};let Z=await q2(Q,J);UH($.config.telemetry,Z);let W=y6(Z.prompt,f.mode??$.config.mode),j=this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles),X=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),H=Array.from(new Set([...j,...X]));return{prompt:W,userImages:f.userImages,userFiles:H.length>0?H:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let f=$1($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:f,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,f){let J=this.sessions.get($),Q=await this.invokeOptionalValue("readSessionManifest",$)??J?.artifacts?.manifest,Z=f(Q?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun($,f){if(q6($))return;let J=f==="aborted"||$.aborting,Q=f==="error";await this.shutdownSession($,{status:J?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:f})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,f){if(f.status==="completed"&&!$.submitAndExitObserved)x8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});j5($);let J=[],Q=(Z,W)=>{J.push(W),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:Z,error:W,severity:"warn"}),X2($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,status:f.status,shutdownReason:f.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,f.status,f.exitCode)}catch(Z){Q("update_status",Z)}try{await $.agent.shutdown(f.shutdownReason)}catch(Z){Q("agent_shutdown",Z)}}try{await Promise.resolve($.runtime.shutdown(f.shutdownReason))}catch(Z){Q("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:f.endReason,ts:Date.now()}}),J.length>0&&f.status==="failed")throw J[0]}async releaseSessionRuntime($,f){let J=[],Q=(Z,W)=>{J.push(W),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:Z,error:W,severity:"warn"}),X2($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,reason:f,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(f)}catch(Z){Q("agent_shutdown",Z)}try{await Promise.resolve($.runtime.shutdown(f))}catch(Z){Q("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),J.length>0)throw J[0]}async updateStatus($,f,J){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,f,J);if(!Q.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(Z.status=f,J0(f))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=Q.endedAt??s(),Z.exit_code=typeof J==="number"?J:null;$.artifacts.manifest=Z,$.status=f,$.updatedAt=Q.endedAt??s(),$.endedAt=J0(f)?null:Z.ended_at,$.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,Z),this.emitStatus($.sessionId,f)}async runWithAuthRetry($,f,J){try{return await f()}catch(Q){if(!lq(Q,$.config.providerId))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(J),f()}}async syncOAuthCredentials($,f){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:f?.forceRefresh})}catch(Q){if(Q instanceof C5)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!J?.apiKey||$.config.apiKey===J.apiKey)return;$.config.apiKey=J.apiKey,$.agent.updateConnection({apiKey:J.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow($){let f=this.sessions.get($);if(!f){let J=Error(`session not found: ${$}`);throw X2(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),J}return f}resolveAbsoluteFilePaths($,f){if(!f||f.length===0)return[];let J=f.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>cq(Q)?Q:dZ($,Q));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity($){return y$({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let f=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),J=H0($.initialUsage,f);return this.withPersistedAggregateUsageFloor(J,$.manifest)}async summarizePersistedTeammateUsage($,f,J){let Q=dZ(f),Z=`${J}.messages.json`,W;try{W=vq($)}catch{return A0()}let j=A0();for(let X of W){if(!X.endsWith(".messages.json"))continue;if(X===Z)continue;let H=dZ($,X);if(H===Q)continue;let Y=await A1(H);if(Y.length===0)continue;j=H0(j,g2(Y))}return j}withPersistedAggregateUsageFloor($,f){let J=iq(f.metadata?.aggregateUsage);if(J)return nq($,J);let Q=f.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=$.totalCost)return $;return{...$,totalCost:Q}}emitStatus($,f){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:f}})}async emitSessionSnapshot($){let f=await this.getSession($);if(!f)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:X$({session:f,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),mA))}async getRow($){let f=$.trim();if(!f)return;return(await this.listRows(mA)).find((Q)=>Q.sessionId===f)}async readManifest($){let f=$.trim();if(!f)return;return await this.invokeOptionalValue("readSessionManifest",f)}invoke($,...f){return bA(this.sessionService,$,...f)}invokeOptional($,...f){return kA(this.sessionService,$,...f)}invokeOptionalValue($,...f){return IA(this.sessionService,$,...f)}}function tq($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function sq($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function qA($={}){let f=new B$({sessionService:new A$(new Y$),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||F0.CLI,interactive:!1,config:{providerId:aq(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:sq(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await f.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:tq(Z)}},async abortSession(J){return await f.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function oq($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
|
|
702
|
-
`).trim()||void 0}var gA=120,lZ="...";function x6($){let f=$.trim();if(!f)return"";if(Buffer.byteLength(f,"utf8")<=gA)return f;let J=gA-Buffer.byteLength(lZ,"utf8");if(J<=0)return lZ;let Q="";for(let Z of f){if(Buffer.byteLength(Q+Z,"utf8")>J)break;Q+=Z}return`${Q}${lZ}`}async function vA($){let f=$?.sessionId?.trim()||"unknown",J=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,Z=[...await A1(J)].reverse().find((H)=>H.role==="assistant"),W=Z?oq(Z.content):void 0,j=$?.workspaceRoot?.trim()||"workspace",X=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():j;return{title:`Task completed (${f})`,body:x6(W&&W.length>0?W:X.length>0?X:j),severity:"info"}}import{captureSdkError as x5,createSessionId as qy}from"@cline/shared";import{createSessionId as Jy}from"@cline/shared";import{createSessionId as fy}from"@cline/shared";function eq($){switch($){case"idle":return"idle";case"pending":return"pending";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function $y($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())f.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())f.parentAgentId=$.parentAgentId;if($.agentId?.trim())f.agentId=$.agentId;if($.conversationId?.trim())f.conversationId=$.conversationId;if($.messagesPath?.trim())f.messagesPath=$.messagesPath;if($.prompt?.trim())f.prompt=$.prompt;if($.provider?.trim())f.provider=$.provider;if($.model?.trim())f.model=$.model;if($.source?.trim())f.source=$.source;if(typeof $.pid==="number")f.pid=$.pid;return Object.keys(f).length>0?f:void 0}function b5($,f,J,Q){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:f?.createdByClientId??"hub",status:eq($.status),participants:f?[...f.participants.values()]:[],metadata:$y($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function u($,f){return{version:$.version,requestId:$.requestId,ok:!0,...f!==void 0?{payload:f}:{}}}function m($,f,J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:f,message:J}}}function k5($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function h0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function H2($,f,J){return{version:"v1",event:$,eventId:fy("hevt_"),sessionId:J,timestamp:Date.now(),payload:f}}async function r0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let Q=await $.sessionHost.getAccumulatedUsage?.(f);return b5(J,$.sessionState.get(f),Q?.usage,Q?.aggregateUsage)}async function i0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let[Q,Z]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(f):[],$.sessionHost.getAccumulatedUsage?.(f)]);return X$({session:J,messages:Q,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function I5($,f,J,Q,Z={}){let W=$.sessionState.get(f);if(W){if(Z.interactive!==void 0)W.interactive=Z.interactive;if(!W.participants.has(J))W.participants.set(J,{clientId:J,attachedAt:Date.now(),role:Q});return W}let j={createdByClientId:J,interactive:Z.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(f,j),j}async function pZ($,f){let J=Jy("approval_"),Q=f.sessionId;if($.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((W)=>{$.pendingApprovals.set(J,{sessionId:Q,resolve:W}),$.publish($.buildEvent("approval.requested",{approvalId:J,sessionId:f.sessionId,agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,toolCallId:f.toolCallId,toolName:f.toolName,inputJson:JSON.stringify(f.input??null),policy:f.policy},Q))})}function rZ($,f,J){let Q=$.pendingApprovals.get(f);if(!Q)return;return $.pendingApprovals.delete(f),Q.resolve(J),{sessionId:Q.sessionId}}function iZ($,f,J){let Q=0;for(let[Z,W]of[...$.pendingApprovals.entries()]){if(!f({approvalId:Z,sessionId:W.sessionId}))continue;$.pendingApprovals.delete(Z),W.resolve({approved:!1,reason:J}),$.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},W.sessionId)),Q+=1}return Q}async function uA($,f){let J=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"";if(!$.pendingApprovals.get(J))return m(f,"approval_not_found",`Unknown approval: ${J}`);let Z=typeof f.payload?.reason==="string"?f.payload.reason:f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)&&typeof f.payload.payload.reason==="string"?f.payload.payload.reason:void 0,W=f.payload?.approved===!0,j=rZ($,J,{approved:W,reason:Z});if(!j)return m(f,"approval_not_found",`Unknown approval: ${J}`);return $.publish($.buildEvent("approval.resolved",{approvalId:J,approved:W,reason:Z},j.sessionId)),u(f,{approvalId:J,approved:W})}import{createSessionId as Wy}from"@cline/shared";function Qy($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var cA={debug:10,info:20,warn:30,error:40,silent:50};function Zy(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function g($,f,J={}){if(cA[$]<cA[Zy()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:f,...Object.fromEntries(Object.entries(J).map(([Z,W])=>[Z,Qy(W)]).filter(([,Z])=>Z!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function nZ($,f){let J=f instanceof Error?f.stack||f.message:String(f);g("error",$,{error:J})}async function dA($,f,J,Q,Z,W){let j=Wy("capreq_"),X=performance.now();return g("info","capability.request.start",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z}),await new Promise((H,Y)=>{$.pendingCapabilityRequests.set(j,{sessionId:f,targetClientId:Z,capabilityName:J,onProgress:W,resolve:(V)=>{if(g(V.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z,ok:V.ok,error:V.error,durationMs:Math.round(performance.now()-X)}),!V.ok){Y(Error(V.error||`Capability ${J} was rejected by ${Z}.`));return}H(V.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:Q},f)),g("info","capability.request.published",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z})})}function lA($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(J);if(!Q)return m(f,"capability_not_found",`Unknown capability request: ${J}`);if((f.clientId?.trim()||"")!==Q.targetClientId)return m(f,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==Q.sessionId)return m(f,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{};return Q.onProgress?.(W),u(f,{requestId:J})}function F1($,f,J){let Q=0;for(let[Z,W]of[...$.pendingCapabilityRequests.entries()]){if(!f({requestId:Z,...W}))continue;$.pendingCapabilityRequests.delete(Z),g("warn","capability.request.cancelled",{requestId:Z,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,reason:J}),W.resolve({ok:!1,error:J}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:W.capabilityName,targetClientId:W.targetClientId,ok:!1,cancelled:!0,error:J},W.sessionId)),Q+=1}return Q}async function pA($,f){let J=typeof f.payload?.sessionId==="string"?f.payload.sessionId.trim():f.sessionId?.trim()||"",Q=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName.trim():"",Z=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId.trim():"";if(!J||!Q||!Z)return m(f,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=await $.requestCapability(J,Q,W,Z);return u(f,j)}catch(W){return m(f,"capability_request_failed",W instanceof Error?W.message:String(W))}}function rA($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(J);if(!Q)return m(f,"capability_not_found",`Unknown capability request: ${J}`);let Z=f.clientId?.trim()||"";if(Z!==Q.targetClientId)return m(f,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==Q.sessionId)return m(f,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);$.pendingCapabilityRequests.delete(J);let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:void 0,j=typeof f.payload?.error==="string"?f.payload.error:void 0,X=f.payload?.ok===!0;return g(X?"info":"warn","capability.respond",{requestId:J,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:X,error:j}),Q.resolve({ok:X,payload:W,error:j}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:X,payload:W,error:j},Q.sessionId)),u(f,{requestId:J,ok:X})}import{createSessionId as jy}from"@cline/shared";function iA($,f){let J=f.payload,Q=J?.clientId?.trim()||f.clientId?.trim()||jy("client_");return $.clients.set(Q,{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),u(f,{clientId:Q})}function nA($,f){let J=f.clientId?.trim(),Q=J?$.clients.get(J):void 0;if(!J||!Q)return m(f,"client_not_found","Client is not registered with this hub.");let Z=k5(f.payload?.metadata);if(Q.lastSeenAt=Date.now(),Z)Q.metadata=JSON.parse(JSON.stringify(Z));return u(f)}function aA($,f,J){let Q=f.clientId?.trim();if(Q)$.clients.delete(Q),J(Q),$.publish($.buildEvent("hub.client.disconnected",{clientId:Q}));return u(f)}function tA($,f){return u(f,{clients:[...$.clients.values()]})}var Xy=30000;function Hy($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function Yy($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function Vy($){return $?$:void 0}function Ay($){let f=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(f&&Number.isFinite(f)&&f>0)return Math.floor(f);let J=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function By($,f,J,Q){let Z=performance.now(),W=!1,j={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J.sessionId,timeoutMs:Q},X=setInterval(()=>{if(W)return;let V=Math.round(performance.now()-Z);g("warn","run.heartbeat",{...j,elapsedMs:V}),$.publish($.buildEvent("run.heartbeat",{requestId:f.requestId,elapsedMs:V,...Q?{timeoutMs:Q}:{}},J.sessionId))},Xy),H=$.sessionHost.runTurn(J);H.then((V)=>{if(!W)return;g("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:V?.finishReason})},(V)=>{if(!W)return;g("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:V})});let Y;try{if(!Q)return await H;return await Promise.race([H,new Promise((V,A)=>{Y=setTimeout(()=>{let B=`Hub run ${f.command} timed out after ${Q}ms.`;W=!0,clearInterval(X),A(Error(B)),g("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),iZ($,(G)=>G.sessionId===J.sessionId,B),F1($,(G)=>G.sessionId===J.sessionId,B),$.sessionHost.abort(J.sessionId,B).catch((G)=>{g("error","run.timeout_abort_failed",{...j,error:G})})},Q)})])}finally{if(W=!0,clearInterval(X),Y)clearTimeout(Y)}}async function sA($,f){let J=h0(f),Q=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!Z.trim())return m(f,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,J));let W=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,j=Array.isArray(W?.userFiles)?W.userFiles.filter((V)=>typeof V==="string"):void 0,X=Ay(Q);$.suppressNextTerminalEventBySession.set(J,"run.start.reply");let H;try{H=await By($,f,{sessionId:J,prompt:Z,mode:Vy(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(W?.userImages)?W.userImages:void 0,userFiles:j,timeoutMs:X},X)}catch(V){if($.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J);throw $.publish($.buildEvent("run.failed",{reason:"error",error:V instanceof Error?V.message:String(V)},J)),V}if(H){let V=await i0($,J),A=Yy(H);if($.publish($.buildEvent(Hy(H.finishReason),{reason:H.finishReason,...A?{error:A}:{},result:H,...V?{snapshot:V}:{}},J)),$.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J)}else $.suppressNextTerminalEventBySession.delete(J);let Y=await i0($,J);return u(f,H||Y?{...H?{result:H}:{},...Y?{snapshot:Y}:{}}:void 0)}async function oA($,f){let J=h0(f),Q=typeof f.payload?.reason==="string"?f.payload.reason:"Run was aborted before pending approval or capability request was resolved.";iZ($,(Z)=>Z.sessionId===J,Q);try{await $.sessionHost.abort(J,f.payload?.reason)}catch(Z){g("warn","run.abort_failed",{command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J,error:Z})}finally{F1($,(Z)=>Z.sessionId===J,Q)}return u(f,{applied:!0})}async function eA($,f){let J=R8(f.payload?.payload);if(!J)return m(f,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(J),u(f,{applied:!0})}async function $B($,f){switch(f.type){case"chunk":return;case"agent_event":await Gy($,f);return;case"hook":if(f.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:f.payload.toolName},f.payload.sessionId));else if(f.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:f.payload.toolName},f.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:f.payload.sessionId,summary:f.payload.summary,lastEvent:f.payload.lifecycle};$.publish($.buildEvent("team.progress",J,f.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:f.payload.sessionId,prompts:f.payload.prompts},f.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:f.payload.id,prompt:f.payload.prompt,delivery:f.payload.delivery,attachmentCount:f.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:f.payload.sessionId,prompt:J},f.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:f.payload.sessionId,snapshot:f.payload.snapshot},f.payload.sessionId));return;case"status":{let[J,Q]=await Promise.all([r0($,f.payload.sessionId),i0($,f.payload.sessionId)]);if(J)$.publish($.buildEvent("session.updated",{session:J,...Q?{snapshot:Q}:{}},f.payload.sessionId));return}case"ended":await Ky($,f);return;default:return}}async function Gy($,f){let{sessionId:J,event:Q}=f.payload;if(Q.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Q.iteration},J));return}if(Q.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},J));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Q.text},J));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},J));return}if(Q.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},J));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Q.text},J));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Q.reasoning},J));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},J));break}return}if(Q.type==="usage"){let Z;try{Z=await $.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}$.publish($.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:Z?.usage,aggregateUsage:Z?.aggregateUsage,agent:{kind:f.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:f.payload.teamAgentId,teamRole:f.payload.teamRole}},J));return}if(Q.type==="done")$.publish($.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},J))}async function Ky($,f){let J=$.suppressNextTerminalEventBySession.get(f.payload.sessionId),Q=J===f.payload.reason||J==="run.start.reply";if(Q)$.suppressNextTerminalEventBySession.delete(f.payload.sessionId);let[Z,W]=await Promise.all([r0($,f.payload.sessionId),i0($,f.payload.sessionId)]);if(f.payload.reason==="completed"){let j=await vA(Z);$.publish($.buildEvent("ui.notify",j,f.payload.sessionId))}if(Q)return;$.publish($.buildEvent(f.payload.reason==="aborted"?"run.aborted":f.payload.reason==="error"||f.payload.reason==="failed"?"run.failed":"run.completed",{reason:f.payload.reason,...W?{snapshot:W}:{}},f.payload.sessionId))}import{createSessionId as JB,parseRuntimeConfigExtensions as QB}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Rd,HUB_COMPACTION_CAPABILITY as Ld,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Od,HUB_HOOK_CAPABILITY_PREFIX as zd,HUB_MISTAKE_LIMIT_CAPABILITY as _d,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Nd,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Td,isHubToolExecutorName as Fy}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Sd,HUB_COMPACTION_CAPABILITY as hd,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Cd,HUB_HOOK_CAPABILITY_PREFIX as Ed,HUB_MISTAKE_LIMIT_CAPABILITY as bd,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as kd,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Id}from"@cline/shared";var Py=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function Y2($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function Uy($,f){let J=typeof $.name==="string"?$.name.trim():"",Q=typeof $.description==="string"?$.description:"",Z=typeof $.capabilityName==="string"?$.capabilityName.trim():"",W=Y2($.inputSchema);if(!J||!Q||!W||!Z||f.has(Z))return;return f.add(Z),{kind:"tool",capabilityName:Z,name:J,description:Q,inputSchema:W,...Y2($.lifecycle)?{lifecycle:Y2($.lifecycle)}:{}}}function tZ($){if(!Array.isArray($))return[];let f=[],J=new Set;for(let Q of $){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let Z=Q,W=Z.kind,j=typeof Z.capabilityName==="string"?Z.capabilityName.trim():"";if(!j||J.has(j))continue;if(W==="tool"){let X=Uy(Z,J);if(X)f.push(X);continue}if(W==="toolExecutor"){let X=Z.executor;if(!Fy(X))continue;J.add(j),f.push({kind:"toolExecutor",capabilityName:j,executor:X});continue}if(W==="hook"){let X=typeof Z.name==="string"?Z.name.trim():"";if(!X)continue;J.add(j),f.push({kind:"hook",capabilityName:j,name:X});continue}if(W==="compaction"){J.add(j),f.push({kind:"compaction",capabilityName:j,...Y2(Z.config)?{config:Y2(Z.config)}:{}});continue}if(W==="checkpoint"){J.add(j),f.push({kind:"checkpoint",capabilityName:j,...Y2(Z.config)?{config:Y2(Z.config)}:{}});continue}if(W==="mistakeLimit"){J.add(j),f.push({kind:"mistakeLimit",capabilityName:j});continue}if(W==="userInstructionService")J.add(j),f.push({kind:"userInstructionService",capabilityName:j})}return f}function fB($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function Dy($){return Object.hasOwn($,"update")?$.update:$}function c6($){return $.trim().replace(/^\/+/,"").toLowerCase()}function Ry($){let f=($??[]).map(c6).filter(Boolean);return f.length>0?new Set(f):void 0}function Ly($,f,J){if(!J)return!0;let Q=c6($),Z=c6(f),W=Q.includes(":")?Q.split(":").at(-1)??Q:Q,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(Q)||J.has(Z)||J.has(W)||J.has(j)}function aZ($,f){let J=Ry(f);return $.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>Ly(Q.id,Q.name,J))}function Oy($,f){let J=async(Q,Z)=>{let W=c6(Q),X=aZ($,f).filter((B)=>B.id===W||c6(B.name)===W||B.id.endsWith(`:${W}`)).filter((B)=>!B.disabled);if(X.length!==1)return X.length>1?`Skill "${Q}" is ambiguous. Use one of: ${X.map((B)=>B.id).join(", ")}`:`Skill "${Q}" not found.`;let H=X[0].skill,Y=Z?.trim(),V=Y?`
|
|
703
|
-
<command-args>${Y}</command-args>`:"",
|
|
704
|
-
|
|
705
|
-
`:"";return`<command-name>${
|
|
693
|
+
version = team_outcome_fragments.version + 1`,[W,Q.outcomeId,Q.id,Q.section,Q.sourceAgentId,Q.sourceRunId??null,Q.content,Q.status,Q.reviewedBy??null,Q.reviewedAt?Q.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,f){let J=k2($),W=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(W.length===0)return[];let Z=MQ();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
|
|
694
|
+
WHERE team_name = ? AND status IN ('queued', 'running')`,[f,Z,J]),W.map((Q)=>Q.run_id)}handleTeamEvent($,f){this.appendTeamEvent($,f.type,f)}}function yQ($={}){try{let f=new Uf($);return f.init(),f}catch{let f=new tJ({teamDir:$.teamDir});return f.init(),f}}function k5($,f){return SM($,f)}function CM($,f){let J=f?.["*"]??{},W=f?.[$]??{};return{...J,...W}.enabled!==!1}function EM($,f){return $.filter((J)=>CM(J.name,f))}function MV($,f){return S1(EM($,f))}function I5(){return`team-${hM(5)}`}function qQ($,f,J,W,Z,Q,j,H){let X=m0[E$({mode:J})],Y=uf(f,W,J,Z??vf);return MV(p1({cwd:$,...X,enableSkills:!!j,...Y,executors:{...j?{skills:j}:{},...H??{}}}),Q)}function bM($){return qQ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,kM,$.toolExecutors).some((f)=>f.name==="skills")}var kM=async()=>"";async function IM($){let f=z0();if(!x$({filePath:f}))return{tools:[]};let J=new Vf({clientFactory:O2({settingsPath:f})}),W;try{W=await Af(J,{filePath:f})}catch(H){await J.dispose().catch(()=>{});let X=H instanceof Error?H.message:String(H);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${X}`),{tools:[]}}let Z=W.filter((H)=>H.disabled!==!0),Q=await Promise.allSettled(Z.map((H)=>_2({serverName:H.name,provider:J}))),j=[];for(let[H,X]of Q.entries())if(X.status==="fulfilled")j.push(...X.value);else{let Y=X.reason instanceof Error?X.reason.message:String(X.reason);$?.log(`[mcp] Failed to load tools from MCP server "${Z[H].name}", skipping: ${Y}`)}return{tools:j,shutdown:async()=>{await J.dispose()}}}function xM($,f){if(!$)return;for(let J of $.getTeammateIds())try{$.shutdownTeammate(J,f)}catch{}}function mM($){if($===void 0)return!0;switch($){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function gM($){let f=m0[E$({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??f.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??f.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class I2{teamRuntimeEntries=new Map;async build($){let{config:f,hooks:J,extensions:W,logger:Z,telemetry:Q,createSpawnTool:j,onTeamRestored:H,userInstructionService:X,configExtensions:Y,toolExecutors:A}=$,V=$.onTeamEvent??(()=>{}),B=gM(f),K=W$(),G=[],R=f.teamName?.trim()||I5(),P=f.sessionId?.trim()||R,F=k5(Y,"rules"),U=k5(Y,"skills"),_=k5(Y,"workflows"),z=k5(Y,"plugins"),D=F||U||_,O=!1,N=Boolean(X),q=X,$0;if(!q&&D)q=F1({skills:U?{workspacePath:f.cwd,includePluginSkills:z,pluginSkillDirectories:z?$.pluginSkillDirectories:void 0,pluginPaths:f.pluginPaths,cwd:f.cwd}:{workspacePath:f.cwd},rules:{workspacePath:f.cwd},workflows:{workspacePath:f.cwd}});if(q)await q.start().catch(()=>{});let Y0=B.enableTools&&U&&Boolean(q)&&q?.hasConfiguredSkills(f.skills)===!0&&bM({cwd:f.cwd,providerId:f.providerId,mode:B.mode,modelId:f.modelId,toolRoutingRules:f.toolRoutingRules,toolPolicies:f.toolPolicies,toolExecutors:A}),o=q&&D?q.createExtension({includeRules:F,includeSkills:U,includeWorkflows:_,registerSkillsTool:Y0,allowedSkillNames:f.skills}):void 0,A0=o?[...W??f.extensions??[],o]:W??f.extensions;if(B.enableTools){if(G.push(...qQ(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,A)),!B.disableMcpSettingsTools){let r=await IM(f.logger);G.push(...r.tools),$0=r.shutdown}}let i,J$=B.enableAgentTeams?yQ():void 0,p=J$?.loadRuntime(P),n0=p?.state,k=p?.teammates??[],D0=new Map(k.map((r)=>[r.agentId,r])),n=f.sessionId||R,a0,T1=[],N1=!1,_f=df({providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey??"",baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:J,extensions:A0,logger:Z??f.logger,telemetry:$.telemetry??f.telemetry,workspaceMetadata:f.workspaceMetadata});if(!this.teamRuntimeEntries.has(n))this.teamRuntimeEntries.set(n,{delegatedAgentConfigProvider:_f});let c2=()=>{if(!B.enableAgentTeams)return;let r=this.teamRuntimeEntries.get(n)??{delegatedAgentConfigProvider:_f};if(this.teamRuntimeEntries.set(n,r),i=r.runtime,!i){if(i=new Gf({teamName:R,leadAgentId:f.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(f0)=>{if(V(f0),i&&J$){if(f0.type==="teammate_spawned"&&f0.teammate?.rolePrompt){let D$={agentId:f0.agentId,rolePrompt:f0.teammate.rolePrompt,modelId:f0.teammate.modelId,maxIterations:f0.teammate.maxIterations};D0.set(D$.agentId,D$)}if(f0.type==="teammate_shutdown"&&!mM(f0.reason))D0.delete(f0.agentId);J$.handleTeamEvent(P,f0),J$.persistRuntime(P,i.exportState(),Array.from(D0.values()))}}}),n0)i.hydrateState(n0),N1=!0;r.runtime=i}if(!O){if(!i)return;O=!0;let f0=rf({runtime:i,leadAgentId:f.sessionId||"lead",restoredFromPersistence:Boolean(n0),restoredTeammates:k,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(D$)=>{T1=D$,a0?.addTools(D$)},createBaseTools:B.enableTools?()=>qQ(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,A):void 0,teammateConfigProvider:_f});if(N1)i.recoverActiveRuns("runtime_recovered");if(f0.restoredFromPersistence)H?.();G.push(...f0.tools)}return i};if(B.enableSpawnAgent&&j){let r=j();G.push({...r,execute:async(f0,D$)=>{return c2(),r.execute(f0,D$)}})}if(B.enableAgentTeams)c2();let X4=MV(G,f.toolPolicies),AW=X4.some((r)=>r.name===J0.SUBMIT_AND_EXIT&&r.lifecycle?.completesRun===!0),zf=B.enableAgentTeams?()=>{let r=this.teamRuntimeEntries.get(n)?.runtime;if(!r)return;let f0=r.listTasks(),D$=f0.some((d$)=>d$.status==="in_progress"||d$.status==="pending"),m7=r.listRuns({}),zK=m7.some((d$)=>d$.status==="running"||d$.status==="queued");if(D$||zK){let d$=f0.filter((h0)=>h0.status==="in_progress"||h0.status==="pending").map((h0)=>`${h0.id} (${h0.status}): ${h0.title}`).join(", "),g7=m7.filter((h0)=>h0.status==="running"||h0.status==="queued").map((h0)=>`${h0.id} (${h0.status})`).join(", "),VW=[];if(d$)VW.push(`Unfinished tasks: ${d$}`);if(g7)VW.push(`Active runs: ${g7}`);return`[SYSTEM] You still have team obligations. ${VW.join(". ")}. Use team_run_task to delegate work, or team_task with action=complete to mark tasks done, or team_await_runs to wait for active runs. Do NOT stop until all tasks are completed.`}return}:void 0,d2=AW?{requireCompletionTool:!0,...zf?{completionGuard:zf}:{}}:zf?{completionGuard:zf}:void 0;return{tools:X4,logger:Z??f.logger,telemetry:Q??f.telemetry,teamRuntime:i,teamRestoredFromPersistence:Boolean(n0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(n)?.delegatedAgentConfigProvider??_f,extensions:A0,completionPolicy:d2,registerLeadAgent:(r)=>{if(a0=r,T1.length>0)r.addTools(S1(T1,[...K]))},shutdown:async(r)=>{if(xM(i,r),this.teamRuntimeEntries.delete(n),await $0?.(),!N)q?.stop()}}}}var wV={};w(wV,{requestDesktopToolApproval:()=>SQ});import{mkdir as vM,readFile as uM,unlink as cM,writeFile as dM}from"node:fs/promises";import{join as qV}from"node:path";function lM($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function pM($){return new Promise((f)=>setTimeout(f,$))}async function wQ($){try{await cM($)}catch{}}async function SQ($,f={}){let J=f.approvalDir?.trim(),W=f.sessionId?.trim();if(!J||!W)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await vM(J,{recursive:!0});let Z=lM(`${$.toolCallId}`),Q=qV(J,`${W}.request.${Z}.json`),j=qV(J,`${W}.decision.${Z}.json`),H=f.nowIso??(()=>new Date().toISOString());await dM(Q,`${JSON.stringify({requestId:Z,sessionId:W,createdAt:H(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
|
|
695
|
+
`,"utf8");let X=f.timeoutMs??300000,Y=f.pollIntervalMs??200,A=Date.now();while(Date.now()-A<X){try{let V=await uM(j,"utf8"),B=JSON.parse(V),K={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([wQ(j),wQ(Q)]),K}catch{}await pM(Y)}return await wQ(Q),{approved:!1,reason:"Tool approval request timed out"}}Z$();Z$();var EV={};w(EV,{uninstallPlugin:()=>mQ});import{existsSync as m2,readdirSync as rM,readFileSync as iM,rmdirSync as nM,rmSync as aM,statSync as tM}from"node:fs";import{basename as l0,dirname as O1,extname as sM,isAbsolute as oM,join as c$,relative as eM,resolve as x2,sep as hQ}from"node:path";import{discoverPluginModulePaths as $y,resolvePluginConfigSearchPaths as fy}from"@cline/shared/storage";var IQ="_installed",Jy="package",Wy=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function CQ($){return $.trim().toLowerCase()}function f$($,f){let J=f?.trim();if(!J)return;$.add(J)}function Zy($){return $.replace(/-[0-9a-f]{12}$/i,"")}function EQ($){let f=sM($);return f?$.slice(0,-f.length):$}function bQ($){if(!m2($))return;try{let f=JSON.parse(iM($,"utf8"));return typeof f.name==="string"?f.name.trim():void 0}catch{return}}function xQ($,f){let J=eM(f,$);return J===""||!J.startsWith("..")&&!oM(J)}function SV($){let J=x2($).split(hQ),W=J.lastIndexOf(IQ);if(W<0)return;let Z=J[W+1];if(!Z)return;let Q=Wy.get(Z)??1,j=W+2+Q;if(J.length<j)return;let H=J.slice(0,j).join(hQ)||hQ;return m2(H)?H:void 0}function x5($){try{return rM($,{withFileTypes:!0})}catch{return[]}}function Qy($){let f=c$($,IQ);if(!m2(f))return[];let J=[];for(let W of x5(f)){if(!W.isDirectory())continue;let Z=c$(f,W.name);if(W.name==="git"){for(let Q of x5(Z)){if(!Q.isDirectory())continue;let j=c$(Z,Q.name);for(let H of x5(j))if(H.isDirectory())J.push(c$(j,H.name))}continue}for(let Q of x5(Z))if(Q.isDirectory())J.push(c$(Z,Q.name))}return J.sort((W,Z)=>W.localeCompare(Z))}function hV($){try{return $y($)}catch{return[]}}function kQ($){let f=hV($),J=new Set;f$(J,l0($)),f$(J,Zy(l0($))),f$(J,bQ(c$($,"package.json"))),f$(J,bQ(c$($,Jy,"package.json")));for(let W of f)f$(J,l0(W)),f$(J,EQ(l0(W)));return{installPath:$,entryPaths:f,names:[...J].sort((W,Z)=>W.localeCompare(Z)),installed:!0}}function jy($,f){let J=x2($),W=f.find((j)=>xQ(J,j));if(!W)return;let Z=O1(J);while(Z!==W&&Z!==O1(Z)){if(m2(c$(Z,"package.json")))return Z;Z=O1(Z)}let Q=l0(J);if((Q==="index.ts"||Q==="index.js")&&O1(J)!==W)return O1(J);return J}function CV($,f){let J=jy($,f);if(!J)return;let W=new Set;return f$(W,l0($)),f$(W,EQ(l0($))),f$(W,l0(J)),f$(W,EQ(l0(J))),f$(W,bQ(c$(J,"package.json"))),{installPath:J,entryPaths:[$],names:[...W].sort((Z,Q)=>Z.localeCompare(Q)),installed:!1}}function Hy($){let f=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return fy(f).filter((J)=>m2(J))}function Xy($){let f=new Map;for(let J of $){for(let W of Qy(J))f.set(W,kQ(W));for(let W of hV(J)){let Z=SV(W);if(Z){if(!f.has(Z))f.set(Z,kQ(Z));continue}let Q=CV(W,$);if(Q)f.set(Q.installPath,Q)}}return[...f.values()].sort((J,W)=>J.installPath.localeCompare(W.installPath))}function Yy($,f){let J=CQ(f);if(!J)return!1;if(CQ($.installPath)===J)return!0;return $.names.some((W)=>CQ(W)===J)}function Ay($,f,J){let W=x2($);for(let Q of f){if(xQ(W,Q.installPath))return Q;if(Q.entryPaths.some((j)=>x2(j)===W))return Q}let Z=SV(W);if(Z)return kQ(Z);if(m2(W))return CV(W,J);return}function Vy($){let f=E0(),J=f.disabledPlugins;if(!J?.length)return;let W=J.filter((Z)=>{let Q=x2(Z);if(xQ(Q,$.installPath))return!1;return!$.entryPaths.some((j)=>x2(j)===Q)});if(W.length===J.length)return;a$({...f,disabledPlugins:W})}function By($){let f=O1($);while(f!==O1(f)&&l0(f)!==IQ){try{nM(f)}catch{return}f=O1(f)}}function Ky($){return`${$.names[0]??l0($.installPath)} at ${$.installPath}`}async function mQ($){let f=Hy($),J=Xy(f),W=$.path?.trim(),Z=$.name?.trim(),Q;if(W){if(Q=Ay(W,J,f),!Q)throw Error(`No plugin found at ${W}`)}else{if(!Z)throw Error("plugin uninstall requires a plugin name");let H=J.filter((X)=>Yy(X,Z));if(H.length===0)throw Error(`No plugin found matching "${Z}"`);if(H.length>1)throw Error(`Multiple plugins match "${Z}": ${H.map(Ky).join(", ")}`);Q=H[0]}let j=tM(Q.installPath,{throwIfNoEntry:!1});if(!j)throw Error(`Plugin install path does not exist: ${Q.installPath}`);if(aM(Q.installPath,{recursive:j.isDirectory(),force:!0}),Vy(Q),Q.installed)By(Q.installPath);return{name:Z||Q.names[0]||l0(Q.installPath),installPath:Q.installPath,removedPaths:[Q.installPath],entryPaths:Q.entryPaths}}var eV={};w(eV,{updateLocalProvider:()=>p5,saveLocalProviderSettings:()=>rQ,saveLocalProviderOAuthCredentials:()=>tQ,resolveLocalClineAuthToken:()=>sQ,refreshProviderModelsFromSource:()=>iQ,normalizeOAuthProvider:()=>nQ,loginLocalProvider:()=>aQ,listLocalProviders:()=>lQ,getLocalProviderModels:()=>pQ,ensureCustomProvidersLoaded:()=>c5,deleteLocalProvider:()=>r5,addLocalProvider:()=>dQ});import*as T0 from"@cline/llms";import{getClineEnvironmentConfig as by}from"@cline/shared";import{existsSync as Gy,mkdirSync as Py,readFileSync as Fy,writeFileSync as Uy}from"node:fs";import{mkdir as Ry,readFile as Dy,writeFile as Ly}from"node:fs/promises";import{dirname as gQ,join as Oy}from"node:path";import*as q0 from"@cline/llms";import{ModelCapabilitySchema as _y,ProviderCapabilitySchema as zy,ProviderClientSchema as Ty,ProviderProtocolSchema as Ny}from"@cline/shared";import{z as l}from"zod";var My=l.object({id:l.string().optional(),name:l.string().optional(),maxTokens:l.number().optional(),contextWindow:l.number().optional(),maxInputTokens:l.number().optional(),capabilities:l.array(_y).optional(),supportsVision:l.boolean().optional(),supportsAttachments:l.boolean().optional(),supportsReasoning:l.boolean().optional()}).passthrough(),yy=l.object({name:l.string(),baseUrl:l.string(),defaultModelId:l.string().optional(),protocol:Ny.optional(),client:Ty.optional(),capabilities:l.array(zy).optional(),modelsSourceUrl:l.string().optional()}).passthrough(),bV=l.object({provider:yy.optional(),models:l.record(l.string(),My).optional()}).passthrough(),kV=l.object({version:l.literal(1),providers:l.record(l.string(),bV)}),qy=l.object({version:l.literal(1),providers:l.record(l.string(),l.unknown())}),m5=new Set;function IV($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function Rf($){return Oy(gQ($.getFilePath()),"models.json")}function g5(){return{version:1,providers:{}}}function xV($){let f=qy.safeParse($);if(!f.success)return g5();let J={};for(let[W,Z]of Object.entries(f.data.providers)){let Q=bV.safeParse(Z);if(Q.success)J[W]=Q.data}return{version:1,providers:J}}function vQ($){if(!Gy($))return g5();try{let f=Fy($,"utf8");return xV(JSON.parse(f))}catch{}return g5()}async function g2($){try{let f=await Dy($,"utf8");return xV(JSON.parse(f))}catch{}return g5()}function mV($,f){Py(gQ($),{recursive:!0});let J=kV.parse(f);Uy($,`${JSON.stringify(J,null,2)}
|
|
696
|
+
`,"utf8")}async function v5($,f){await Ry(gQ($),{recursive:!0});let J=kV.parse(f);await Ly($,`${JSON.stringify(J,null,2)}
|
|
697
|
+
`,"utf8")}function gV($,f){return{id:$,name:f.name??$,supportsAttachments:f.capabilities?.includes("files"),supportsVision:f.capabilities?.includes("images"),supportsReasoning:f.capabilities?.includes("reasoning")||f.thinkingConfig!=null}}function vV($){if(!$||$.length===0)return;let f=new Set;if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("tools"))f.add("tools");return f.size>0?[...f]:void 0}function uV($){let f=new Set;if(!$||$.length===0)return[...f];if($.includes("streaming"))f.add("streaming");if($.includes("tools"))f.add("tools");if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("vision"))f.add("images"),f.add("files");return[...f]}function wy($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function cV($,f){return $??f??"openai-chat"}function dV($,f,J){return $??J??(f==="openai-responses"?"openai":"openai-compatible")}function lV($,f,J){let W=new Set(f?.capabilities??J??[]);if(f?.supportsVision)W.add("images");if(f?.supportsAttachments)W.add("files");if(f?.supportsReasoning)W.add("reasoning");return{id:$,name:f?.name??$,maxTokens:f?.maxTokens,contextWindow:f?.contextWindow,maxInputTokens:f?.maxInputTokens,capabilities:W.size>0?[...W]:void 0}}function Sy($,f){for(let[J,W]of Object.entries(f??{})){let Z=W.id?.trim()||J.trim();if(!Z)continue;q0.registerModel($,Z,lV(Z,W))}}function hy($,f,J){return{...f??{},id:$,name:f?.name??$,capabilities:f?.capabilities??J}}function Cy($){return Object.assign({},...q0.resolveProviderModelCatalogKeys($).map((J)=>q0.getGeneratedModelsForProvider(J)))}function Ey($){let f=$.provider.trim();if(!f||q0.isBuiltInProviderId(f))return;let J=$.baseUrl?.trim();if(!J)return;let W=q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=Cy(f),Q=uV($.capabilities),j=Q.length>0?Q:void 0,H=$.model?.trim(),X={...Z,...W?.models??{}};if(H)X[H]=hy(H,X[H],j);let Y=Object.keys(X).filter(Boolean),A=H||Y[0];if(!A)return;let V=cV($.protocol,W?.provider.protocol),B=dV($.client,V,W?.provider.client);q0.registerProvider({provider:{id:f,name:W?.provider.name??IV(f),description:W?.provider.description,protocol:V,client:B,baseUrl:J,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:A,capabilities:vV($.capabilities)??W?.provider.capabilities,source:"file"},models:X})}function u5($){for(let f of Object.values($.providers))Ey(f.settings)}function sJ($,f){let J=f.models??{};if(!wy(f.provider)){Sy($,J);return}let W=uV(f.provider.capabilities),Z=Object.entries(J).map(([Y,A])=>({id:A.id?.trim()||Y.trim(),model:A})).filter(({id:Y})=>Y.length>0),Q=f.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=cV(f.provider.protocol,void 0),H=dV(f.provider.client,j,void 0),X=Object.fromEntries(Z.map(({id:Y,model:A})=>[Y,{...lV(Y,A,W.length>0?W:void 0),status:"active"}]));q0.registerProvider({provider:{id:$,name:f.provider.name.trim()||IV($),protocol:j,client:H,baseUrl:f.provider.baseUrl,modelsSourceUrl:f.provider.modelsSourceUrl,defaultModelId:Q,capabilities:vV(f.provider.capabilities),source:"file"},models:X})}function pV($){let f=Rf($);if(m5.has(f))return;let J=vQ(f);for(let[W,Z]of Object.entries(J.providers))sJ(W,Z);m5.add(f)}async function c5($){let f=Rf($);if(m5.has(f))return;let J=await g2(f);for(let[W,Z]of Object.entries(J.providers))sJ(W,Z);m5.add(f)}function ky($){return $.apiKey??$.auth?.apiKey}function Iy($){return($.auth?.accessToken?.trim()??"").length>0}function iV($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function xy($){let f=$.split(/\s+/).filter(Boolean);if(f.length===0)return"?";if(f.length===1)return f[0].slice(0,2).toUpperCase();return`${f[0][0]}${f[1][0]}`.toUpperCase()}function my($){let f=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let W of $)J=J*31+W.charCodeAt(0)>>>0;return f[J%f.length]}function nV($){return Object.entries($).sort(([f],[J])=>f.localeCompare(J)).map(([f,J])=>gV(f,J))}async function gy($,f){let J=await T0.getModelsForProvider($);if(!f)return J;let W=await HJ($,{loadPrivateOnAuth:!0,failOnError:!1},f);return W?.knownModels?{...J,...W.knownModels}:J}function uQ($){return[...new Set(($??[]).map((f)=>f.trim()).filter(Boolean))]}function vy($){if(!$?.length)return;return[...new Set($)]}function uy($,f){return vy([...$??[],...f??[]])}function cy($){let f=$?.popularRank;return typeof f==="number"&&Number.isFinite(f)?f:Number.MAX_SAFE_INTEGER}function dy($){if(!$||typeof $!=="object")return!1;let f=$;return typeof f.path==="string"&&f.path.trim().length>0&&typeof f.label==="string"&&f.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(f.type))}function ly($){let f=$?.configFields;if(!Array.isArray(f))return;return f.filter(dy)}var d5={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},rV={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function py($){if(!$)return[d5];if($.source!=="system")return $.baseUrl?[d5,rV]:[d5];let f=[];if($.env?.length)f.push(d5);if($.baseUrl)f.push(rV);return f}function ry($,f){return f.split(".").reduce((J,W)=>{if(!J||typeof J!=="object")return;return J[W]},$)}function iy($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function ny($,f,J){if(!$?.length)return;let W={};for(let Z of $){let j=iy(Z.path==="baseUrl"&&f?.baseUrl===void 0?J?.baseUrl:ry(f,Z.path))??Z.defaultValue;if(j!==void 0)W[Z.path]=j}return W}function aV($){let f=Object.entries($??{}).filter(([J])=>J.trim().length>0);return f.length>0?Object.fromEntries(f):void 0}function cQ($,f){let J=f?.includes("vision")??!1,W=f?.includes("reasoning")??!1;return Object.fromEntries($.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:W}]))}async function tV($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let f=$.modelsSourceUrl?await y6($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...f])]}function sV($,f){let J=$.read(),W=!1;if(J.providers[f])delete J.providers[f],W=!0;if(J.lastUsedProvider===f)delete J.lastUsedProvider,W=!0;if(W)$.write(J);T0.unregisterProvider(f)}async function dQ($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=f.baseUrl.trim(),Z=f.apiKey?.trim()??"";if(!W&&!Z){let G=Rf($);if((await g2(G)).providers[J]){let P=await r5($,{providerId:J});return{providerId:J,settingsPath:P.settingsPath,modelsPath:P.modelsPath,modelsCount:0}}return sV($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(T0.hasProvider(J))throw Error(`provider "${J}" already exists`);let Q=f.name.trim();if(!Q)throw Error("name is required");if(!W)throw Error("baseUrl is required");let j=uQ(f.models),H=f.modelsSourceUrl?.trim(),X=await tV({providerId:J,explicitModels:j,modelsSourceUrl:H,shouldRecompute:!0});if(X.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let Y=f.defaultModelId?.trim()&&X.includes(f.defaultModelId.trim())?f.defaultModelId.trim():X[0],A=f.capabilities?.length?[...new Set(f.capabilities)]:void 0,V=aV(f.headers);$.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:W,headers:V,timeout:f.timeoutMs,model:Y,protocol:f.protocol,client:f.client},{setLastUsed:!1});let B=Rf($),K=await g2(B);return K.providers[J]={provider:{name:Q,baseUrl:W,defaultModelId:Y,protocol:f.protocol,client:f.client,capabilities:A,modelsSourceUrl:H},models:cQ(X,A)},await v5(B,K),sJ(J,K.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:B,modelsCount:X.length}}async function p5($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=Rf($),Z=await g2(W),Q=Z.providers[J];if(!Q){let z=$.getProviderSettings(J);if(!z)throw Error(`provider "${J}" does not exist`);let D=f.modelsSourceUrl?.trim(),O=uQ(f.models)[0]??z.model?.trim();if(!O&&!D)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:f.name?.trim()||iV(J),baseUrl:f.baseUrl?.trim()??z.baseUrl?.trim()??"",defaultModelId:O,protocol:z.protocol,client:z.client,capabilities:z.capabilities},models:O?cQ([O],z.capabilities):{}}}if(!Q.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=f.name?.trim()??Q.provider.name.trim();if(!j)throw Error("name is required");let H=f.baseUrl?.trim()??Q.provider.baseUrl.trim();if(!H)throw Error("baseUrl is required");let X=f.capabilities===void 0?Q.provider.capabilities:f.capabilities===null?void 0:[...new Set(f.capabilities)],Y=f.protocol===void 0?Q.provider.protocol:f.protocol??void 0,A=f.client===void 0?Q.provider.client:f.client??void 0,V=uQ(f.models),B=f.modelsSourceUrl===void 0?Q.provider.modelsSourceUrl:f.modelsSourceUrl?.trim()||void 0,K=f.models!==void 0||f.modelsSourceUrl!==void 0&&!!B,G=Object.keys(Q.models??{}).map((z)=>z.trim()).filter(Boolean),R=await tV({providerId:J,explicitModels:V,modelsSourceUrl:B,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let P=f.defaultModelId===void 0?Q.provider.defaultModelId?.trim():f.defaultModelId?.trim(),F=P&&R.includes(P)?P:R[0],_={...$.getProviderSettings(J)??{},provider:J,baseUrl:H,model:F};if(Y)_.protocol=Y;else delete _.protocol;if(A)_.client=A;else delete _.client;if(f.apiKey!==void 0){let z=f.apiKey?.trim()??"";if(z)_.apiKey=z;else delete _.apiKey}if(f.headers!==void 0){let z=aV(f.headers);if(z)_.headers=z;else delete _.headers}if(f.timeoutMs!==void 0)if(typeof f.timeoutMs==="number")_.timeout=f.timeoutMs;else delete _.timeout;return $.saveProviderSettings(_,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:H,defaultModelId:F,protocol:Y,client:A,capabilities:X,modelsSourceUrl:B},models:cQ(R,X)},await v5(W,Z),sJ(J,Z.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:W,modelsCount:R.length}}async function r5($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=Rf($),Z=await g2(W);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await v5(W,Z),T0.unregisterProvider(J),sV($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:W}}async function lQ($){let f=$.read(),J=T0.getProviderIds(),W=await Promise.all(J.map(async(Q)=>{let[j,H]=await Promise.all([T0.getProvider(Q),T0.getModelsForProvider(Q)]),X=nV(H),Y=f.providers[Q]?.settings,A=j?.name??iV(Q),V=uy(j?.capabilities,Y?.capabilities),B=ly(j?.metadata)??py(j);return{provider:{id:Q,name:A,models:X.length,color:my(Q),letter:xy(A),enabled:Boolean(Y),apiKey:Y?ky(Y):void 0,oauthAccessTokenPresent:Y?Iy(Y):void 0,baseUrl:Y?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:Y?.protocol??j?.protocol,client:Y?.client??j?.client,capabilities:V,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:B,configValues:ny(B,Y,j),modelList:X},rank:cy(j?.metadata)}}));return W.sort((Q,j)=>{if(Q.rank!==j.rank)return Q.rank-j.rank;return Q.provider.name.localeCompare(j.provider.name)||Q.provider.id.localeCompare(j.provider.id)}),{providers:W.map((Q)=>Q.provider),settingsPath:$.getFilePath()}}async function pQ($,f){let J=$.trim(),W=await gy(J,f),Z=nV(W);return{providerId:J,models:Z}}function l5($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function oV($,f){if(!l5(f))return l5($)?{...$}:void 0;let J=l5($)?{...$}:{};for(let[W,Z]of Object.entries(f)){if(Z==null||Z===""){delete J[W];continue}if(l5(Z)){let Q=oV(J[W],Z);if(Q&&Object.keys(Q).length>0)J[W]=Q;else delete J[W];continue}J[W]=Z}return Object.keys(J).length>0?J:void 0}function rQ($,f){let J=f.providerId.trim();if(f.enabled===!1){let Q=$.read();if(delete Q.providers[J],Q.lastUsedProvider===J)delete Q.lastUsedProvider;return $.write(Q),{providerId:J,enabled:!1,settingsPath:$.getFilePath()}}let Z={...$.getProviderSettings(J)??{},provider:J};for(let Q of["apiKey","baseUrl","model","region"])if(Object.hasOwn(f,Q)&&typeof f[Q]==="string")if(f[Q].trim().length===0)delete Z[Q];else Z[Q]=f[Q];for(let Q of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(f,Q))Z[Q]=f[Q];for(let Q of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(f,Q)&&f[Q]!=null){let j=oV(Z[Q],f[Q]);if(j)Z[Q]=j;else delete Z[Q]}return $.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:$.getFilePath()}}async function iQ($,f){let J=f.trim(),W=$.getProviderSettings(J),Q=T0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=W?.baseUrl?.trim()||Q?.baseUrl?.trim(),H=q6(j,Q?.baseUrl,Q?.modelsSourceUrl);if(!W||!Q||!j||!H)return{providerId:J,refreshed:!1};let X=await p5($,{providerId:J,name:Q.name,baseUrl:j,apiKey:W.apiKey,headers:W.headers??null,timeoutMs:W.timeout??null,modelsSourceUrl:H,protocol:W.protocol??Q.protocol??null,client:W.client??Q.client??null,capabilities:W.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:X.modelsCount}}function nQ($){let f=$.trim().toLowerCase();if(f==="codex"||f==="openai-codex")return"openai-codex";if(f==="cline"||f==="oca")return f;throw Error(`provider "${$}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function ay($,f){if($==="cline")return f.access.startsWith("workos:")?f.access:`workos:${f.access}`;return f.access}async function aQ($,f,J,W){let Z=GJ({onPrompt:async(Q)=>Q.defaultValue??"",openUrl:J,onOpenUrlError:({error:Q})=>{throw Q instanceof Error?Q:Error(String(Q))}});if($==="cline")return F2({apiBaseUrl:f?.baseUrl?.trim()||by().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:W});if($==="oca")return A2({mode:f?.oca?.mode,callbacks:Z,telemetry:W});return U2({onAuth:Z.onAuth,onPrompt:Z.onPrompt,onProgress:Z.onProgress,onManualCodeInput:Z.onManualCodeInput,telemetry:W})}function tQ($,f,J,W){let Z={...J?.auth??{},accessToken:ay(f,W),refreshToken:W.refresh,accountId:W.accountId,expiresAt:W.expires},Q={...J??{provider:f},provider:f,auth:Z};return $.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function sQ($){let f=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return f&&f.length>0?f:void 0}var $B={};w($B,{getProviderConfigFields:()=>oQ});import*as i5 from"@cline/llms";import{isOAuthProviderId as ty}from"@cline/shared";var sy=["apiKey","baseUrl","awsRegion","awsProfile","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],oy={bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}},sapaicore:{mode:"replace",description:"SAP AI Core uses OAuth client credentials and an AI Core API URL, not a generic API key.",fields:{baseUrl:{label:"AI Core Base URL",placeholder:"https://api.ai.<region>.aws.ml.hana.ondemand.com"},sapClientId:{label:"Client ID",placeholder:"sb-...|xsuaa_std!b..."},sapClientSecret:{label:"Client Secret",placeholder:"SAP AI Core client secret"},sapTokenUrl:{label:"Token URL",placeholder:"https://<subdomain>.authentication.sap.hana.ondemand.com"},sapResourceGroup:{label:"Resource Group",placeholder:"default",optional:!0},sapDeploymentId:{label:"Deployment ID",placeholder:"SAP AI Core deployment id",optional:!0}}}};function ey($,f){let J={};for(let W of sy){let Z=$[W],Q=f[W];if(Z||Q)J[W]={...Z,...Q}}return J}function $q($){let f=oy[$.providerId];if(!f)return $;return{...$,description:f.description??$.description,fields:f.mode==="replace"?f.fields:ey($.fields,f.fields)}}var fq=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function Jq($,f){if(!f?.provider.baseUrl)return!1;if(f.provider.source!=="system")return!0;return fq.has($)}function oQ($){let f=i5.normalizeProviderId($);if(ty(f))return{providerId:f,authMethod:"oauth",fields:{}};let J=i5.MODEL_COLLECTIONS_BY_PROVIDER_ID[f];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:f,authMethod:"local",fields:{}};let W=J?.provider.baseUrl,Z={apiKey:{}};if(Jq(f,J))Z.baseUrl={defaultValue:W};return $q({providerId:f,authMethod:"api-key",fields:Z})}var ZB={};w(ZB,{resolveLegacyClineAuth:()=>f7,migrateLegacyProviderSettings:()=>oJ});import{existsSync as Wq,readFileSync as Zq}from"node:fs";import{dirname as Qq,join as eQ}from"node:path";import*as a5 from"@cline/llms";import{resolveClineDataDir as jq}from"@cline/shared/storage";var n5="openai",WB=a5.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,fB=128000;function f7($){let f=$?.trim();if(!f)return;try{let J=JSON.parse(f);if(!J)return;let W=typeof J.expiresAt==="number"&&Number.isFinite(J.expiresAt)?J.expiresAt<10000000000?J.expiresAt*1000:J.expiresAt:void 0;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:W,accountId:J.userInfo?.id}}catch{return}}function h($){let f=$?.trim();return f?f:void 0}function JB($){if(!Wq($))return;try{let f=Zq($,"utf8"),J=JSON.parse(f);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function Hq($){let f=$.dataDir??jq(),J=$.globalStatePath??eQ(f,"globalState.json"),W=$.secretsPath??eQ(f,"secrets.json"),Z=JB(J),Q=JB(W);if(!Z&&!Q)return;return{globalState:Z??{},secrets:Q??{}}}function $7($){if($===n5)return WB;return $}function Xq($,f,J,W){let Z=J==="plan"?"planMode":"actMode",Q=f===W?h(J==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,H={openrouter:`${Z}OpenRouterModelId`,cline:`${Z}ClineModelId`,openai:`${Z}OpenAiModelId`,ollama:`${Z}OllamaModelId`,lmstudio:`${Z}LmStudioModelId`,litellm:`${Z}LiteLlmModelId`,requesty:`${Z}RequestyModelId`,together:`${Z}TogetherModelId`,fireworks:`${Z}FireworksModelId`,sapaicore:`${Z}SapAiCoreModelId`,groq:`${Z}GroqModelId`,baseten:`${Z}BasetenModelId`,huggingface:`${Z}HuggingFaceModelId`,"huawei-cloud-maas":`${Z}HuaweiCloudMaasModelId`,oca:`${Z}OcaModelId`,aihubmix:`${Z}AihubmixModelId`,hicap:`${Z}HicapModelId`,nousResearch:`${Z}NousResearchModelId`,"vercel-ai-gateway":`${Z}VercelAiGatewayModelId`}[f];return(H?h(typeof $[H]==="string"?$[H]:void 0):void 0)??Q}function Yq($,f,J){let W=J==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,Z=J==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,Q=J==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,j=(f==="gemini"?Z:void 0)??W,H=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,X=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!H&&X===void 0)return;return{...H?{effort:H}:{},...X!==void 0?{budgetTokens:X}:{}}}function Aq($){let f=$["openai-codex-oauth-credentials"];if(!f)return;try{let J=JSON.parse(f),W=h(J.access_token),Z=h(J.refresh_token),Q=h(J.accountId);if(!W&&!Z&&!Q)return;return{...W?{apiKey:W}:{},auth:{...W?{accessToken:W}:{},...Z?{refreshToken:Z}:{},...Q?{accountId:Q}:{}}}}catch{return}}function Vq($){let f=a5.getGeneratedModelsForProvider($);return Object.keys(f)[0]??void 0}function Bq($,f,J,W){let Z=$7($),Q=h(W==="plan"?f.planModeApiProvider:f.actModeApiProvider),j=Xq(f,$,W,Q)??Vq(Z),H=Yq(f,Z,W),X=typeof f.requestTimeoutMs==="number"&&Number.isInteger(f.requestTimeoutMs)&&f.requestTimeoutMs>0?f.requestTimeoutMs:void 0,Y={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},A={};if($==="openai-codex")Object.assign(A,Aq(J));if($==="cline")try{let F=h(J["cline:clineAccountId"]);if(F)A.auth={...A.auth??{},...f7(F)}}catch{}if($===n5&&f.openAiHeaders)A.headers=f.openAiHeaders;if($==="bedrock"){let F=f.awsAuthentication==="profile"||f.awsUseProfile===!0;A.aws={accessKey:h(J.awsAccessKey),secretKey:h(J.awsSecretKey),sessionToken:h(J.awsSessionToken),region:h(f.awsRegion),authentication:f.awsAuthentication,profile:F?h(f.awsProfile):void 0,usePromptCache:f.awsBedrockUsePromptCache,useCrossRegionInference:f.awsUseCrossRegionInference,useGlobalInference:f.awsUseGlobalInference,endpoint:h(f.awsBedrockEndpoint),customModelBaseId:h(W==="plan"?f.planModeAwsBedrockCustomModelBaseId:f.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")A.gcp={projectId:h(f.vertexProjectId),region:h(f.vertexRegion)};if($===n5&&(f.azureApiVersion||f.azureIdentity!==void 0))A.azure={apiVersion:h(f.azureApiVersion),useIdentity:f.azureIdentity};if($==="sapaicore")A.sap={clientId:h(J.sapAiCoreClientId),clientSecret:h(J.sapAiCoreClientSecret),tokenUrl:h(f.sapAiCoreTokenUrl),resourceGroup:h(f.sapAiResourceGroup),deploymentId:h(W==="plan"?f.planModeSapAiCoreDeploymentId:f.actModeSapAiCoreDeploymentId),useOrchestrationMode:f.sapAiCoreUseOrchestrationMode};if($==="oca"){A.oca={mode:f.ocaMode};let F=h(J.ocaRefreshToken);if(F)A.auth={...A.auth??{},refreshToken:F}}if($==="qwen")A.apiLine=f.qwenApiLine;if($==="moonshot")A.apiLine=f.moonshotApiLine;if($==="zai")A.apiLine=f.zaiApiLine;if($==="minimax")A.apiLine=f.minimaxApiLine;let V={anthropic:f.anthropicBaseUrl,openai:f.openAiBaseUrl,ollama:f.ollamaBaseUrl,lmstudio:f.lmStudioBaseUrl,litellm:f.liteLlmBaseUrl,gemini:f.geminiBaseUrl,requesty:f.requestyBaseUrl,asksage:f.asksageApiUrl,dify:f.difyBaseUrl,oca:f.ocaBaseUrl,aihubmix:f.aihubmixBaseUrl,sapaicore:f.sapAiCoreBaseUrl},B=h(Y[$]),K=h(V[$]),G={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...K?{baseUrl:K}:{},...H?{reasoning:H}:{},...X?{timeout:X}:{},...A},R=AJ.safeParse(G);if(!R.success)return;return Object.keys(G).filter((F)=>F!=="provider").length>0?R.data:void 0}function Kq($,f){if($!==WB)return;if(!f.baseUrl||!f.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:f.baseUrl,defaultModelId:f.model},models:{[f.model]:{id:f.model,name:f.model,contextWindow:fB,maxInputTokens:fB,capabilities:["streaming","tools","images"]}}}}function Gq($,f){let J=new Set;for(let Z of[$.actModeApiProvider,$.planModeApiProvider]){let Q=h(Z);if(Q)J.add(Q)}if(h(f.apiKey))J.add("anthropic");if(h(f.openRouterApiKey))J.add("openrouter");if(h(f.openAiApiKey))J.add(n5);if(h(f.openAiNativeApiKey))J.add("openai-native");if(h(f["openai-codex-oauth-credentials"]))J.add("openai-codex");if(h(f.geminiApiKey))J.add("gemini");if(h(f.ollamaApiKey))J.add("ollama");if(h(f.awsAccessKey)||h(f.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||h($.awsProfile))J.add("bedrock");if(h($.vertexProjectId)||h($.vertexRegion))J.add("vertex");if(h(f.clineApiKey))J.add("cline");let W=f7(h(f["cline:clineAccountId"]));if(W?.accessToken||W?.refreshToken||W?.accountId)J.add("cline");if(h(f.ocaApiKey))J.add("oca");if(h(f.sapAiCoreClientId)||h(f.sapAiCoreClientSecret)||h($.sapAiCoreTokenUrl)||h($.sapAiCoreBaseUrl)||h($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)J.add("sapaicore");return J}function oJ($){let f=$.providerSettingsManager.read(),J=Hq($);if(!J)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let{globalState:W,secrets:Z}=J,Q=W.mode==="plan"?"plan":"act",j=Gq(W,Z),H=G1();H.providers={...f.providers},H.lastUsedProvider=f.lastUsedProvider;let X=new Date().toISOString(),Y=0,A=eQ(Qq($.providerSettingsManager.getFilePath()),"models.json"),V=vQ(A),B=0;for(let R of j){let P=$7(R);if(H.providers[P])continue;let F=Bq(R,W,Z,Q);if(!F)continue;H.providers[P]={settings:F,updatedAt:X,tokenSource:"migration"},Y+=1;let U=Kq(P,F);if(U&&!V.providers[P])V.providers[P]=U,B+=1}if(Y===0&&B===0)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let K=h(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),G=K?$7(K):void 0;if(H.lastUsedProvider=f.lastUsedProvider??(G&&H.providers[G]?G:Object.keys(H.providers)[0]),$.providerSettingsManager.write(H),B>0)mV(A,V);return{migrated:Y>0||B>0,providerCount:Object.keys(H.providers).length,lastUsedProvider:H.lastUsedProvider}}L0();m4();var HB={};w(HB,{trimMessagesToCheckpoint:()=>jB,trimMessagesBeforeCheckpoint:()=>W7,readSessionCheckpointHistory:()=>eJ,createRestoredCheckpointMetadata:()=>J7,createCheckpointRestorePlan:()=>Z7,applyCheckpointToWorktree:()=>Q7});import{execFile as Pq}from"node:child_process";import{promisify as Fq}from"node:util";var v2=Fq(Pq);function eJ($){let f=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(f?.history)?f.history:[]).filter((W)=>!!W&&typeof W==="object"&&!Array.isArray(W)).flatMap((W)=>{let Z=String(W.ref??"").trim(),Q=Number(W.createdAt??0),j=Number(W.runCount??0);if(Z.length===0||!Number.isFinite(Q)||!Number.isInteger(j)||j<1)return[];let H=W.kind==="stash"||W.kind==="commit"?W.kind:void 0;return[{ref:Z,createdAt:Q,runCount:j,...H?{kind:H}:{}}]})}function J7($,f){let J=eJ($).filter((Z)=>Z.runCount<=f),W=J.at(-1);return W?{latest:W,history:J}:void 0}function Uq($,f){return $.reduce((J,W)=>{if(W.runCount>f)return J;if(!J||W.runCount>J.runCount)return W;return J},void 0)}function QB($,f){let J=0;for(let W=0;W<$.length;W+=1){let Z=$[W];if(Z?.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===f)return W}throw Error(`Could not find user message for checkpoint run ${f}`)}function jB($,f){let J=QB($,f);return $.slice(0,J+1)}function W7($,f){let J=QB($,f);return $.slice(0,J)}function Z7($){let f=$.checkpointRunCount;if(!Number.isInteger(f)||f<1)throw Error("checkpointRunCount must be a positive integer");let J=Uq(eJ($.session),f);if(!J)throw Error(`No checkpoint found at or before run ${f} in session ${$.session.sessionId}`);let W=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!W)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:W,...$.restoreMessages!==!1?{messages:jB($.messages??[],f)}:{}}}async function Q7($,f){if((await v2("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await v2("git",["-C",$,"cat-file","-e",`${f.ref}^{commit}`],{windowsHide:!0}),await v2("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await v2("git",["-C",$,"clean","-fd"],{windowsHide:!0}),f.kind==="commit"){await v2("git",["-C",$,"reset","--hard",f.ref],{windowsHide:!0});return}await v2("git",["-C",$,"stash","apply",f.ref],{windowsHide:!0})}var XB={};w(XB,{SessionVersioningService:()=>_1,SessionVersioningError:()=>w0});class w0 extends Error{code;constructor($,f){super(f);this.code=$;this.name="SessionVersioningError"}}function Rq($){let f=$.sessionId.trim();if(!f)throw new w0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new w0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new w0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new w0("invalid_restore","checkpointRunCount must be a positive integer");return f}class _1{async restoreCheckpoint($){let f=$.restore?.messages!==!1,J=$.restore?.workspace!==!1,W=Rq({sessionId:$.sessionId,restoreMessages:f,restoreWorkspace:J,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),Z=await $.getSession(W);if(!Z)throw new w0("session_not_found",`Session ${W} not found`);let Q=f?await $.readMessages(W):void 0;if(f&&Q?.length===0)throw new w0("session_messages_not_found",`No messages found for session ${W}`);let j=Z7({session:Z,messages:Q,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:f});if(J)await($.applyWorkspaceCheckpoint??Q7)(j.cwd,j.checkpoint);let H=B$({session:Z,messages:Q});if(!f)return{checkpoint:j.checkpoint,sourceSnapshot:H};let X=J7(Z,$.checkpointRunCount),Y=$.restore?.omitCheckpointMessageFromSession?W7(Q??[],$.checkpointRunCount):j.messages??[],A={sourceSession:Z,sourceMessages:Q,sourceSnapshot:H,plan:j,restoredCheckpointMetadata:X,initialMessages:Y,restoreMessages:f,restoreWorkspace:J,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new w0("invalid_restore","start is required when restore.messages is true");let V=$.buildStartInput?await $.buildStartInput(A,$.start):$.start,B=await $.startSession(V),K=$.getStartedSessionId?.(B);if(K)await($.retainCheckpointRefs??RX)(j.cwd,K,X?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:B,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:H,...G?{restoredSnapshot:B$({session:G,messages:Y})}:{}}}}var YB={};w(YB,{FileTeamPersistenceStore:()=>t5});import{appendFileSync as Dq,existsSync as j7,mkdirSync as Lq,readFileSync as Oq,renameSync as _q,unlinkSync as zq,writeFileSync as Tq}from"node:fs";import{join as H7}from"node:path";import{resolveTeamDataDir as Nq}from"@cline/shared/storage";function Mq($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class t5{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let f=Mq($.teamName),J=$.baseDir?.trim()||Nq();this.dirPath=H7(J,f),this.statePath=H7(this.dirPath,"state.json"),this.taskHistoryPath=H7(this.dirPath,"task-history.jsonl")}loadState(){if(!j7(this.statePath))return;try{let $=Oq(this.statePath,"utf8"),f=JSON.parse($);if(f.version!==1||!f.teamState)return;for(let J of f.teammates??[])this.teammateSpecs.set(J.agentId,J);return jV(f.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let f={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;Tq(J,`${JSON.stringify(f,null,2)}
|
|
698
|
+
`,"utf8"),_q(J,this.statePath)}appendTaskHistory($){let f={};switch($.type){case"team_task_updated":f=$.task;break;case"team_message":f={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":f={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":f={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":f={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":f={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),Dq(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:f})}
|
|
699
|
+
`,"utf8")}ensureDir(){if(!j7(this.dirPath))Lq(this.dirPath,{recursive:!0})}hasPersistableState($){let f=$.exportState();if(this.teammateSpecs.size>0)return!0;if(f.members.some((J)=>J.role==="teammate"))return!0;return f.tasks.length>0||f.mailbox.length>0||f.missionLog.length>0}clearPersistedState(){if(j7(this.statePath))zq(this.statePath)}}var AB={};w(AB,{ChatViewStateSchema:()=>X7,ChatSummarySchema:()=>fW,ChatSessionStatusSchema:()=>o5,ChatSessionConfigSchema:()=>s5,ChatMessageSchema:()=>$W,ChatMessageRoleSchema:()=>e5});import{z as C}from"zod";var s5=C.object({workspaceRoot:C.string().min(1),cwd:C.string().optional(),provider:C.string().min(1),model:C.string().min(1),mode:C.enum(["act","plan"]).default("act"),apiKey:C.string(),systemPrompt:C.string().optional(),rules:C.string().optional(),maxIterations:C.number().int().positive().optional(),enableTools:C.boolean(),enableSpawn:C.boolean().optional(),enableTeams:C.boolean().optional(),autoApproveTools:C.boolean().optional(),missionStepInterval:C.number().int().positive().optional(),missionTimeIntervalMs:C.number().int().positive().optional()}),o5=C.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),e5=C.enum(["user","assistant","tool","system","status","error"]),$W=C.object({id:C.string().min(1),sessionId:C.string().nullable(),role:e5,content:C.string(),createdAt:C.number().int().nonnegative(),meta:C.object({stream:C.enum(["stdout","stderr"]).optional(),toolName:C.string().optional(),iteration:C.number().int().nonnegative().optional(),agentId:C.string().optional(),conversationId:C.string().optional(),hookEventName:C.string().optional(),inputTokens:C.number().int().nonnegative().optional(),outputTokens:C.number().int().nonnegative().optional(),checkpoint:C.object({ref:C.string(),createdAt:C.number().int().nonnegative(),runCount:C.number().int().positive(),kind:C.enum(["stash","commit"]).optional()}).optional()}).optional()}),fW=C.object({toolCalls:C.number().int().nonnegative(),tokensIn:C.number().int().nonnegative(),tokensOut:C.number().int().nonnegative()}),X7=C.object({sessionId:C.string().nullable(),status:o5,config:s5,messages:C.array($W),rawTranscript:C.string(),error:C.string().nullable(),summary:fW});var VB={};w(VB,{CORE_BUILD_VERSION:()=>Y7});var Y7=T3;import{Agent as Xw,createAgentRuntime as Yw}from"@cline/agents";var KB={};w(KB,{fetchClineRecommendedModels:()=>A7,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>JW});import{getClineEnvironmentConfig as yq}from"@cline/shared";var qq=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 wq($){return{recommended:$.recommended.map((f)=>({...f,tags:[...f.tags]})),free:$.free.map((f)=>({...f,tags:[...f.tags]}))}}function BB($){if(!$||typeof $!=="object")return null;let f=$;if(typeof f.id!=="string"||f.id.length===0)return null;return{id:f.id,name:typeof f.name==="string"&&f.name.length>0?f.name:f.id,description:typeof f.description==="string"?f.description:"",tags:Array.isArray(f.tags)?f.tags.filter((J)=>typeof J==="string"):[]}}function Sq($){if(!$||typeof $!=="object")return null;let f=$,J=Array.isArray(f.recommended)?f.recommended:[],W=Array.isArray(f.free)?f.free:[],Z=J.map(BB).filter((j)=>j!==null),Q=W.map(BB).filter((j)=>j!==null);if(Z.length===0&&Q.length===0)return null;return{recommended:Z,free:Q}}function hq($){let f=$.baseUrl?.trim();if(f)return f;let J=yq().apiBaseUrl;try{return($.providerSettingsManager??new R$).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function Cq($,f,J){let W=new AbortController,Z=setTimeout(()=>W.abort(),J);try{return await $(f,{signal:W.signal})}finally{clearTimeout(Z)}}async function A7($={}){try{let f=hq($),J=$.fetchImpl??fetch,W=await Cq(J,`${f}/api/v1/ai/cline/recommended-models`,$.timeoutMs??qq);if(!W.ok)throw Error(`HTTP ${W.status}`);let Z=await W.json(),Q=Sq(Z);if(Q)return Q}catch{}return wq(JW)}var GB={};w(GB,{loadLlmsConfigFromFile:()=>B7,defineLlmsConfig:()=>V7});import{readFile as Eq}from"node:fs/promises";import bq from"node:path";function V7($){return $}async function B7($){let f=bq.resolve($),J=await Eq(f,"utf8"),W;try{W=JSON.parse(J)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${f}": ${Q}`)}return kq(W,f)}function kq($,f){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${f}": expected an object.`);let W=$.providers;if(!Array.isArray(W))throw Error(`Invalid llms config in "${f}": "providers" must be an array.`);if(!W.length)throw Error(`Invalid llms config in "${f}": "providers" cannot be empty.`);return $}var LB={};w(LB,{createLlmsSdk:()=>G7,DefaultLlmsSdk:()=>$4});import{BUILT_IN_PROVIDER_IDS as UB,createHandler as mq,createHandlerAsync as gq,getProviderCollection as vq,hasProvider as RB,registerAsyncHandler as uq,registerHandler as cq,registerModel as dq,registerProvider as DB}from"@cline/llms";function PB($){return $?{...$}:{}}function Iq($,f){if($)return $;if(!f)return;let J=globalThis.process;if(!J?.env)return;return J.env[f]}function xq($,f){if(!f.length)throw Error(`Provider "${$}" must include at least one model.`)}function FB($){let f=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:f,defaultModel:$.collection.provider.defaultModelId,modelCount:f.length}}class K7{providers=new Map;register($){xq($.id,$.models);let f=$.defaultModel??$.models[0];if(!f)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(f))throw Error(`Default model "${f}" is not included in configured models for "${$.id}".`);let J=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...J?.models??[],...$.models]),defaultModel:f,defaults:{...J?.defaults??{},...PB($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:Iq($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...PB($.settings)}})}registerModel($,f){let J=this.providers.get($);if(!J){this.providers.set($,{id:$,models:new Set([f]),defaultModel:f,defaults:{}});return}J.models.add(f)}createHandlerConfig($){let f=this.require($.providerId),J=$.modelId??f.defaultModel;if(!f.models.has(J))throw Error(`Model "${J}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:J,...f.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,f){return this.providers.get($)?.models.has(f)??!1}require($){let f=this.providers.get($);if(!f)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return f}}class $4{configuredProviders=new K7;constructor($){this.applyConfig($)}createHandler($){return mq(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return gq(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(DB($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)cq($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)uq($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let f=$.exposeModels??Object.keys($.models),J=$.defaultModel??f[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);DB({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:J,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:f,defaultModel:J,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){dq($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...UB]}async getBuiltInProviders(){return(await Promise.all(UB.map((f)=>vq(f)))).filter((f)=>f!==void 0).map((f)=>FB({collection:f}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,f){return this.configuredProviders.hasModel($,f)}applyConfig($){for(let f of $.providers)this.configuredProviders.registerSelectionConfig(f);for(let f of $.models??[])this.registerModel(f);for(let f of $.customProviders??[])this.registerProvider(f);for(let f of this.configuredProviders.list()){let J=RB(f.id),W=this.configuredProviders.createHandlerConfig({providerId:f.id,modelId:f.defaultModel}).routingProviderId,Z=typeof W==="string"&&RB(W);if(!J&&!Z)throw Error(`Provider "${f.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function G7($){return new $4($)}MW();async function lq(){return Promise.resolve().then(() => (LQ(),RV))}function Gw(){return new Date().toISOString()}function Pw($){if(qB($)!=="providers.json")return;let f=F7($);if(qB(f)!=="settings")return;return F7(f)}class R${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??Kw(),this.dataDir=$.dataDir??Pw(this.filePath),this.dataDir||!$.filePath)oJ({providerSettingsManager:this,dataDir:this.dataDir});if(pV(this),u5(this.read()),P7(this.filePath))try{yB(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!P7(this.filePath))return G1();try{let $=Vw(this.filePath,"utf8"),f=JSON.parse($),J=K2.safeParse(f);if(J.success)return u5(J.data),J.data}catch{}return G1()}write($){let f=K2.parse($),J=F7(this.filePath);if(!P7(J))Aw(J,{recursive:!0,mode:448});Bw(this.filePath,`${JSON.stringify(f,null,2)}
|
|
700
|
+
`,"utf8");try{yB(this.filePath,384)}catch{}u5(f)}saveProviderSettings($,f={}){let J=AJ.parse($),W=this.read(),Z=J.provider,Q=f.setLastUsed!==!1,j=W.providers[Z],H=f.tokenSource??j?.tokenSource??"manual",X={...W,providers:{...W.providers,[Z]:{settings:J,updatedAt:Gw(),tokenSource:H}},lastUsedProvider:Q?Z:W.lastUsedProvider};return this.write(X),X}getProviderSettings($){return this.read().providers[$]?.settings}getLastUsedProviderSettings(){let $=this.read(),f=$.lastUsedProvider;if(!f)return;return $.providers[f]?.settings}getProviderConfig($,f){let J=this.getProviderSettings($);if(!J)return;return v0(J,f)}getLastUsedProviderConfig($){let f=this.getLastUsedProviderSettings();if(!f)return;return v0(f,$)}async refreshCatalog(){try{await V2({})}catch{}}}L0();x4();import{getClineEnvironmentConfig as Fw,isOAuthProviderId as Uw}from"@cline/shared";var U7="workos:";function Rw($,f){if($==="cline")return`${U7}${f}`;return f}function Dw($,f){if($==="cline"&&f.toLowerCase().startsWith(U7))return f.slice(U7.length);return f}function Lw($){let J=_0($)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function Ow($,f){let J=$.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let W=Lw(f);if(W)return W;return Date.now()-1}function _w($,f){let J=f.auth?.accessToken?.trim(),W=f.auth?.refreshToken?.trim();if(!J||!W)return null;let Z=Dw($,J);if(!Z)return null;return{access:Z,refresh:W,expires:Ow(f,Z),accountId:f.auth?.accountId}}function zw($,f){let J=$?.expiresAt,W=f?.expiresAt;return $?.accessToken===f?.accessToken&&$?.refreshToken===f?.refreshToken&&$?.accountId===f?.accountId&&J===W}class ZW extends Error{providerId;constructor($){super(`OAuth credentials for provider "${$}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=$}}class R7{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new R$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){if(!Uw($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,f=!1){let J=this.refreshInFlight.get($);if(J)return J;let W=this.resolveProviderApiKeyInternal($,f).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,W),W}async resolveProviderApiKeyInternal($,f){let J=this.providerSettingsManager.getProviderSettings($);if(!J)return null;let W=_w($,J);if(!W)return null;let Z=await this.resolveCredentials($,J,W,f);if(!Z)throw new ZW($);let Q=Rw($,Z.access),j={...J.auth??{},accessToken:Q,refreshToken:Z.refresh,accountId:Z.accountId};j.expiresAt=Z.expires;let H={...J,auth:j},X=!zw(J.auth,H.auth);if(X)this.providerSettingsManager.saveProviderSettings(H,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:Q,accountId:Z.accountId,refreshed:X}}async resolveCredentials($,f,J,W){if($==="cline")return FJ(J,{apiBaseUrl:f.baseUrl?.trim()||Fw().apiBaseUrl,telemetry:this.telemetry},{forceRefresh:W});if($==="oca")return ZJ(J,{forceRefresh:W,telemetry:this.telemetry},{mode:f.oca?.mode,telemetry:this.telemetry});return RJ(J,{forceRefresh:W,telemetry:this.telemetry})}}import{normalizeUserInput as Tw}from"@cline/shared";import{nanoid as Nw}from"nanoid";class wB{list($){return $?p0($):[]}update($,f){if(!$)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=f.promptId.trim(),W=$.pendingPrompts.findIndex((X)=>X.id===J);if(W<0)return{sessionId:f.sessionId,prompts:p0($),updated:!1};let Z=$.pendingPrompts[W];if(!Z)return{sessionId:f.sessionId,prompts:p0($),updated:!1};let Q=f.prompt===void 0?Z.prompt:Tw(f.prompt).trim();if(!Q)throw Error("prompt cannot be empty");let j=f.delivery??Z.delivery,H={...Z,prompt:Q,mode:f.mode??Z.mode,delivery:j};return $.pendingPrompts.splice(W,1),Mw($,H,W,Z.delivery),{sessionId:f.sessionId,prompts:p0($),prompt:QW(H),updated:!0}}delete($,f){if(!$)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=f.promptId.trim(),W=$.pendingPrompts.findIndex((Q)=>Q.id===J);if(W<0)return{sessionId:f.sessionId,prompts:p0($),removed:!1};let[Z]=$.pendingPrompts.splice(W,1);return{sessionId:f.sessionId,prompts:p0($),prompt:Z?QW(Z):void 0,removed:!0}}enqueue($,f){let{prompt:J,mode:W,delivery:Z,userImages:Q,userFiles:j}=f,H=$.pendingPrompts.findIndex((X)=>X.prompt===J);if(H>=0){let[X]=$.pendingPrompts.splice(H,1),Y={...X,prompt:J,mode:W??X.mode,userImages:Q??X.userImages,userFiles:j??X.userFiles};if(Z==="steer"||X.delivery==="steer")$.pendingPrompts.unshift({...Y,delivery:"steer"});else $.pendingPrompts.push(Y)}else{let X={id:`pending_${Date.now()}_${Nw(5)}`,prompt:J,mode:W,delivery:Z,userImages:Q,userFiles:j};if(Z==="steer")$.pendingPrompts.unshift(X);else $.pendingPrompts.push(X)}return p0($)}consumeSteer($){let f=$.pendingPrompts.findIndex((W)=>W.delivery==="steer");if(f<0)return{prompts:p0($)};let[J]=$.pendingPrompts.splice(f,1);return{entry:J,prompts:p0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:p0($)}}requeueFront($,f){return $.pendingPrompts.unshift(f),p0($)}clear($){return $.pendingPrompts.length=0,[]}}class D7{deps;service=new wB;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=this.service.update(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}delete($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=this.service.delete(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}enqueue($,f){let J=this.deps.getSession($);if(!J||J.aborting)return;this.service.enqueue(J,f),this.emitPrompts(J),this.scheduleDrain($,J)}consumeSteer($){let f=this.deps.getSession($);if(!f)return;let{entry:J}=this.service.consumeSteer(f);if(!J)return;return this.emitPrompts(f),this.emitSubmitted(f,J),J}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:p0($)}})}scheduleDrain($,f){if(f.pendingPrompts.length===0||f.aborting||f.drainingPendingPrompts||!f.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let f=this.deps.getSession($);if(!f)return;if(f.aborting||f.drainingPendingPrompts)return;if(!f.agent.canStartRun())return;let{entry:J}=this.service.shiftNext(f);if(!J)return;this.emitPrompts(f),this.emitSubmitted(f,J),f.drainingPendingPrompts=!0;let W=!0;try{await this.deps.send({sessionId:$,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{W=!1,this.service.requeueFront(f,J),this.emitPrompts(f)}finally{if(f.drainingPendingPrompts=!1,W&&f.pendingPrompts.length>0&&f.status!=="failed"&&f.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,f){let J=QW(f);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function QW($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function p0($){return $.pendingPrompts.map(QW)}function Mw($,f,J,W){if(f.delivery==="steer")$.pendingPrompts.unshift(f);else if(W==="steer")$.pendingPrompts.push(f);else $.pendingPrompts.splice(J,0,f)}L0();class O7{deps;constructor($){this.deps=$}dispatchAgentEvent($,f,J){let W=this.deps.getSession($),Z={sessionId:$,config:f,liveSession:W,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},Q=IZ(J),j=!!W&&(!Q.agentId||Q.agentId===L7(W.agent));xZ(Z,J,j?{isPrimaryAgentEvent:!0,agentId:L7(W.agent),conversationId:W.agent.getConversationId(),...W?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,f){let J=this.deps.getSession($);if(J){if(jQ(J,f),f.type==="agent_event"){let W={sessionId:$,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};xZ(W,f.event,{agentId:f.agentId,teamRole:"teammate",teamAgentId:f.agentId,isPrimaryAgentEvent:!1})}if(f.type==="teammate_spawned"){let W=k$({agentId:f.teammate.runtimeAgentId??f.agentId,conversationId:f.teammate.conversationId,parentAgentId:f.teammate.parentAgentId,createdByAgentId:L7(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:f.agentId});if(W)n$(J.config.telemetry,{ulid:$,modelId:f.teammate.modelId??J.config.modelId,provider:J.config.providerId,...W})}}if(await HQ($,f,this.deps.invokeBackendOptional),J)XQ(J,$,f,this.deps.emit)}async handlePluginEvent($,f,J){if(f.name==="plugin_log"){this.handlePluginLog($,f.payload);return}if(f.name==="automation_event"){let X=this.deps.getSession($)?.config.extensionContext?.automation??J;if(!X)return;let Y=f.payload&&typeof f.payload==="object"?f.payload:void 0;if(!Y)return;await X.ingestEvent(Y);return}if(f.name!=="steer_message"&&f.name!=="queue_message"&&f.name!=="pending_prompt")return;let W=f.payload&&typeof f.payload==="object"?f.payload:void 0,Z=typeof W?.sessionId==="string"&&W.sessionId.trim().length>0?W.sessionId.trim():$,Q=typeof W?.prompt==="string"?W.prompt.trim():"";if(!Q)return;let j=f.name==="steer_message"?"steer":f.name==="queue_message"?"queue":W?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:Q,delivery:j})}handlePluginLog($,f,J){let W=this.deps.getSession($),Z=J??W?.config.extensionContext?.logger??W?.config.logger;if(!Z||!f||typeof f!=="object")return;let Q=f,j=typeof Q.message==="string"?Q.message:"";if(!j)return;let H=Q.metadata&&typeof Q.metadata==="object"?{...Q.metadata}:{};if(H.sessionId??=$,typeof Q.pluginName==="string"&&Q.pluginName)H.pluginName=Q.pluginName;if(Q.level==="debug"){Z.debug(j,H);return}if(Q.level==="error"){if(Z.error)Z.error(j,H);else Z.log(j,{...H,severity:"error"});return}Z.log(j,H)}}function L7($){return $.getAgentId()}function _7($){return{sessionId:$.sessionId,source:$.source,pid:process.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:H1($.config),teamName:$.config.teamName?.trim()||void 0,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,parentSessionId:typeof $.sessionMetadata?.parentSessionId==="string"?$.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof $.sessionMetadata?.parentAgentId==="string"?$.sessionMetadata.parentAgentId:void 0,agentId:typeof $.sessionMetadata?.agentId==="string"?$.sessionMetadata.agentId:void 0,conversationId:typeof $.sessionMetadata?.conversationId==="string"?$.sessionMetadata.conversationId:void 0,isSubagent:typeof $.sessionMetadata?.isSubagent==="boolean"?$.sessionMetadata.isSubagent:!1,prompt:$.pendingPrompt,metadata:$.sessionMetadata,messagesPath:$.artifacts?.messagesPath,updatedAt:$.updatedAt??$.endedAt??$.startedAt}}function z7($,f){let J=$[f];return typeof J==="function"?J:null}async function SB($,f,...J){let W=z7($,f);if(!W)throw Error(`session service method not available: ${f}`);return Promise.resolve(W.apply($,J))}async function hB($,f,...J){let W=z7($,f);if(!W)return;await Promise.resolve(W.apply($,J))}async function CB($,f,...J){let W=z7($,f);if(!W)return;return await Promise.resolve(W.apply($,J))}Z$();L0();function T7($,f,J,W){return Q1({configProvider:{getRuntimeConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:f.hooks,extensions:f.extensions,logger:f.logger,telemetry:f.telemetry},getConnectionConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Q=f.enableTools?p1({cwd:f.cwd,...m0[E$({mode:f.mode})],executors:W}):[];if(f.enableSpawnAgent)Q.push(T7($,f,J,W));return S1(Q)},onSubAgentEvent:(Q)=>$.onAgentEvent(J,f,Q),onSubAgentStart:(Q)=>{let j=$.getSession(J)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let H=k$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:Q.parentAgentId});if(H)n$(f.telemetry,{ulid:J,modelId:f.modelId,provider:f.providerId,...H});$8(f.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...H}),$.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let j=$.getSession(J)?.runtime.teamRuntime,H=$.subAgentStarts.get(Q.subAgentId),X=H?Date.now()-H.startedAt:0,Y=Q.result?.text?Q.result.text.split(`
|
|
701
|
+
`).length:0;$8(f.telemetry,{event:"ended",ulid:J,durationMs:X,outputLines:Y,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...k$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",J,Q)}})}import{readFile as yw,stat as qw}from"node:fs/promises";var ww=20480000;async function EB($){let f=await qw($);if(!f.isFile())throw Error("Path is not a file");if(f.size>ww)throw Error("File is too large to read into context.");let J=await yw($,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var bB=5000;function Q4($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function xw($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=Q4(f.inputTokens),W=Q4(f.outputTokens),Z=Q4(f.cacheReadTokens),Q=Q4(f.cacheWriteTokens),j=Q4(f.totalCost);if(J===void 0||W===void 0||Z===void 0||Q===void 0||j===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:Z,cacheWriteTokens:Q,totalCost:j}}function mw($,f){return{inputTokens:Math.max($.inputTokens,f.inputTokens),outputTokens:Math.max($.outputTokens,f.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,f.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,f.cacheWriteTokens),totalCost:Math.max($.totalCost,f.totalCost)}}class U${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new vJ;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new _1;constructor($){let f=hw();if(f)Iw(f);let J=h1($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new I2,this.createAgentInstance=$.createAgent??((W)=>new Z1(W)),this.defaultCapabilities=R0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new R$,this.oauthTokenManager=$.oauthTokenManager??new R7({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=$.fetch,this.pendingPromptsController=new D7({getSession:(W)=>this.sessions.get(W),emit:(W)=>this.emit(W),send:(W)=>this.runTurn(W)}),this.pendingPrompts={list:async(W)=>this.pendingPromptsController.list(W.sessionId),update:async(W)=>this.pendingPromptsController.update(W),delete:async(W)=>this.pendingPromptsController.delete(W)},this.eventBridge=new O7({getSession:(W)=>this.sessions.get(W),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(W)=>this.emit(W),persistMessages:(W,Z,Q)=>{this.invoke("persistSessionMessages",W,Z,Q)},enqueuePendingPrompt:(W,Z)=>this.pendingPromptsController.enqueue(W,Z),invokeBackendOptional:(W,...Z)=>this.invokeOptional(W,...Z)})}async startSession($){let f=$.source??P0.CLI,J=s(),W=$.config.sessionId?.trim()??"",Z=W||Ew(),Q=$,j=Q.initialMessages??[],H=j.length>0?sf(j):B0(),X=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!X)throw Error("session service method not available: ensureSessionsDir");let Y=N7(X,Z),A=N7(Y,`${Z}.messages.json`),V=N7(Y,`${Z}.json`),B=H1($.config),K=M0.parse({version:1,session_id:Z,source:f,pid:process.pid,started_at:J,status:"running",interactive:$.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Q.config.cwd,workspace_root:B,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,messages_path:A}),G;if(W.length>0&&j.length>0&&!Q.prompt?.trim()){let k=await this.invokeOptionalValue("readSessionManifest",Z);if(k)K=k,G={manifestPath:V,messagesPath:k.messages_path||A,manifest:k}}let P=await this.seedAggregateUsageFromArtifacts({initialUsage:H,sessionDir:Y,rootMessagesPath:G?.messagesPath??A,manifest:K});this.usageBySession.set(Z,H),this.aggregateUsageBySession.set(Z,P);let F=R0(this.defaultCapabilities,$.capabilities),U=F?.toolExecutors??this.toolExecutors,_=$.localRuntime,z=_?.extensionContext?.logger??_?.logger,D=_?.extensionContext?.automation,O;O=await QY({input:Q,localRuntime:$.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:F,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(k)=>{if(k.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,k.payload,z);return}this.eventBridge.handlePluginEvent(Z,k,D)},onTeamEvent:(k)=>{this.eventBridge.handleTeamEvent(Z,k),O.config.onTeamEvent?.(k)},createSpawnTool:()=>T7({getSession:(k)=>this.sessions.get(k),subAgentStarts:this.subAgentStarts,onAgentEvent:(k,D0,n)=>this.eventBridge.dispatchAgentEvent(k,D0,n),invokeBackendOptional:(k,...D0)=>this.invokeOptional(k,...D0)},O.config,Z,U),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(k)=>{await this.persistSessionMetadata(Z,()=>k)}});let N=await this.runtimeBuilder.build(O.runtimeBuilderInput),q=O.config,$0=O.providerConfig;if(N.teamRuntime&&!q.teamName?.trim())q.teamName=N.teamRuntime.getTeamName();let Y0=[...N.tools,...q.extraTools??[]],o=N.extensions??O.extensions,A0={sessionId:Z,providerId:$0.providerId,modelId:$0.modelId,apiKey:$0.apiKey,baseUrl:$0.baseUrl,headers:$0.headers,knownModels:$0.knownModels,providerConfig:$0,thinking:q.thinking,reasoningEffort:q.reasoningEffort??$0.reasoningEffort,systemPrompt:q.systemPrompt,maxIterations:q.maxIterations,execution:q.execution,prepareTurn:L8(q),tools:Y0,hooks:O.hooks,extensions:o,hookErrorMode:q.hookErrorMode,initialMessages:O.effectiveInput.initialMessages,userFileContentLoader:EB,toolPolicies:O.toolPolicies,requestToolApproval:O.requestToolApproval?async(k)=>{let D0=O.requestToolApproval,n=this.sessions.get(Z);if(n)await this.markTurnPending(n);try{if(!D0)return{approved:!1,reason:"Tool approval callback is not configured."};return await D0(k)}finally{let a0=this.sessions.get(Z);if(a0?.status==="pending")await this.markTurnRunning(a0)}}:void 0,telemetry:q.telemetry,onConsecutiveMistakeLimitReached:q.onConsecutiveMistakeLimitReached,completionPolicy:N.completionPolicy,consumePendingUserMessage:()=>{let k=this.pendingPromptsController.consumeSteer(Z);return k?rJ(k.prompt,k.mode??q.mode):void 0},logger:N.logger??q.logger,extensionContext:q.extensionContext,onEvent:(k)=>this.eventBridge.dispatchAgentEvent(Z,q,k)};A0.hooks={...A0.hooks,onEvent:async(k)=>{if(await O.hooks?.onEvent?.(k),k.type!=="assistant-message")return;let D0=this.sessions.get(Z);if(!D0)return;let n=D0.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,n,q.systemPrompt)}catch(a0){q.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:a0}),Df(q.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:a0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:q.providerId,modelId:q.modelId}})}}};let i=this.createAgentInstance(A0);if(A0.onEvent)i.subscribeEvents(A0.onEvent);N.registerLeadAgent?.(i);let J$=k$({agentId:i.getAgentId(),conversationId:i.getConversationId(),teamId:N.teamRuntime?.getTeamId(),teamName:N.teamRuntime?.getTeamName(),teamRole:N.teamRuntime?"lead":void 0});if(HY(q,Z,W.length>0,B,J$),J$)n$(q.telemetry,{ulid:Z,modelId:q.modelId,provider:q.providerId,...J$});if(N.teamRuntime)y4(q.telemetry,{ulid:Z,teamId:N.teamRuntime.getTeamId(),teamName:N.teamRuntime.getTeamName(),leadAgentId:i.getAgentId(),restoredFromPersistence:N.teamRestoredFromPersistence===!0});let p={sessionId:Z,config:q,sessionMetadata:Q.sessionMetadata,...G?{artifacts:G}:{},source:f,startedAt:G?.manifest.started_at??J,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??J,pendingPrompt:K.prompt,runtime:N,agent:i,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:O.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,p),this.emitStatus(Z,"running"),j.length>0&&!G){if(await this.ensureSessionPersisted(p),await this.invoke("persistSessionMessages",p.sessionId,j,p.config.systemPrompt),!Q.prompt?.trim())await this.updateStatus(p,"completed",0)}let n0;try{if(Q.prompt?.trim())if(n0=await this.executeTurn(p,{prompt:Q.prompt,userImages:Q.userImages,userFiles:Q.userFiles}),!p.interactive)await this.finalizeSingleRun(p,n0.finishReason);else await this.completeInteractiveTurn(p,n0.finishReason)}catch(k){if(p.interactive&&p.aborting)n0=await this.completeAbortedInteractiveTurn(p);else throw Df(p.config.telemetry,{component:"core",operation:"session.start",error:k,severity:"error",handled:!1,context:{sessionId:p.sessionId,providerId:p.config.providerId,modelId:p.config.modelId}}),await this.failSession(p),k}return{sessionId:Z,manifest:K,manifestPath:V,messagesPath:A,result:n0}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(f)=>this.getSession(f),readMessages:(f)=>this.readSessionMessages(f),buildStartInput:(f,J)=>{let W=f.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:f.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...W?{sessionMetadata:W}:{},initialMessages:f.initialMessages}},startSession:(f)=>this.startSession(f),getStartedSessionId:(f)=>f.sessionId,readRestoredSession:(f)=>this.getSession(f)})}async runTurn($){let f=this.getSessionOrThrow($.sessionId),J=f.agent.canStartRun(),W=$.delivery??(f.interactive&&!J?"queue":void 0);if(f.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:W??"immediate"}}),W==="queue"||W==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:W,userImages:$.userImages,userFiles:$.userFiles});return}try{let Z=await this.executeTurn(f,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!f.interactive)await this.finalizeSingleRun(f,Z.finishReason);else await this.completeInteractiveTurn(f,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),Z}catch(Z){if(f.interactive&&f.aborting)return await this.completeAbortedInteractiveTurn(f);throw Df(f.config.telemetry,{component:"core",operation:"session.submit",error:Z,severity:"error",handled:!1,context:{sessionId:f.sessionId,providerId:f.config.providerId,modelId:f.config.modelId}}),await this.failSession(f),Z}}async getAccumulatedUsage($){let f=s9(this.usageBySession.get($)),J=s9(this.aggregateUsageBySession.get($));return f||J?{usage:f,aggregateUsage:J}:void 0}async abort($,f){let J=this.sessions.get($);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort(f)}async stopSession($){let f=this.sessions.get($);if(!f)return;if(f.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),f.interactive&&!W0(f.status)){await this.releaseSessionRuntime(f,"session_stop");return}if(f.interactive&&f.agent.canStartRun()){await this.shutdownSession(f,{status:this.resolveInteractiveStopStatus(f),exitCode:this.resolveInteractiveStopExitCode(f),shutdownReason:"session_stop",endReason:"stopped"});return}f.aborting=!0,f.agent.abort(Error("session_stop")),await this.shutdownSession(f,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let f=[...this.sessions.values()];if(f.length===0)return;await Promise.allSettled(f.map((J)=>J.interactive&&!W0(J.status)?this.releaseSessionRuntime(J,$):J.interactive&&J.agent.canStartRun()?this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let f=this.sessions.get($);if(f)return _7(f);let J=$.trim();if(!J)return;let W=await this.getRow(J);if(W)return d8(W);let Z=await this.readManifest(J);return Z?_5(Z):void 0}async listSessions($=200){let J=(await this.listRows($)).map(d8),W=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(W.has(Z.sessionId))continue;J.unshift(_7(Z))}return J.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let f=await this.invoke("deleteSession",$);if(f.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return f.deleted}async updateSession($,f){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:f.prompt,metadata:f.metadata,title:f.title}))?.updated===!0}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.getRow(f);if(J?.messagesPath)return R1(J.messagesPath);let W=await this.readManifest(f);return R1(W?.messages_path)}async dispatchHookEvent($){await TA($,{queueSpawnRequest:(f)=>this.invokeOptional("queueSpawnRequest",f),upsertSubagentSessionFromHook:(f)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",f),appendSubagentHookAudit:(f,J)=>this.invokeOptional("appendSubagentHookAudit",f,J),applySubagentStatus:(f,J)=>this.invokeOptional("applySubagentStatus",f,J)})}subscribe($,f){return this.events.subscribe($,f)}async updateSessionModel($,f){let J=this.getSessionOrThrow($);J.config.modelId=f,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:f}),J.agent.updateConnection({modelId:f})}handlePluginEvent($,f,J){return this.eventBridge.handlePluginEvent($,f,J)}async executeTurn($,f){let J=await this.prepareTurnInput($,f),W=J.prompt.trim();if(!W)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=W;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let Z=await this.executeAgentTurn($,W,J.userImages,J.userFiles);while(YQ($,Z.finishReason)){let Q=await AQ($);if(Q.length===0)break;let j=VQ($,Q);Z=await this.executeAgentTurn($,j)}return Z}async completeInteractiveTurn($,f){if(pJ($))return;$.lastInteractiveTurnFinishReason=f,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let f=$.lastInteractiveTurnFinishReason;if(!f)return"cancelled";switch(f){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return f}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let f=new Date,J=$.agent.getMessages(),W=B0();return $.persistedMessages=J,$.started=$.started||J.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:W}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:W,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:f,endedAt:f,durationMs:0}}async executeAgentTurn($,f,J,W){let Z=$.started||$.agent.getMessages().length>0,Q=$.persistedMessages??$.agent.getMessages(),j=this.usageBySession.get($.sessionId)??B0(),H=this.aggregateUsageBySession.get($.sessionId)??j;$.turnUsageBaseline=j,$.turnAggregateUsageBaseline=H,$.turnPrimaryUsage=B0(),$.turnUsageByAgent=new Map,L4($.config.telemetry,$.sessionId,$.config.mode),wf($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let X=Z?()=>$.agent.continue(f,J,W):()=>$.agent.run(f,J,W),Y=await this.runWithAuthRetry($,X,Q);$.started=!0;let A=Y6(Y.messages,Y,Q);$.persistedMessages=A;let V=p8($.turnUsageByAgent?.values()??[]),B=H0(j,Y.usage),K=H0(H0(B0(),Y.usage),V),G=H0(H,K);return this.usageBySession.set($.sessionId,B),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:B.totalCost,aggregatedAgentsCost:G.totalCost,usage:B,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,A,$.config.systemPrompt),this.observeTaskCompletionTool($,Y),Y}catch(X){throw Df($.config.telemetry,{component:"core",operation:"session.turn",error:X,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),X}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,f){if($.submitAndExitObserved)return;if(!f.toolCalls.some((W)=>W.name===J0.SUBMIT_AND_EXIT&&W.error===void 0))return;$.submitAndExitObserved=!0,o2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,f){let J=H1($.config),W=kw(f.prompt).trim();if(!W)return{prompt:"",userImages:f.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles)};let Z=await mf(W,J);XY($.config.telemetry,Z);let Q=rJ(Z.prompt,f.mode??$.config.mode),j=this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles),H=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),X=Array.from(new Set([...j,...H]));return{prompt:Q,userImages:f.userImages,userFiles:X.length>0?X:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let f=H1($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:f,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,f){let J=this.sessions.get($),W=await this.invokeOptionalValue("readSessionManifest",$)??J?.artifacts?.manifest,Z=f(W?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun($,f){if(pJ($))return;let J=f==="aborted"||$.aborting,W=f==="error";await this.shutdownSession($,{status:J?"cancelled":W?"failed":"completed",exitCode:W?1:0,shutdownReason:W?"session_error":"session_complete",endReason:f})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,f){if(f.status==="completed"&&!$.submitAndExitObserved)o2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});q5($);let J=[],W=(Z,Q)=>{J.push(Q),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:Z,error:Q,severity:"warn"}),Df($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:Q,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,status:f.status,shutdownReason:f.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,f.status,f.exitCode)}catch(Z){W("update_status",Z)}try{await $.agent.shutdown(f.shutdownReason)}catch(Z){W("agent_shutdown",Z)}}try{await Promise.resolve($.runtime.shutdown(f.shutdownReason))}catch(Z){W("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){W("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:f.endReason,ts:Date.now()}}),J.length>0&&f.status==="failed")throw J[0]}async releaseSessionRuntime($,f){let J=[],W=(Z,Q)=>{J.push(Q),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:Z,error:Q,severity:"warn"}),Df($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:Q,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,reason:f,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(f)}catch(Z){W("agent_shutdown",Z)}try{await Promise.resolve($.runtime.shutdown(f))}catch(Z){W("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){W("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),J.length>0)throw J[0]}async updateStatus($,f,J){if(!$.artifacts)return;let W=await this.invoke("updateSessionStatus",$.sessionId,f,J);if(!W.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(Z.status=f,W0(f))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=W.endedAt??s(),Z.exit_code=typeof J==="number"?J:null;$.artifacts.manifest=Z,$.status=f,$.updatedAt=W.endedAt??s(),$.endedAt=W0(f)?null:Z.ended_at,$.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,Z),this.emitStatus($.sessionId,f)}async runWithAuthRetry($,f,J){try{return await f()}catch(W){if(!bw(W,$.config.providerId))throw W;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(J),f()}}async syncOAuthCredentials($,f){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:f?.forceRefresh})}catch(W){if(W instanceof ZW)throw Error(`${W.providerId} requires re-authentication.`);throw W}if(!J?.apiKey||$.config.apiKey===J.apiKey)return;$.config.apiKey=J.apiKey,$.agent.updateConnection({apiKey:J.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow($){let f=this.sessions.get($);if(!f){let J=new M$($);throw Df(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),J}return f}resolveAbsoluteFilePaths($,f){if(!f||f.length===0)return[];let J=f.map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>Cw(W)?W:M7($,W));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity($){return k$({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let f=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),J=H0($.initialUsage,f);return this.withPersistedAggregateUsageFloor(J,$.manifest)}async summarizePersistedTeammateUsage($,f,J){let W=M7(f),Z=`${J}.messages.json`,Q;try{Q=Sw($)}catch{return B0()}let j=B0();for(let H of Q){if(!H.endsWith(".messages.json"))continue;if(H===Z)continue;let X=M7($,H);if(X===W)continue;let Y=await R1(X);if(Y.length===0)continue;j=H0(j,sf(Y))}return j}withPersistedAggregateUsageFloor($,f){let J=xw(f.metadata?.aggregateUsage);if(J)return mw($,J);let W=f.metadata?.aggregatedAgentsCost;if(typeof W!=="number"||!Number.isFinite(W)||W<=$.totalCost)return $;return{...$,totalCost:W}}emitStatus($,f){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:f}})}async emitSessionSnapshot($){let f=await this.getSession($);if(!f)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:B$({session:f,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),bB))}async getRow($){let f=$.trim();if(!f)return;return(await this.listRows(bB)).find((W)=>W.sessionId===f)}async readManifest($){let f=$.trim();if(!f)return;return await this.invokeOptionalValue("readSessionManifest",f)}invoke($,...f){return SB(this.sessionService,$,...f)}invokeOptional($,...f){return hB(this.sessionService,$,...f)}invokeOptionalValue($,...f){return CB(this.sessionService,$,...f)}}function vw($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function uw($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function zB($={}){let f=new U$({sessionService:new F$(new G$),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||P0.CLI,interactive:!1,config:{providerId:gw(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:uw(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,W){let Z=await f.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:vw(Z)}},async abortSession(J){return await f.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function cw($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
|
|
702
|
+
`).trim()||void 0}var kB=120,y7="...";function f4($){let f=$.trim();if(!f)return"";if(Buffer.byteLength(f,"utf8")<=kB)return f;let J=kB-Buffer.byteLength(y7,"utf8");if(J<=0)return y7;let W="";for(let Z of f){if(Buffer.byteLength(W+Z,"utf8")>J)break;W+=Z}return`${W}${y7}`}async function IB($){let f=$?.sessionId?.trim()||"unknown",J=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,Z=[...await R1(J)].reverse().find((X)=>X.role==="assistant"),Q=Z?cw(Z.content):void 0,j=$?.workspaceRoot?.trim()||"workspace",H=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():j;return{title:`Task completed (${f})`,body:f4(Q&&Q.length>0?Q:H.length>0?H:j),severity:"info"}}import{captureSdkError as YW,createSessionId as RS}from"@cline/shared";import{createSessionId as rw}from"@cline/shared";import{createSessionId as pw}from"@cline/shared";function dw($){switch($){case"idle":return"idle";case"pending":return"pending";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function lw($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())f.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())f.parentAgentId=$.parentAgentId;if($.agentId?.trim())f.agentId=$.agentId;if($.conversationId?.trim())f.conversationId=$.conversationId;if($.messagesPath?.trim())f.messagesPath=$.messagesPath;if($.prompt?.trim())f.prompt=$.prompt;if($.provider?.trim())f.provider=$.provider;if($.model?.trim())f.model=$.model;if($.source?.trim())f.source=$.source;if(typeof $.pid==="number")f.pid=$.pid;return Object.keys(f).length>0?f:void 0}function jW($,f,J,W){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:f?.createdByClientId??"hub",status:dw($.status),participants:f?[...f.participants.values()]:[],metadata:lw($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...W?{aggregateUsage:{...W}}:{}}}function u($,f){return{version:$.version,requestId:$.requestId,ok:!0,...f!==void 0?{payload:f}:{}}}function m($,f,J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:f,message:J}}}function HW($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function S0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function Lf($,f,J){return{version:"v1",event:$,eventId:pw("hevt_"),sessionId:J,timestamp:Date.now(),payload:f}}async function r0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let W=await $.sessionHost.getAccumulatedUsage?.(f);return jW(J,$.sessionState.get(f),W?.usage,W?.aggregateUsage)}async function i0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let[W,Z]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(f):[],$.sessionHost.getAccumulatedUsage?.(f)]);return B$({session:J,messages:W,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function XW($,f,J,W,Z={}){let Q=$.sessionState.get(f);if(Q){if(Z.interactive!==void 0)Q.interactive=Z.interactive;if(!Q.participants.has(J))Q.participants.set(J,{clientId:J,attachedAt:Date.now(),role:W});return Q}let j={createdByClientId:J,interactive:Z.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:W}]])};return $.sessionState.set(f,j),j}async function q7($,f){let J=rw("approval_"),W=f.sessionId;if($.sessionState.get(W)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((Q)=>{$.pendingApprovals.set(J,{sessionId:W,resolve:Q}),$.publish($.buildEvent("approval.requested",{approvalId:J,sessionId:f.sessionId,agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,toolCallId:f.toolCallId,toolName:f.toolName,inputJson:JSON.stringify(f.input??null),policy:f.policy},W))})}function w7($,f,J){let W=$.pendingApprovals.get(f);if(!W)return;return $.pendingApprovals.delete(f),W.resolve(J),{sessionId:W.sessionId}}function S7($,f,J){let W=0;for(let[Z,Q]of[...$.pendingApprovals.entries()]){if(!f({approvalId:Z,sessionId:Q.sessionId}))continue;$.pendingApprovals.delete(Z),Q.resolve({approved:!1,reason:J}),$.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},Q.sessionId)),W+=1}return W}async function xB($,f){let J=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"";if(!$.pendingApprovals.get(J))return m(f,"approval_not_found",`Unknown approval: ${J}`);let Z=typeof f.payload?.reason==="string"?f.payload.reason:f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)&&typeof f.payload.payload.reason==="string"?f.payload.payload.reason:void 0,Q=f.payload?.approved===!0,j=w7($,J,{approved:Q,reason:Z});if(!j)return m(f,"approval_not_found",`Unknown approval: ${J}`);return $.publish($.buildEvent("approval.resolved",{approvalId:J,approved:Q,reason:Z},j.sessionId)),u(f,{approvalId:J,approved:Q})}import{createSessionId as aw}from"@cline/shared";function iw($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var mB={debug:10,info:20,warn:30,error:40,silent:50};function nw(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function g($,f,J={}){if(mB[$]<mB[nw()])return;let W=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:f,...Object.fromEntries(Object.entries(J).map(([Z,Q])=>[Z,iw(Q)]).filter(([,Z])=>Z!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${W}`);return}console.log(`[hub] ${W}`)}function h7($,f){let J=f instanceof Error?f.stack||f.message:String(f);g("error",$,{error:J})}async function gB($,f,J,W,Z,Q){let j=aw("capreq_"),H=performance.now();return g("info","capability.request.start",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z}),await new Promise((X,Y)=>{$.pendingCapabilityRequests.set(j,{sessionId:f,targetClientId:Z,capabilityName:J,onProgress:Q,resolve:(A)=>{if(g(A.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z,ok:A.ok,error:A.error,durationMs:Math.round(performance.now()-H)}),!A.ok){Y(Error(A.error||`Capability ${J} was rejected by ${Z}.`));return}X(A.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:W},f)),g("info","capability.request.published",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z})})}function vB($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(J);if(!W)return m(f,"capability_not_found",`Unknown capability request: ${J}`);if((f.clientId?.trim()||"")!==W.targetClientId)return m(f,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==W.sessionId)return m(f,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{};return W.onProgress?.(Q),u(f,{requestId:J})}function z1($,f,J){let W=0;for(let[Z,Q]of[...$.pendingCapabilityRequests.entries()]){if(!f({requestId:Z,...Q}))continue;$.pendingCapabilityRequests.delete(Z),g("warn","capability.request.cancelled",{requestId:Z,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,reason:J}),Q.resolve({ok:!1,error:J}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,ok:!1,cancelled:!0,error:J},Q.sessionId)),W+=1}return W}async function uB($,f){let J=typeof f.payload?.sessionId==="string"?f.payload.sessionId.trim():f.sessionId?.trim()||"",W=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName.trim():"",Z=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId.trim():"";if(!J||!W||!Z)return m(f,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=await $.requestCapability(J,W,Q,Z);return u(f,j)}catch(Q){return m(f,"capability_request_failed",Q instanceof Error?Q.message:String(Q))}}function cB($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(J);if(!W)return m(f,"capability_not_found",`Unknown capability request: ${J}`);let Z=f.clientId?.trim()||"";if(Z!==W.targetClientId)return m(f,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==W.sessionId)return m(f,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);$.pendingCapabilityRequests.delete(J);let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:void 0,j=typeof f.payload?.error==="string"?f.payload.error:void 0,H=f.payload?.ok===!0;return g(H?"info":"warn","capability.respond",{requestId:J,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:Z,ok:H,error:j}),W.resolve({ok:H,payload:Q,error:j}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:Z,ok:H,payload:Q,error:j},W.sessionId)),u(f,{requestId:J,ok:H})}import{createSessionId as tw}from"@cline/shared";function dB($,f){let J=f.payload,W=J?.clientId?.trim()||f.clientId?.trim()||tw("client_");return $.clients.set(W,{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),u(f,{clientId:W})}function lB($,f){let J=f.clientId?.trim(),W=J?$.clients.get(J):void 0;if(!J||!W)return m(f,"client_not_found","Client is not registered with this hub.");let Z=HW(f.payload?.metadata);if(W.lastSeenAt=Date.now(),Z)W.metadata=JSON.parse(JSON.stringify(Z));return u(f)}function pB($,f,J){let W=f.clientId?.trim();if(W)$.clients.delete(W),J(W),$.publish($.buildEvent("hub.client.disconnected",{clientId:W}));return u(f)}function rB($,f){return u(f,{clients:[...$.clients.values()]})}var sw=30000;function ow($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function ew($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function $S($,f,J){let W=J instanceof Error&&J.message.trim()?J.message:`Unknown session: ${f}`;return m($,C1,W)}function fS($){return $?$:void 0}function JS($){let f=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(f&&Number.isFinite(f)&&f>0)return Math.floor(f);let J=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function WS($,f,J,W){let Z=performance.now(),Q=!1,j={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J.sessionId,timeoutMs:W},H=setInterval(()=>{if(Q)return;let A=Math.round(performance.now()-Z);g("warn","run.heartbeat",{...j,elapsedMs:A}),$.publish($.buildEvent("run.heartbeat",{requestId:f.requestId,elapsedMs:A,...W?{timeoutMs:W}:{}},J.sessionId))},sw),X=$.sessionHost.runTurn(J);X.then((A)=>{if(!Q)return;g("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:A?.finishReason})},(A)=>{if(!Q)return;g("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:A})});let Y;try{if(!W)return await X;return await Promise.race([X,new Promise((A,V)=>{Y=setTimeout(()=>{let B=`Hub run ${f.command} timed out after ${W}ms.`;Q=!0,clearInterval(H),V(Error(B)),g("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),S7($,(K)=>K.sessionId===J.sessionId,B),z1($,(K)=>K.sessionId===J.sessionId,B),$.sessionHost.abort(J.sessionId,B).catch((K)=>{g("error","run.timeout_abort_failed",{...j,error:K})})},W)})])}finally{if(Q=!0,clearInterval(H),Y)clearTimeout(Y)}}async function iB($,f){let J=S0(f),W=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof W.prompt==="string"?W.prompt:typeof W.input==="string"?W.input:"";if(!Z.trim())return m(f,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,J));let Q=W.attachments&&typeof W.attachments==="object"&&!Array.isArray(W.attachments)?W.attachments:void 0,j=Array.isArray(Q?.userFiles)?Q.userFiles.filter((A)=>typeof A==="string"):void 0,H=JS(W);$.suppressNextTerminalEventBySession.set(J,"run.start.reply");let X;try{X=await WS($,f,{sessionId:J,prompt:Z,mode:fS(W.mode),delivery:W.delivery==="queue"||W.delivery==="steer"?W.delivery:void 0,userImages:Array.isArray(Q?.userImages)?Q.userImages:void 0,userFiles:j,timeoutMs:H},H)}catch(A){if($.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J);if(y$(A))return $S(f,J,A);throw $.publish($.buildEvent("run.failed",{reason:"error",error:A instanceof Error?A.message:String(A)},J)),A}if(X){let A=await i0($,J),V=ew(X);if($.publish($.buildEvent(ow(X.finishReason),{reason:X.finishReason,...V?{error:V}:{},result:X,...A?{snapshot:A}:{}},J)),$.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J)}else $.suppressNextTerminalEventBySession.delete(J);let Y=await i0($,J);return u(f,X||Y?{...X?{result:X}:{},...Y?{snapshot:Y}:{}}:void 0)}async function nB($,f){let J=S0(f),W=typeof f.payload?.reason==="string"?f.payload.reason:"Run was aborted before pending approval or capability request was resolved.";S7($,(Z)=>Z.sessionId===J,W);try{await $.sessionHost.abort(J,f.payload?.reason)}catch(Z){g("warn","run.abort_failed",{command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J,error:Z})}finally{z1($,(Z)=>Z.sessionId===J,W)}return u(f,{applied:!0})}async function aB($,f){let J=C2(f.payload?.payload);if(!J)return m(f,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(J),u(f,{applied:!0})}async function tB($,f){switch(f.type){case"chunk":return;case"agent_event":await ZS($,f);return;case"hook":if(f.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:f.payload.toolName},f.payload.sessionId));else if(f.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:f.payload.toolName},f.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:f.payload.sessionId,summary:f.payload.summary,lastEvent:f.payload.lifecycle};$.publish($.buildEvent("team.progress",J,f.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:f.payload.sessionId,prompts:f.payload.prompts},f.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:f.payload.id,prompt:f.payload.prompt,delivery:f.payload.delivery,attachmentCount:f.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:f.payload.sessionId,prompt:J},f.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:f.payload.sessionId,snapshot:f.payload.snapshot},f.payload.sessionId));return;case"status":{let[J,W]=await Promise.all([r0($,f.payload.sessionId),i0($,f.payload.sessionId)]);if(J)$.publish($.buildEvent("session.updated",{session:J,...W?{snapshot:W}:{}},f.payload.sessionId));return}case"ended":await QS($,f);return;default:return}}async function ZS($,f){let{sessionId:J,event:W}=f.payload;if(W.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:W.iteration},J));return}if(W.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:W.iteration,hadToolCalls:W.hadToolCalls,toolCallCount:W.toolCallCount},J));return}if(W.type==="content_start"){if(W.contentType==="text"&&typeof W.text==="string"&&W.text.length>0){$.publish($.buildEvent("assistant.delta",{text:W.text},J));return}if(W.contentType==="reasoning"){if(W.redacted&&!W.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof W.reasoning==="string"&&W.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:W.reasoning,redacted:W.redacted===!0},J));return}if(W.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:W.toolCallId,toolName:W.toolName,input:W.input},J));return}}if(W.type==="content_end"){switch(W.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:W.text},J));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:W.reasoning},J));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:W.toolCallId,toolName:W.toolName,output:W.output,error:W.error},J));break}return}if(W.type==="usage"){let Z;try{Z=await $.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}$.publish($.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:W.inputTokens,outputTokens:W.outputTokens,cacheReadTokens:W.cacheReadTokens??0,cacheWriteTokens:W.cacheWriteTokens??0,totalCost:W.cost??0},totals:{inputTokens:W.totalInputTokens,outputTokens:W.totalOutputTokens,cacheReadTokens:W.totalCacheReadTokens??0,cacheWriteTokens:W.totalCacheWriteTokens??0,totalCost:W.totalCost??0},usage:Z?.usage,aggregateUsage:Z?.aggregateUsage,agent:{kind:f.payload.teamRole==="teammate"?"teammate":W.parentAgentId?"subagent":"lead",agentId:W.agentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamAgentId:f.payload.teamAgentId,teamRole:f.payload.teamRole}},J));return}if(W.type==="done")$.publish($.buildEvent("agent.done",{reason:W.reason,text:W.text,iterations:W.iterations,usage:W.usage},J))}async function QS($,f){let J=$.suppressNextTerminalEventBySession.get(f.payload.sessionId),W=J===f.payload.reason||J==="run.start.reply";if(W)$.suppressNextTerminalEventBySession.delete(f.payload.sessionId);let[Z,Q]=await Promise.all([r0($,f.payload.sessionId),i0($,f.payload.sessionId)]);if(f.payload.reason==="completed"){let j=await IB(Z);$.publish($.buildEvent("ui.notify",j,f.payload.sessionId))}if(W)return;$.publish($.buildEvent(f.payload.reason==="aborted"?"run.aborted":f.payload.reason==="error"||f.payload.reason==="failed"?"run.failed":"run.completed",{reason:f.payload.reason,...Q?{snapshot:Q}:{}},f.payload.sessionId))}import{createSessionId as oB,parseRuntimeConfigExtensions as eB}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Sp,HUB_COMPACTION_CAPABILITY as hp,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Cp,HUB_HOOK_CAPABILITY_PREFIX as Ep,HUB_MISTAKE_LIMIT_CAPABILITY as bp,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as kp,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Ip,isHubToolExecutorName as jS}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as up,HUB_COMPACTION_CAPABILITY as cp,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as dp,HUB_HOOK_CAPABILITY_PREFIX as lp,HUB_MISTAKE_LIMIT_CAPABILITY as pp,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as rp,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as ip}from"@cline/shared";var HS=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function Of($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function XS($,f){let J=typeof $.name==="string"?$.name.trim():"",W=typeof $.description==="string"?$.description:"",Z=typeof $.capabilityName==="string"?$.capabilityName.trim():"",Q=Of($.inputSchema);if(!J||!W||!Q||!Z||f.has(Z))return;return f.add(Z),{kind:"tool",capabilityName:Z,name:J,description:W,inputSchema:Q,...Of($.lifecycle)?{lifecycle:Of($.lifecycle)}:{}}}function E7($){if(!Array.isArray($))return[];let f=[],J=new Set;for(let W of $){if(!W||typeof W!=="object"||Array.isArray(W))continue;let Z=W,Q=Z.kind,j=typeof Z.capabilityName==="string"?Z.capabilityName.trim():"";if(!j||J.has(j))continue;if(Q==="tool"){let H=XS(Z,J);if(H)f.push(H);continue}if(Q==="toolExecutor"){let H=Z.executor;if(!jS(H))continue;J.add(j),f.push({kind:"toolExecutor",capabilityName:j,executor:H});continue}if(Q==="hook"){let H=typeof Z.name==="string"?Z.name.trim():"";if(!H)continue;J.add(j),f.push({kind:"hook",capabilityName:j,name:H});continue}if(Q==="compaction"){J.add(j),f.push({kind:"compaction",capabilityName:j,...Of(Z.config)?{config:Of(Z.config)}:{}});continue}if(Q==="checkpoint"){J.add(j),f.push({kind:"checkpoint",capabilityName:j,...Of(Z.config)?{config:Of(Z.config)}:{}});continue}if(Q==="mistakeLimit"){J.add(j),f.push({kind:"mistakeLimit",capabilityName:j});continue}if(Q==="userInstructionService")J.add(j),f.push({kind:"userInstructionService",capabilityName:j})}return f}function sB($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function YS($){return Object.hasOwn($,"update")?$.update:$}function j4($){return $.trim().replace(/^\/+/,"").toLowerCase()}function AS($){let f=($??[]).map(j4).filter(Boolean);return f.length>0?new Set(f):void 0}function VS($,f,J){if(!J)return!0;let W=j4($),Z=j4(f),Q=W.includes(":")?W.split(":").at(-1)??W:W,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(W)||J.has(Z)||J.has(Q)||J.has(j)}function C7($,f){let J=AS(f);return $.records.skill.map((W)=>({id:W.id,name:W.item.name,description:"description"in W.item&&typeof W.item.description==="string"?W.item.description:void 0,disabled:W.item.disabled===!0,skill:W.item})).filter((W)=>VS(W.id,W.name,J))}function BS($,f){let J=async(W,Z)=>{let Q=j4(W),H=C7($,f).filter((B)=>B.id===Q||j4(B.name)===Q||B.id.endsWith(`:${Q}`)).filter((B)=>!B.disabled);if(H.length!==1)return H.length>1?`Skill "${W}" is ambiguous. Use one of: ${H.map((B)=>B.id).join(", ")}`:`Skill "${W}" not found.`;let X=H[0].skill,Y=Z?.trim(),A=Y?`
|
|
703
|
+
<command-args>${Y}</command-args>`:"",V=X.description?.trim()?`Description: ${X.description.trim()}
|
|
704
|
+
|
|
705
|
+
`:"";return`<command-name>${X.name}</command-name>${A}
|
|
706
706
|
<command-instructions>
|
|
707
|
-
${
|
|
708
|
-
</command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>
|
|
707
|
+
${V}${X.instructions}
|
|
708
|
+
</command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>C7($,f).map(({skill:W,...Z})=>Z),enumerable:!0}),J}function KS($,f,J,W){let Z={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},Q=async()=>{let j=await W($,J.capabilityName,{},f);if(j?.snapshot)Z=j.snapshot};return{start:Q,stop:()=>{},refreshType:async()=>{await Q()},listRecords:(j)=>[...Z.records[j]],listRuntimeCommands:()=>[...Z.runtimeCommands],resolveRuntimeSlashCommand:(j)=>{if(!j.startsWith("/")||j.length<2)return j;let X=j.match(/^\/(\S+)/)?.[1];if(!X)return j;let Y=Z.runtimeCommands.find((A)=>A.name===X);return Y?`${Y.instructions}${j.slice(X.length+1)}`:j},hasConfiguredSkills:(j)=>C7(Z,j).some((H)=>!H.disabled),createExtension:(j)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[j.includeRules?"rules":void 0,j.registerSkillsTool?"tools":void 0,j.includeSkills||j.includeWorkflows?"commands":void 0].filter((H)=>Boolean(H))},setup(H){if(j.includeRules)H.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>Nf(Z.records.rule.map((X)=>X.item).filter((X)=>X.disabled!==!0))});if(j.registerSkillsTool)H.registerTool(x1(BS(Z,j.allowedSkillNames)));for(let X of Z.runtimeCommands.filter((Y)=>Y.kind==="skill"&&j.includeSkills||Y.kind==="workflow"&&j.includeWorkflows))H.registerCommand({name:X.name,description:X.description,handler:(Y)=>{let A=Y.trim();return A?`${X.instructions}
|
|
709
709
|
|
|
710
|
-
${V}`:H.instructions}})}})}}function _y($,f,J,Q){let Z=J.map((W)=>[W.executor,async(...j)=>{let X=j.at(-1),H=j.slice(0,-1);return(await Q($,W.capabilityName,{executor:W.executor,args:H,context:fB(X)},f))?.result}]);return Z.length>0?Object.fromEntries(Z):void 0}function Ny($,f,J,Q){if(J.length===0)return;return J.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,lifecycle:Z.lifecycle,async execute(W,j){return(await Q($,Z.capabilityName,{toolName:Z.name,input:W,context:fB(j)},f,j.emitUpdate?(H)=>{j.emitUpdate?.(Dy(H))}:void 0))?.result}}))}function Ty($,f,J,Q){let Z=new Map(J.map((j)=>[j.name,j])),W={};for(let j of Py){let X=Z.get(j);if(!X)continue;W[j]=async(H)=>{return(await Q($,X.capabilityName,{context:H},f))?.control}}return Object.keys(W).length>0?W:void 0}function sZ($){let f=$.contributions.filter((H)=>H.kind==="toolExecutor"),J=$.contributions.filter((H)=>H.kind==="tool"),Q=$.contributions.filter((H)=>H.kind==="hook"),Z=$.contributions.find((H)=>H.kind==="compaction"),W=$.contributions.find((H)=>H.kind==="checkpoint"),j=$.contributions.find((H)=>H.kind==="mistakeLimit"),X=$.contributions.find((H)=>H.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:_y($.sessionId,$.targetClientId,f,$.requestCapability),localRuntime:{...Q.length>0?{hooks:Ty($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...J.length>0?{extraTools:Ny($.sessionId,$.targetClientId,J,$.requestCapability)}:{},...Z?{compaction:{...$.sessionConfig?.compaction??{},...Z.config,compact:async(H)=>{return(await $.requestCapability($.sessionId,Z.capabilityName,{context:H},$.targetClientId))?.result}}}:{},...W?{checkpoint:{...$.sessionConfig?.checkpoint??{},...W.config,createCheckpoint:async(H)=>{return(await $.requestCapability($.sessionId,W.capabilityName,{context:H},$.targetClientId))?.result}}}:{},...j?{onConsecutiveMistakeLimitReached:async(H)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:H},$.targetClientId))?.result}}:{},...X?{userInstructionService:zy($.sessionId,$.targetClientId,X,$.requestCapability)}:{}}}}var ZB="hubCapabilityOwnerClientId";function WB($,f){$[ZB]=f}function My($){let f=$?.[ZB];return typeof f==="string"&&f.trim()?f.trim():void 0}async function jB($,f,J){let Q=performance.now(),Z={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:f.sessionId};g("info","session.create.begin",Z);let W=f.payload&&typeof f.payload==="object"?f.payload:{},j=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{},X=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0,H=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{};if(typeof X?.mode==="string")j.mode=X.mode;else if(typeof H.mode==="string")j.mode=H.mode;if(typeof X?.systemPrompt==="string")j.systemPrompt=X.systemPrompt;else if(typeof H.systemPrompt==="string")j.systemPrompt=H.systemPrompt;if(X?.checkpoint?.enabled===!0)j.checkpointEnabled=!0;else if(H.checkpointEnabled===!0)j.checkpointEnabled=!0;let Y=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},V=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():"";if(!V)return g("warn","session.create.invalid",{...Z,reason:"missing_workspace_root"}),m(f,"invalid_session_create","session.create requires workspaceRoot or cwd");let A=f.clientId?.trim()||"hub-client",B=tZ(H.clientContributions);if(g("info","session.create.contributions_parsed",{...Z,clientId:A,workspaceRoot:V,cwd:typeof W.cwd==="string"?W.cwd:void 0,contributionCount:B.length}),B.length>0)WB(j,A);let K=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||JB(),D=QB(H.configExtensions);g("info","session.create.runtime_build.begin",{...Z,sessionId:K,configExtensionCount:D?.length??0});let F=sZ({sessionId:K,targetClientId:A,contributions:B,sessionConfig:X,requestCapability:$.requestCapability});g("info","session.create.start_session.begin",{...Z,sessionId:K,provider:X?.providerId??(typeof Y.provider==="string"?Y.provider:typeof j.provider==="string"?j.provider:"hub"),model:X?.modelId??(typeof Y.model==="string"?Y.model:typeof j.model==="string"?j.model:"hub")});let P=await $.sessionHost.startSession({source:typeof j.source==="string"?j.source:void 0,interactive:j.interactive!==!1,sessionMetadata:Object.keys(j).length>0?j:void 0,initialMessages:Array.isArray(W.initialMessages)?W.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:D,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:K,providerId:X?.providerId??(typeof Y.provider==="string"?Y.provider:typeof j.provider==="string"?j.provider:"hub"),modelId:X?.modelId??(typeof Y.model==="string"?Y.model:typeof j.model==="string"?j.model:"hub"),apiKey:X?.apiKey??(typeof Y.apiKey==="string"?Y.apiKey:void 0),cwd:X?.cwd??(typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():V),workspaceRoot:X?.workspaceRoot??V,systemPrompt:X?.systemPrompt??(typeof H.systemPrompt==="string"?H.systemPrompt:""),mode:X?.mode??(H.mode==="plan"||H.mode==="yolo"?H.mode:"act"),maxIterations:X?.maxIterations??(typeof H.maxIterations==="number"?H.maxIterations:void 0),enableTools:X?.enableTools??H.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??H.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??H.enableTeams!==!1,checkpoint:X?.checkpoint??(H.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof j.teamName==="string"?j.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):H.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});g("info","session.create.start_session.end",{...Z,sessionId:P.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!P.result}),I5($,P.sessionId,A,"creator",{interactive:j.interactive!==!1}),g("info","session.create.read_records.begin",{...Z,sessionId:P.sessionId});let[U,z]=await Promise.all([r0($,P.sessionId),i0($,P.sessionId)]);if(g("info","session.create.read_records.end",{...Z,sessionId:P.sessionId,hasSession:!!U,hasSnapshot:!!z,elapsedMs:Math.round(performance.now()-Q)}),U)$.publish($.buildEvent("session.created",{session:U,...z?{snapshot:z}:{}},P.sessionId));return g("info","session.create.reply",{...Z,sessionId:P.sessionId,elapsedMs:Math.round(performance.now()-Q)}),u(f,{session:U,...z?{snapshot:z}:{}})}async function XB($,f,J){let Q=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof Q.sessionId==="string"?Q.sessionId.trim():f.sessionId?.trim()||"",W=Q.checkpointRunCount;if(!Z)return m(f,"invalid_restore","session.restore requires a session id");let j=Q.restore&&typeof Q.restore==="object"?Q.restore:{},X=j.messages!==!1;if(typeof W!=="number")return m(f,"invalid_restore","checkpointRunCount must be a positive integer");try{let H=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(X&&!H)return m(f,"invalid_restore","sessionConfig is required when restore.messages is true");let Y=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},V=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof H?.mode==="string")V.mode=H.mode;else if(typeof Y.mode==="string")V.mode=Y.mode;if(typeof H?.systemPrompt==="string")V.systemPrompt=H.systemPrompt;else if(typeof Y.systemPrompt==="string")V.systemPrompt=Y.systemPrompt;if(H?.checkpoint?.enabled===!0)V.checkpointEnabled=!0;else if(Y.checkpointEnabled===!0)V.checkpointEnabled=!0;let A=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},B=f.clientId?.trim()||"hub-client",G=tZ(Y.clientContributions);if(G.length>0)WB(V,B);let D=(typeof H?.sessionId==="string"?H.sessionId.trim():"")||JB(),F=QB(Y.configExtensions),P=sZ({sessionId:D,targetClientId:B,contributions:G,sessionConfig:H,requestCapability:$.requestCapability}),z=await new K1().restoreCheckpoint({sessionId:Z,checkpointRunCount:W,restore:{messages:j.messages,workspace:j.workspace,omitCheckpointMessageFromSession:j.omitCheckpointMessageFromSession===!0},start:H,cwd:typeof H?.cwd==="string"&&H.cwd.trim()||typeof H?.workspaceRoot==="string"&&H.workspaceRoot.trim()||void 0,getSession:(N)=>$.sessionHost.getSession(N),readMessages:(N)=>$.sessionHost.readSessionMessages(N),buildStartInput:(N)=>{if(N.restoredCheckpointMetadata)V.checkpoint=N.restoredCheckpointMetadata;let w=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():N.sourceSession.workspaceRoot||N.sourceSession.cwd;return{source:typeof V.source==="string"?V.source:void 0,interactive:V.interactive!==!1,sessionMetadata:{...V,restoredFromSessionId:Z,restoredCheckpointRunCount:W},initialMessages:N.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:F,...P.localRuntime},capabilities:{toolExecutors:P.toolExecutors,requestToolApproval:J},config:{...H??{},sessionId:D,providerId:H?.providerId??(typeof A.provider==="string"?A.provider:N.sourceSession.provider),modelId:H?.modelId??(typeof A.model==="string"?A.model:N.sourceSession.model),apiKey:H?.apiKey??(typeof A.apiKey==="string"?A.apiKey:""),cwd:H?.cwd??N.plan.cwd,workspaceRoot:H?.workspaceRoot??w,systemPrompt:H?.systemPrompt??(typeof Y.systemPrompt==="string"?Y.systemPrompt:""),mode:H?.mode??(Y.mode==="plan"||Y.mode==="yolo"?Y.mode:"act"),maxIterations:H?.maxIterations??(typeof Y.maxIterations==="number"?Y.maxIterations:void 0),enableTools:H?.enableTools??Y.enableTools!==!1,enableSpawnAgent:H?.enableSpawnAgent??Y.enableSpawn!==!1,enableAgentTeams:H?.enableAgentTeams??Y.enableTeams!==!1,checkpoint:H?.checkpoint??(Y.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:H?.teamName??(typeof V.teamName==="string"?V.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):Y.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(N)=>$.sessionHost.startSession(N),getStartedSessionId:(N)=>N.sessionId,readRestoredSession:(N)=>$.sessionHost.getSession(N)});if(!X)return u(f,{checkpoint:z.checkpoint});let _=z.startResult;if(!_)return m(f,"restore_failed","Checkpoint restore did not start a session");I5($,_.sessionId,B,"creator",{interactive:V.interactive!==!1});let[R,L]=await Promise.all([r0($,_.sessionId),i0($,_.sessionId)]);if(R)$.publish($.buildEvent("session.created",{session:R,...L?{snapshot:L}:{}},_.sessionId));return u(f,{session:R,...L?{snapshot:L}:{},messages:z.messages??[],checkpoint:z.checkpoint})}catch(H){if(H instanceof S0)return m(f,H.code,H.code==="session_not_found"?`Unknown session: ${Z}`:H.message);return m(f,"restore_failed",H instanceof Error?H.message:String(H))}}async function HB($,f){let J=h0(f);if(!J)return m(f,"invalid_session_attach","session.attach requires a session id");I5($,J,f.clientId?.trim()||"hub-client","participant");let Q=await r0($,J);if(Q)$.publish($.buildEvent("session.attached",{session:Q},J));return Q?u(f,{session:Q}):m(f,"session_not_found",`Unknown session: ${J}`)}async function YB($,f){let J=h0(f);if(!J)return m(f,"invalid_session_detach","session.detach requires a session id");let Q=f.clientId?.trim()||"hub-client",[Z]=await Promise.all([r0($,J)]),W=My(Z?.metadata)??Q,j=$.sessionState.get(J);if(j){if(j.participants.delete(Q),j.createdByClientId===Q)j.createdByClientId=W;if(j.participants.size===0)$.sessionState.delete(J)}F1($,(Y)=>Y.sessionId===J&&Y.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[X,H]=await Promise.all([r0($,J),i0($,J)]);return $.publish($.buildEvent("session.detached",X?{session:X,...H?{snapshot:H}:{},clientId:Q}:{clientId:Q},J)),u(f)}async function VB($,f){let J=h0(f),Q=f.payload?.includeSnapshot===!0,[Z,W]=await Promise.all([r0($,J),Q?i0($,J):Promise.resolve(void 0)]);return Z?u(f,{session:Z,...W?{snapshot:W}:{}}):m(f,"session_not_found",`Unknown session: ${J}`)}async function AB($,f){let J=h0(f);if(!J)return m(f,"invalid_session_id","session.messages requires a session id");if(!await r0($,J))return m(f,"session_not_found",`Unknown session: ${J}`);let Z=await $.sessionHost.readSessionMessages(J);return u(f,{sessionId:J,messages:Z})}async function BB($,f){let J=typeof f.payload?.limit==="number"?f.payload.limit:200,Z=(await $.sessionHost.listSessions(J)).map((W)=>b5(W,$.sessionState.get(W.sessionId)));return u(f,{sessions:Z})}async function GB($,f){let J=h0(f),Q=k5(f.payload?.metadata),Z=await $.sessionHost.updateSession(J,{metadata:Q}),[W,j]=await Promise.all([r0($,J),i0($,J)]);if(W)$.publish($.buildEvent("session.updated",{session:W,...j?{snapshot:j}:{}},J));return{version:f.version,requestId:f.requestId,ok:Z.updated,payload:{updated:Z.updated,session:W,...j?{snapshot:j}:{}}}}async function KB($,f){let J=h0(f),Q=await $.sessionHost.deleteSession(J);return $.sessionState.delete(J),u(f,{deleted:Q})}async function FB($,f){let J=h0(f),Q=$.sessionHost.pendingPrompts;if(!Q)return m(f,"pending_prompts_unavailable","Pending prompt service is not available.");let Z=await Q.list({sessionId:J});return u(f,{sessionId:J,prompts:Z})}async function PB($,f){let J=h0(f),Q=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=typeof f.payload?.prompt==="string"?f.payload.prompt:void 0,W=f.payload?.delivery==="queue"||f.payload?.delivery==="steer"?f.payload.delivery:void 0,j=$.sessionHost.pendingPrompts;if(!j)return m(f,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await j.update({sessionId:J,promptId:Q,prompt:Z,delivery:W});return u(f,X)}async function UB($,f){let J=h0(f),Q=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=$.sessionHost.pendingPrompts;if(!Z)return m(f,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.delete({sessionId:J,promptId:Q});return u(f,W)}function DB($){switch($){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var yy=new Set(["skills","workflows","rules","tools","mcp"]);function oZ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function d6($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${f}' must be a string.`);return J}function wy($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${f}' must be a boolean.`);return J}function RB($){if($===void 0)return{};if(!oZ($))throw Error("settings.list payload must be an object.");return{cwd:d6($,"cwd"),workspaceRoot:d6($,"workspaceRoot"),availabilityContext:oZ($.availabilityContext)?$.availabilityContext:void 0}}function Sy($){if(!oZ($))throw Error("settings.toggle payload must be an object.");let{type:f}=$;if(typeof f!=="string"||!yy.has(f))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...RB($),type:f,id:d6($,"id"),path:d6($,"path"),name:d6($,"name"),enabled:wy($,"enabled")}}class M8{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=qy("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new B$({sessionService:new A$(new Y$),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(f)=>this.publish(f),buildEvent:H2,requestCapability:(f,J,Q,Z,W)=>dA(this.ctx,f,J,Q,Z,W)},this.schedules=new P2({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(f,J)=>{let Q=f==="schedule.execution.completed"?"schedule.execution_completed":f==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(H2(Q,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new B2(this.schedules),this.settings=$.settingsService??new V1,$.cronOptions)this.cronService=new O6({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((f)=>{$B(this.ctx,f).catch((J)=>{nZ("session event handling failed",J),x5(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:J,severity:"error",handled:!0,context:{eventType:f.type,sessionId:f.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())rZ(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(F1(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let f=await this.dispatchCommand($);return this.captureFailedReply($,f),f}catch(f){throw x5(this.options.telemetry,{component:"core",operation:"hub.command",error:f,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),f}}async dispatchCommand($){switch($.command){case"client.register":return iA(this.ctx,$);case"client.update":return nA(this.ctx,$);case"client.unregister":return aA(this.ctx,$,(f)=>{this.listeners.delete(f),this.detachClientFromSessions(f)});case"client.list":return tA(this.ctx,$);case"session.create":return await jB(this.ctx,$,(f)=>pZ(this.ctx,f));case"session.restore":return await XB(this.ctx,$,(f)=>pZ(this.ctx,f));case"session.attach":return await HB(this.ctx,$);case"session.detach":return await YB(this.ctx,$);case"session.get":return await VB(this.ctx,$);case"session.messages":return await AB(this.ctx,$);case"session.list":return await BB(this.ctx,$);case"session.update":return await GB(this.ctx,$);case"session.pending_prompts":return await FB(this.ctx,$);case"session.update_pending_prompt":return await PB(this.ctx,$);case"session.remove_pending_prompt":return await UB(this.ctx,$);case"session.delete":return await KB(this.ctx,$);case"session.hook":return await eA(this.ctx,$);case"run.start":case"session.send_input":return await sA(this.ctx,$);case"run.abort":return await oA(this.ctx,$);case"capability.request":return await pA(this.ctx,$);case"approval.respond":return await uA(this.ctx,$);case"capability.respond":return rA(this.ctx,$);case"capability.progress":return lA(this.ctx,$);case"ui.notify":return this.publish(H2("ui.notify",$.payload??{})),u($);case"ui.show_window":return this.publish(H2("ui.show_window",$.payload??{})),u($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let f=await this.scheduleCommands.handleCommand($);if(f.ok){let J=DB($.command);if(J)this.publish(H2(J,f.payload))}return f}}}captureFailedReply($,f){if(f.ok||!f.error||!hy(f.error.code))return;x5(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(f.error.message),severity:f.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:f.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let f=await this.settings.list(RB($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:f instanceof Error?f.message:String(f)}}}}async handleSettingsToggle($){try{let f=await this.settings.toggle(Sy($.payload));return this.publish(H2("settings.changed",{types:f.changedTypes,snapshot:f.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f.snapshot,changedTypes:f.changedTypes}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:f instanceof Error?f.message:String(f)}}}}subscribe($,f,J){let Q=this.listeners.get($)??new Set,Z={sessionId:J?.sessionId,listener:f};return Q.add(Z),this.listeners.set($,Q),()=>{let W=this.listeners.get($);if(!W)return;if(W.delete(Z),W.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[f,J]of this.sessionState.entries())if(J.participants.delete($),J.participants.size===0)this.sessionState.delete(f);F1(this.ctx,(f)=>f.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let f of this.listeners.values())for(let J of f){if(J.sessionId&&J.sessionId!==$.sessionId)continue;try{J.listener($)}catch(Q){nZ(`listener threw while publishing ${$.event}`,Q),x5(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function hy($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as ky}from"node:crypto";import Iy from"node:http";import xy from"node:net";import{URL as zB}from"node:url";import{WebSocketServer as my}from"ws";import{captureSdkError as LB,HUB_COMMAND_SLOW_LOG_MS as Cy,resolveHubCommandTimeoutMs as Ey,safeJsonParse as by}from"@cline/shared";function eZ($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function OB($,f,J){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:f,message:J}}}class m6{transport;telemetry;constructor($,f){this.transport=$;this.telemetry=f}attach($){let f=new Map,J=new Set,Q=!1,Z=(H)=>{try{$.send(JSON.stringify(H))}catch(Y){console.error(`[hub] failed to send websocket frame: ${Y instanceof Error?Y.stack||Y.message:String(Y)}`)}},W=(H)=>{Z({kind:"event",envelope:H})},j=async(H)=>{try{let Y=JSON.parse(H.data);switch(Y.kind){case"command":{let V=performance.now(),A=!1,B=eZ(Y);g("info","command.start",B);let G=setTimeout(()=>{if(A)return;g("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-V)})},Cy),K=this.transport.command(Y.envelope);K.then((_)=>{if(!A)return;g(_.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-V),ok:_.ok,errorCode:_.error?.code,errorMessage:_.error?.message})},(_)=>{if(!A)return;g("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-V),error:_})});let D=!1,F,P,U=Ey(Y.envelope.command,Y.envelope.timeoutMs);try{P=U===null?await K:await Promise.race([K,new Promise((_)=>{F=setTimeout(()=>{D=!0,LB(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${Y.envelope.command} did not complete within ${U}ms.`),severity:"error",handled:!0,context:{...B,timeoutMs:U}}),_(OB(Y,"hub_command_timeout",`Hub command ${Y.envelope.command} did not complete within ${U}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${Y.envelope.requestId}.`))},U)})])}catch(_){if(clearTimeout(G),F)clearTimeout(F);throw _}if(A=D,clearTimeout(G),F)clearTimeout(F);let z=Math.round(performance.now()-V);if(D)g("error","command.timeout",{...B,durationMs:z,timeoutMs:U});else g(P.ok?"info":"warn","command.end",{...B,durationMs:z,ok:P.ok,errorCode:P.error?.code,errorMessage:P.error?.message});if(Y.envelope.command==="client.register"&&P.ok){let R=(Y.envelope.payload??{}).clientId?.trim()||Y.envelope.clientId?.trim();if(R)J.add(R)}else if(Y.envelope.command==="client.unregister"&&P.ok){let _=Y.envelope.clientId?.trim();if(_)J.delete(_)}Z({kind:"reply",envelope:P});break}case"stream.subscribe":{let V=`${Y.clientId}:${Y.sessionId??"*"}`;if(f.has(V))break;let A=await this.transport.subscribe(Y.clientId,W,{sessionId:Y.sessionId});f.set(V,A);break}case"stream.unsubscribe":{let V=`${Y.clientId}:${Y.sessionId??"*"}`;f.get(V)?.(),f.delete(V);break}case"reply":case"event":break}}catch(Y){let V=typeof H.data==="string"?by(H.data):void 0;if(!V||V.kind!=="command"){g("error","rejected malformed websocket frame",{error:Y});return}g("error","command.error",{...eZ(V),error:Y}),LB(this.telemetry,{component:"core",operation:"hub.websocket_command",error:Y,severity:"error",handled:!0,context:eZ(V)}),Z({kind:"reply",envelope:OB(V,"command_failed",Y instanceof Error?Y.message:"Unknown hub error")})}},X=()=>{if(Q)return;Q=!0;for(let H of f.values())H();f.clear();for(let H of J)this.transport.command({version:"v1",command:"client.unregister",clientId:H});J.clear(),$.removeEventListener("message",j),$.removeEventListener("close",X)};return $.addEventListener("message",j),$.addEventListener("close",X),X}}class g6{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,f,J){return this.transport.subscribe($,f,J)}}function gy($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();return String($)}function vy($){return{send(f){$.send(f)},addEventListener(f,J){if(f==="message"){$.on("message",(Q)=>{J({data:gy(Q)})});return}$.on("close",J)},removeEventListener(){}}}function uy($){try{$.write(`HTTP/1.1 400 Bad Request\r
|
|
710
|
+
${A}`:X.instructions}})}})}}function GS($,f,J,W){let Z=J.map((Q)=>[Q.executor,async(...j)=>{let H=j.at(-1),X=j.slice(0,-1);return(await W($,Q.capabilityName,{executor:Q.executor,args:X,context:sB(H)},f))?.result}]);return Z.length>0?Object.fromEntries(Z):void 0}function PS($,f,J,W){if(J.length===0)return;return J.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,lifecycle:Z.lifecycle,async execute(Q,j){return(await W($,Z.capabilityName,{toolName:Z.name,input:Q,context:sB(j)},f,j.emitUpdate?(X)=>{j.emitUpdate?.(YS(X))}:void 0))?.result}}))}function FS($,f,J,W){let Z=new Map(J.map((j)=>[j.name,j])),Q={};for(let j of HS){let H=Z.get(j);if(!H)continue;Q[j]=async(X)=>{return(await W($,H.capabilityName,{context:X},f))?.control}}return Object.keys(Q).length>0?Q:void 0}function b7($){let f=$.contributions.filter((X)=>X.kind==="toolExecutor"),J=$.contributions.filter((X)=>X.kind==="tool"),W=$.contributions.filter((X)=>X.kind==="hook"),Z=$.contributions.find((X)=>X.kind==="compaction"),Q=$.contributions.find((X)=>X.kind==="checkpoint"),j=$.contributions.find((X)=>X.kind==="mistakeLimit"),H=$.contributions.find((X)=>X.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:GS($.sessionId,$.targetClientId,f,$.requestCapability),localRuntime:{...W.length>0?{hooks:FS($.sessionId,$.targetClientId,W,$.requestCapability)}:{},...J.length>0?{extraTools:PS($.sessionId,$.targetClientId,J,$.requestCapability)}:{},...Z?{compaction:{...$.sessionConfig?.compaction??{},...Z.config,compact:async(X)=>{return(await $.requestCapability($.sessionId,Z.capabilityName,{context:X},$.targetClientId))?.result}}}:{},...Q?{checkpoint:{...$.sessionConfig?.checkpoint??{},...Q.config,createCheckpoint:async(X)=>{return(await $.requestCapability($.sessionId,Q.capabilityName,{context:X},$.targetClientId))?.result}}}:{},...j?{onConsecutiveMistakeLimitReached:async(X)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:X},$.targetClientId))?.result}}:{},...H?{userInstructionService:KS($.sessionId,$.targetClientId,H,$.requestCapability)}:{}}}}var $K="hubCapabilityOwnerClientId";function fK($,f){$[$K]=f}function US($){let f=$?.[$K];return typeof f==="string"&&f.trim()?f.trim():void 0}async function JK($,f,J){let W=performance.now(),Z={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:f.sessionId};g("info","session.create.begin",Z);let Q=f.payload&&typeof f.payload==="object"?f.payload:{},j=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{},H=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0,X=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{};if(typeof H?.mode==="string")j.mode=H.mode;else if(typeof X.mode==="string")j.mode=X.mode;if(typeof H?.systemPrompt==="string")j.systemPrompt=H.systemPrompt;else if(typeof X.systemPrompt==="string")j.systemPrompt=X.systemPrompt;if(H?.checkpoint?.enabled===!0)j.checkpointEnabled=!0;else if(X.checkpointEnabled===!0)j.checkpointEnabled=!0;let Y=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},A=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():"";if(!A)return g("warn","session.create.invalid",{...Z,reason:"missing_workspace_root"}),m(f,"invalid_session_create","session.create requires workspaceRoot or cwd");let V=f.clientId?.trim()||"hub-client",B=E7(X.clientContributions);if(g("info","session.create.contributions_parsed",{...Z,clientId:V,workspaceRoot:A,cwd:typeof Q.cwd==="string"?Q.cwd:void 0,contributionCount:B.length}),B.length>0)fK(j,V);let G=(typeof H?.sessionId==="string"?H.sessionId.trim():"")||oB(),R=eB(X.configExtensions);g("info","session.create.runtime_build.begin",{...Z,sessionId:G,configExtensionCount:R?.length??0});let P=b7({sessionId:G,targetClientId:V,contributions:B,sessionConfig:H,requestCapability:$.requestCapability});g("info","session.create.start_session.begin",{...Z,sessionId:G,provider:H?.providerId??(typeof Y.provider==="string"?Y.provider:typeof j.provider==="string"?j.provider:"hub"),model:H?.modelId??(typeof Y.model==="string"?Y.model:typeof j.model==="string"?j.model:"hub")});let F=await $.sessionHost.startSession({source:typeof j.source==="string"?j.source:void 0,interactive:j.interactive!==!1,sessionMetadata:Object.keys(j).length>0?j:void 0,initialMessages:Array.isArray(Q.initialMessages)?Q.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...P.localRuntime},capabilities:{toolExecutors:P.toolExecutors,requestToolApproval:J},config:{...H??{},sessionId:G,providerId:H?.providerId??(typeof Y.provider==="string"?Y.provider:typeof j.provider==="string"?j.provider:"hub"),modelId:H?.modelId??(typeof Y.model==="string"?Y.model:typeof j.model==="string"?j.model:"hub"),apiKey:H?.apiKey??(typeof Y.apiKey==="string"?Y.apiKey:void 0),cwd:H?.cwd??(typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():A),workspaceRoot:H?.workspaceRoot??A,systemPrompt:H?.systemPrompt??(typeof X.systemPrompt==="string"?X.systemPrompt:""),mode:H?.mode??(X.mode==="plan"||X.mode==="yolo"?X.mode:"act"),maxIterations:H?.maxIterations??(typeof X.maxIterations==="number"?X.maxIterations:void 0),enableTools:H?.enableTools??X.enableTools!==!1,enableSpawnAgent:H?.enableSpawnAgent??X.enableSpawn!==!1,enableAgentTeams:H?.enableAgentTeams??X.enableTeams!==!1,checkpoint:H?.checkpoint??(X.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:H?.teamName??(typeof j.teamName==="string"?j.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):X.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});g("info","session.create.start_session.end",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-W),hasImmediateResult:!!F.result}),XW($,F.sessionId,V,"creator",{interactive:j.interactive!==!1}),g("info","session.create.read_records.begin",{...Z,sessionId:F.sessionId});let[U,_]=await Promise.all([r0($,F.sessionId),i0($,F.sessionId)]);if(g("info","session.create.read_records.end",{...Z,sessionId:F.sessionId,hasSession:!!U,hasSnapshot:!!_,elapsedMs:Math.round(performance.now()-W)}),U)$.publish($.buildEvent("session.created",{session:U,..._?{snapshot:_}:{}},F.sessionId));return g("info","session.create.reply",{...Z,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-W)}),u(f,{session:U,..._?{snapshot:_}:{}})}async function WK($,f,J){let W=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof W.sessionId==="string"?W.sessionId.trim():f.sessionId?.trim()||"",Q=W.checkpointRunCount;if(!Z)return m(f,"invalid_restore","session.restore requires a session id");let j=W.restore&&typeof W.restore==="object"?W.restore:{},H=j.messages!==!1;if(typeof Q!=="number")return m(f,"invalid_restore","checkpointRunCount must be a positive integer");try{let X=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0;if(H&&!X)return m(f,"invalid_restore","sessionConfig is required when restore.messages is true");let Y=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{},A=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{};if(typeof X?.mode==="string")A.mode=X.mode;else if(typeof Y.mode==="string")A.mode=Y.mode;if(typeof X?.systemPrompt==="string")A.systemPrompt=X.systemPrompt;else if(typeof Y.systemPrompt==="string")A.systemPrompt=Y.systemPrompt;if(X?.checkpoint?.enabled===!0)A.checkpointEnabled=!0;else if(Y.checkpointEnabled===!0)A.checkpointEnabled=!0;let V=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},B=f.clientId?.trim()||"hub-client",K=E7(Y.clientContributions);if(K.length>0)fK(A,B);let R=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||oB(),P=eB(Y.configExtensions),F=b7({sessionId:R,targetClientId:B,contributions:K,sessionConfig:X,requestCapability:$.requestCapability}),_=await new _1().restoreCheckpoint({sessionId:Z,checkpointRunCount:Q,restore:{messages:j.messages,workspace:j.workspace,omitCheckpointMessageFromSession:j.omitCheckpointMessageFromSession===!0},start:X,cwd:typeof X?.cwd==="string"&&X.cwd.trim()||typeof X?.workspaceRoot==="string"&&X.workspaceRoot.trim()||void 0,getSession:(N)=>$.sessionHost.getSession(N),readMessages:(N)=>$.sessionHost.readSessionMessages(N),buildStartInput:(N)=>{if(N.restoredCheckpointMetadata)A.checkpoint=N.restoredCheckpointMetadata;let q=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():N.sourceSession.workspaceRoot||N.sourceSession.cwd;return{source:typeof A.source==="string"?A.source:void 0,interactive:A.interactive!==!1,sessionMetadata:{...A,restoredFromSessionId:Z,restoredCheckpointRunCount:Q},initialMessages:N.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:P,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:R,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:N.sourceSession.provider),modelId:X?.modelId??(typeof V.model==="string"?V.model:N.sourceSession.model),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:""),cwd:X?.cwd??N.plan.cwd,workspaceRoot:X?.workspaceRoot??q,systemPrompt:X?.systemPrompt??(typeof Y.systemPrompt==="string"?Y.systemPrompt:""),mode:X?.mode??(Y.mode==="plan"||Y.mode==="yolo"?Y.mode:"act"),maxIterations:X?.maxIterations??(typeof Y.maxIterations==="number"?Y.maxIterations:void 0),enableTools:X?.enableTools??Y.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??Y.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??Y.enableTeams!==!1,checkpoint:X?.checkpoint??(Y.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof A.teamName==="string"?A.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):Y.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(N)=>$.sessionHost.startSession(N),getStartedSessionId:(N)=>N.sessionId,readRestoredSession:(N)=>$.sessionHost.getSession(N)});if(!H)return u(f,{checkpoint:_.checkpoint});let z=_.startResult;if(!z)return m(f,"restore_failed","Checkpoint restore did not start a session");XW($,z.sessionId,B,"creator",{interactive:A.interactive!==!1});let[D,O]=await Promise.all([r0($,z.sessionId),i0($,z.sessionId)]);if(D)$.publish($.buildEvent("session.created",{session:D,...O?{snapshot:O}:{}},z.sessionId));return u(f,{session:D,...O?{snapshot:O}:{},messages:_.messages??[],checkpoint:_.checkpoint})}catch(X){if(X instanceof w0)return m(f,X.code,X.code==="session_not_found"?`Unknown session: ${Z}`:X.message);return m(f,"restore_failed",X instanceof Error?X.message:String(X))}}async function ZK($,f){let J=S0(f);if(!J)return m(f,"invalid_session_attach","session.attach requires a session id");XW($,J,f.clientId?.trim()||"hub-client","participant");let W=await r0($,J);if(W)$.publish($.buildEvent("session.attached",{session:W},J));return W?u(f,{session:W}):m(f,"session_not_found",`Unknown session: ${J}`)}async function QK($,f){let J=S0(f);if(!J)return m(f,"invalid_session_detach","session.detach requires a session id");let W=f.clientId?.trim()||"hub-client",[Z]=await Promise.all([r0($,J)]),Q=US(Z?.metadata)??W,j=$.sessionState.get(J);if(j){if(j.participants.delete(W),j.createdByClientId===W)j.createdByClientId=Q;if(j.participants.size===0)$.sessionState.delete(J)}z1($,(Y)=>Y.sessionId===J&&Y.targetClientId===W,`Capability owner client ${W} detached before request was resolved.`);let[H,X]=await Promise.all([r0($,J),i0($,J)]);return $.publish($.buildEvent("session.detached",H?{session:H,...X?{snapshot:X}:{},clientId:W}:{clientId:W},J)),u(f)}async function jK($,f){let J=S0(f),W=f.payload?.includeSnapshot===!0,[Z,Q]=await Promise.all([r0($,J),W?i0($,J):Promise.resolve(void 0)]);return Z?u(f,{session:Z,...Q?{snapshot:Q}:{}}):m(f,"session_not_found",`Unknown session: ${J}`)}async function HK($,f){let J=S0(f);if(!J)return m(f,"invalid_session_id","session.messages requires a session id");if(!await r0($,J))return m(f,"session_not_found",`Unknown session: ${J}`);let Z=await $.sessionHost.readSessionMessages(J);return u(f,{sessionId:J,messages:Z})}async function XK($,f){let J=typeof f.payload?.limit==="number"?f.payload.limit:200,Z=(await $.sessionHost.listSessions(J)).map((Q)=>jW(Q,$.sessionState.get(Q.sessionId)));return u(f,{sessions:Z})}async function YK($,f){let J=S0(f),W=HW(f.payload?.metadata),Z=await $.sessionHost.updateSession(J,{metadata:W}),[Q,j]=await Promise.all([r0($,J),i0($,J)]);if(Q)$.publish($.buildEvent("session.updated",{session:Q,...j?{snapshot:j}:{}},J));return{version:f.version,requestId:f.requestId,ok:Z.updated,payload:{updated:Z.updated,session:Q,...j?{snapshot:j}:{}}}}async function AK($,f){let J=S0(f),W=await $.sessionHost.deleteSession(J);return $.sessionState.delete(J),u(f,{deleted:W})}async function VK($,f){let J=S0(f),W=$.sessionHost.pendingPrompts;if(!W)return m(f,"pending_prompts_unavailable","Pending prompt service is not available.");let Z=await W.list({sessionId:J});return u(f,{sessionId:J,prompts:Z})}async function BK($,f){let J=S0(f),W=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=typeof f.payload?.prompt==="string"?f.payload.prompt:void 0,Q=f.payload?.delivery==="queue"||f.payload?.delivery==="steer"?f.payload.delivery:void 0,j=$.sessionHost.pendingPrompts;if(!j)return m(f,"pending_prompts_unavailable","Pending prompt service is not available.");let H=await j.update({sessionId:J,promptId:W,prompt:Z,delivery:Q});return u(f,H)}async function KK($,f){let J=S0(f),W=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=$.sessionHost.pendingPrompts;if(!Z)return m(f,"pending_prompts_unavailable","Pending prompt service is not available.");let Q=await Z.delete({sessionId:J,promptId:W});return u(f,Q)}function GK($){switch($){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var DS=new Set(["skills","workflows","rules","tools","mcp"]);function k7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function H4($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${f}' must be a string.`);return J}function LS($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${f}' must be a boolean.`);return J}function PK($){if($===void 0)return{};if(!k7($))throw Error("settings.list payload must be an object.");return{cwd:H4($,"cwd"),workspaceRoot:H4($,"workspaceRoot"),availabilityContext:k7($.availabilityContext)?$.availabilityContext:void 0}}function OS($){if(!k7($))throw Error("settings.toggle payload must be an object.");let{type:f}=$;if(typeof f!=="string"||!DS.has(f))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...PK($),type:f,id:H4($,"id"),path:H4($,"path"),name:H4($,"name"),enabled:LS($,"enabled")}}class u2{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=RS("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new U$({sessionService:new F$(new G$),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(f)=>this.publish(f),buildEvent:Lf,requestCapability:(f,J,W,Z,Q)=>gB(this.ctx,f,J,W,Z,Q)},this.schedules=new qf({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(f,J)=>{let W=f==="schedule.execution.completed"?"schedule.execution_completed":f==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!W)return;this.publish(Lf(W,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new Tf(this.schedules),this.settings=$.settingsService??new U1,$.cronOptions)this.cronService=new gJ({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((f)=>{tB(this.ctx,f).catch((J)=>{h7("session event handling failed",J),YW(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:J,severity:"error",handled:!0,context:{eventType:f.type,sessionId:f.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())w7(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(z1(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let f=await this.dispatchCommand($);return this.captureFailedReply($,f),f}catch(f){throw YW(this.options.telemetry,{component:"core",operation:"hub.command",error:f,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),f}}async dispatchCommand($){switch($.command){case"client.register":return dB(this.ctx,$);case"client.update":return lB(this.ctx,$);case"client.unregister":return pB(this.ctx,$,(f)=>{this.listeners.delete(f),this.detachClientFromSessions(f)});case"client.list":return rB(this.ctx,$);case"session.create":return await JK(this.ctx,$,(f)=>q7(this.ctx,f));case"session.restore":return await WK(this.ctx,$,(f)=>q7(this.ctx,f));case"session.attach":return await ZK(this.ctx,$);case"session.detach":return await QK(this.ctx,$);case"session.get":return await jK(this.ctx,$);case"session.messages":return await HK(this.ctx,$);case"session.list":return await XK(this.ctx,$);case"session.update":return await YK(this.ctx,$);case"session.pending_prompts":return await VK(this.ctx,$);case"session.update_pending_prompt":return await BK(this.ctx,$);case"session.remove_pending_prompt":return await KK(this.ctx,$);case"session.delete":return await AK(this.ctx,$);case"session.hook":return await aB(this.ctx,$);case"run.start":case"session.send_input":return await iB(this.ctx,$);case"run.abort":return await nB(this.ctx,$);case"capability.request":return await uB(this.ctx,$);case"approval.respond":return await xB(this.ctx,$);case"capability.respond":return cB(this.ctx,$);case"capability.progress":return vB(this.ctx,$);case"ui.notify":return this.publish(Lf("ui.notify",$.payload??{})),u($);case"ui.show_window":return this.publish(Lf("ui.show_window",$.payload??{})),u($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let f=await this.scheduleCommands.handleCommand($);if(f.ok){let J=GK($.command);if(J)this.publish(Lf(J,f.payload))}return f}}}captureFailedReply($,f){if(f.ok||!f.error||!_S(f.error.code))return;YW(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(f.error.message),severity:f.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:f.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let f=await this.settings.list(PK($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:f instanceof Error?f.message:String(f)}}}}async handleSettingsToggle($){try{let f=await this.settings.toggle(OS($.payload));return this.publish(Lf("settings.changed",{types:f.changedTypes,snapshot:f.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f.snapshot,changedTypes:f.changedTypes}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:f instanceof Error?f.message:String(f)}}}}subscribe($,f,J){let W=this.listeners.get($)??new Set,Z={sessionId:J?.sessionId,listener:f};return W.add(Z),this.listeners.set($,W),()=>{let Q=this.listeners.get($);if(!Q)return;if(Q.delete(Z),Q.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[f,J]of this.sessionState.entries())if(J.participants.delete($),J.participants.size===0)this.sessionState.delete(f);z1(this.ctx,(f)=>f.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let f of this.listeners.values())for(let J of f){if(J.sessionId&&J.sessionId!==$.sessionId)continue;try{J.listener($)}catch(W){h7(`listener threw while publishing ${$.event}`,W),YW(this.options.telemetry,{component:"core",operation:"hub.publish",error:W,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function _S($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as MS}from"node:crypto";import yS from"node:http";import qS from"node:net";import{URL as RK}from"node:url";import{WebSocketServer as wS}from"ws";import{captureSdkError as FK,HUB_COMMAND_SLOW_LOG_MS as zS,resolveHubCommandTimeoutMs as TS,safeJsonParse as NS}from"@cline/shared";function I7($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function UK($,f,J){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:f,message:J}}}class J4{transport;telemetry;constructor($,f){this.transport=$;this.telemetry=f}attach($){let f=new Map,J=new Set,W=!1,Z=(X)=>{try{$.send(JSON.stringify(X))}catch(Y){console.error(`[hub] failed to send websocket frame: ${Y instanceof Error?Y.stack||Y.message:String(Y)}`)}},Q=(X)=>{Z({kind:"event",envelope:X})},j=async(X)=>{try{let Y=JSON.parse(X.data);switch(Y.kind){case"command":{let A=performance.now(),V=!1,B=I7(Y);g("info","command.start",B);let K=setTimeout(()=>{if(V)return;g("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-A)})},zS),G=this.transport.command(Y.envelope);G.then((z)=>{if(!V)return;g(z.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-A),ok:z.ok,errorCode:z.error?.code,errorMessage:z.error?.message})},(z)=>{if(!V)return;g("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-A),error:z})});let R=!1,P,F,U=TS(Y.envelope.command,Y.envelope.timeoutMs);try{F=U===null?await G:await Promise.race([G,new Promise((z)=>{P=setTimeout(()=>{R=!0,FK(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${Y.envelope.command} did not complete within ${U}ms.`),severity:"error",handled:!0,context:{...B,timeoutMs:U}}),z(UK(Y,"hub_command_timeout",`Hub command ${Y.envelope.command} did not complete within ${U}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${Y.envelope.requestId}.`))},U)})])}catch(z){if(clearTimeout(K),P)clearTimeout(P);throw z}if(V=R,clearTimeout(K),P)clearTimeout(P);let _=Math.round(performance.now()-A);if(R)g("error","command.timeout",{...B,durationMs:_,timeoutMs:U});else g(F.ok?"info":"warn","command.end",{...B,durationMs:_,ok:F.ok,errorCode:F.error?.code,errorMessage:F.error?.message});if(Y.envelope.command==="client.register"&&F.ok){let D=(Y.envelope.payload??{}).clientId?.trim()||Y.envelope.clientId?.trim();if(D)J.add(D)}else if(Y.envelope.command==="client.unregister"&&F.ok){let z=Y.envelope.clientId?.trim();if(z)J.delete(z)}Z({kind:"reply",envelope:F});break}case"stream.subscribe":{let A=`${Y.clientId}:${Y.sessionId??"*"}`;if(f.has(A))break;let V=await this.transport.subscribe(Y.clientId,Q,{sessionId:Y.sessionId});f.set(A,V);break}case"stream.unsubscribe":{let A=`${Y.clientId}:${Y.sessionId??"*"}`;f.get(A)?.(),f.delete(A);break}case"reply":case"event":break}}catch(Y){let A=typeof X.data==="string"?NS(X.data):void 0;if(!A||A.kind!=="command"){g("error","rejected malformed websocket frame",{error:Y});return}g("error","command.error",{...I7(A),error:Y}),FK(this.telemetry,{component:"core",operation:"hub.websocket_command",error:Y,severity:"error",handled:!0,context:I7(A)}),Z({kind:"reply",envelope:UK(A,"command_failed",Y instanceof Error?Y.message:"Unknown hub error")})}},H=()=>{if(W)return;W=!0;for(let X of f.values())X();f.clear();for(let X of J)this.transport.command({version:"v1",command:"client.unregister",clientId:X});J.clear(),$.removeEventListener("message",j),$.removeEventListener("close",H)};return $.addEventListener("message",j),$.addEventListener("close",H),H}}class W4{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,f,J){return this.transport.subscribe($,f,J)}}function SS($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();return String($)}function hS($){return{send(f){$.send(f)},addEventListener(f,J){if(f==="message"){$.on("message",(W)=>{J({data:SS(W)})});return}$.on("close",J)},removeEventListener(){}}}function CS($){try{$.write(`HTTP/1.1 400 Bad Request\r
|
|
711
711
|
Connection: close\r
|
|
712
712
|
Content-Length: 0\r
|
|
713
713
|
\r
|
|
714
|
-
`),$.end()}catch{$.destroy()}}function
|
|
714
|
+
`),$.end()}catch{$.destroy()}}function ES($){try{$.write(`HTTP/1.1 401 Unauthorized\r
|
|
715
715
|
Connection: close\r
|
|
716
716
|
Content-Length: 0\r
|
|
717
717
|
\r
|
|
718
|
-
`),$.end()}catch{$.destroy()}}function
|
|
719
|
-
Caused by: ${$.stack}`;return
|
|
718
|
+
`),$.end()}catch{$.destroy()}}function DK($,f){if(!$||!f)return!1;let J=Buffer.from($,"utf8"),W=Buffer.from(f,"utf8");return J.length===W.length&&MS(J,W)}function LK($,f){let J=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,W=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",Z=`Failed to start hub server on ${f.host}:${f.port}${f.pathname}: ${W}`,Q=Error(J?`${Z} (${J})`:Z);if(J)$.code=J,Q.code=J;if($ instanceof Error&&$.stack)Q.stack=`${Q.name}: ${Q.message}
|
|
719
|
+
Caused by: ${$.stack}`;return Q}async function bS($){return await new Promise((f,J)=>{let W=qS.createServer();W.once("error",J),W.listen(0,$,()=>{let Z=W.address();if(!Z||typeof Z==="string"){W.close(()=>J(Error("Failed to resolve free port")));return}let Q=Z.port;W.close((j)=>{if(j){J(j);return}f(Q)})})})}function kS($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var x7=new Map,OK="cline-hub-auth.",IS=30000;function _K($){return Array.isArray($)?$.join(","):$??""}function xS($){let f=_K($).trim();return/^Bearer\s+(.+)$/i.exec(f)?.[1]?.trim()||null}function mS($){for(let f of _K($).split(",")){let J=f.trim();if(J.startsWith(OK))return J.slice(OK.length).trim()||null}return null}async function Z4($){let f=$.owner??q$(),J=$.host??"127.0.0.1",W=$.pathname??"/hub",Z=$.port??Ef(),Q=Z===0?await bS(J):Z,j=Q,H=t0(J,Q,W),X=t$(),Y=g4(),A=new u2($);await A.start();let V=new J4(new W4(A),$.telemetry),B=new Set,K=new Date().toISOString(),G={protocolVersion:"v1",coreVersion:Y8.version,buildId:X,pid:process.pid,startedAt:K},R=new Set,P,F,U=async()=>{if(F)return F;return F=(async()=>{if(P)clearInterval(P),P=void 0;for(let O of R)O.terminate?.();R.clear();for(let O of B)O();if(B.clear(),await new Promise((O,N)=>{z.close((q)=>{if(q){N(q);return}O()})}),await new Promise((O,N)=>{_.close((q)=>{if(q){N(q);return}O()})}),await A.stop(),(await V0(f.discoveryPath))?.url===H)await b0(f.discoveryPath)})(),F},_=yS.createServer((D,O)=>{if((D.url??"/")==="/health"){let q=JSON.stringify({hubId:A.getHubId(),...G,authToken:"",host:J,port:j,url:H,updatedAt:new Date().toISOString()});O.statusCode=200,O.setHeader("content-type","application/json"),O.end(q);return}if((D.url??"/")==="/version"){O.statusCode=200,O.setHeader("content-type","application/json"),O.end(JSON.stringify(G));return}if(new RK(D.url??"/",`http://${J}:${j}`).pathname==="/shutdown"&&D.method==="POST"){if(!DK(xS(D.headers.authorization),Y)){O.statusCode=401,O.end("Unauthorized");return}O.statusCode=202,O.setHeader("content-type","application/json"),O.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{U()});return}O.statusCode=404,O.end("Not found")}),z=new wS({noServer:!0});P=setInterval(()=>{for(let D of R){if(D.isAlive===!1){try{D.terminate?.()}catch{}R.delete(D);continue}D.isAlive=!1;try{D.ping?.()}catch{try{D.terminate?.()}catch{}R.delete(D)}}},IS),_.on("upgrade",(D,O,N)=>{if(new RK(D.url??"/",`http://${J}:${j}`).pathname!==W){O.destroy();return}if(!DK(mS(D.headers["sec-websocket-protocol"]),Y)){ES(O);return}try{z.handleUpgrade(D,O,N,($0)=>{let Y0=$0;Y0.isAlive=!0,Y0.on("pong",()=>{Y0.isAlive=!0}),R.add(Y0);let o=V.attach(hS($0));B.add(o),$0.once("close",()=>{R.delete(Y0),o(),B.delete(o)})})}catch{CS(O)}});try{await new Promise((D,O)=>{_.once("error",(N)=>{O(LK(N,{host:J,port:Q,pathname:W}))}),_.listen(Q,J,()=>{let N=_.address();if(!N||typeof N==="string"){O(LK(Error("Failed to resolve hub port"),{host:J,port:Q,pathname:W}));return}j=N.port,H=t0(J,j,W),D()})})}catch(D){if(P)clearInterval(P),P=void 0;throw await A.stop().catch(()=>{return}),D}return await v4(f.discoveryPath,{hubId:A.getHubId(),protocolVersion:"v1",coreVersion:Y8.version,buildId:X,authToken:Y,host:J,port:j,url:H,pid:process.pid,startedAt:K,updatedAt:K}),{host:J,port:j,url:H,authToken:Y,close:U}}async function WW($){let f=$.owner??q$(),J=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=$.host??"127.0.0.1",Z=$.port??Ef(),Q=$.pathname??"/hub",j=t0(W,Z,Q),H=f.discoveryPath,X=(A)=>{if(!J)s$(A.url,A.authToken);return A},Y=x7.get(H);if(Y){let A=await Y;if(A.url===j)return X({server:A,url:A.url,authToken:A.authToken,action:"reuse"})}return await u4(f.discoveryPath,async()=>{let A=await V0(f.discoveryPath);if(A?.url&&(A.url===j||$.allowPortFallback===!0)){let G=await Q$(A.url);if(G?.url&&await H$(G.url,{authToken:A.authToken}))return X({url:G.url,authToken:A.authToken,action:"reuse"})}if((await Q$(j))?.url||A?.url)await b0(f.discoveryPath);let K=async(G)=>{let R=Z4({...G,owner:f});x7.set(H,R);try{let P=await R;return X({server:P,url:P.url,authToken:P.authToken,action:"started"})}catch(P){throw x7.delete(H),P}};try{return await K($)}catch(G){if(!$.allowPortFallback||!kS(G))throw G;return await K({...$,port:0})}})}async function TB($){let f=j$({host:$.host,port:$.port,pathname:$.pathname});return await Z4({...$,...f,owner:G0()})}async function NB($){let f=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=j$({host:$.host,port:$.port,pathname:$.pathname});return await WW({...$,...J,allowPortFallback:$.allowPortFallback??!f,owner:G0()})}export{v4 as writeHubDiscovery,u4 as withHubStartupLock,H$ as verifyHubConnection,f4 as truncateNotificationBody,CW as toHubHealthUrl,lW as stopLocalHubServerGracefully,Z4 as startHubWebSocketServer,TB as startHubServer,bf as spawnDetachedHubServerWithRetry,mW as spawnDetachedHubServer,r3 as sendHubCommand,l4 as restartLocalHubIfIdleAfterStartupTimeout,b3 as resolveWorkspaceHubOwnerContext,G0 as resolveSharedHubOwnerContext,pW as resolveHubUrl,q$ as resolveHubOwnerContext,j$ as resolveHubEndpointOptions,t$ as resolveHubBuildId,Ef as resolveDefaultHubPort,xW as resolveDefaultHubPathname,IW as resolveDefaultHubHost,G8 as resolveCompatibleLocalHubUrl,S3 as resolveClineDir,A8 as resolveClineDataDir,K8 as requestHubShutdown,s$ as rememberRecoverableLocalHubUrl,V0 as readHubDiscovery,Q$ as probeHubServer,p3 as probeHubConnection,c4 as prewarmDetachedHubServer,o$ as normalizeHubWebSocketUrl,cW as isHubReconnectableTransportError,d4 as isHubCommandTimeoutError,C3 as isDiscoveryFilePresent,WW as ensureHubWebSocketServer,NB as ensureHubServer,I3 as ensureDetachedHubServer,b1 as ensureCompatibleLocalHubUrl,zB as createLocalHubScheduleRuntimeHandlers,h3 as createInMemoryHubOwnerContext,t0 as createHubServerUrl,g4 as createHubAuthToken,N$ as createConfiguredTelemetryService,Cf as createConfiguredTelemetryHandle,p4 as connectToHub,b0 as clearHubDiscovery,s0 as NodeHubClient,W4 as NativeHubTransportAdapter,nW as HubUIClient,O0 as HubTransportError,iW as HubSessionClient,u2 as HubServerTransport,qf as HubScheduleService,Tf as HubScheduleCommandService,kf as HubCommandError,bW as DEFAULT_HUB_PORT,kW as DEFAULT_HUB_PATHNAME,EW as DEFAULT_HUB_HOST,J4 as BrowserWebSocketHubAdapter};
|