@cline/core 0.0.38 → 0.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/ClineCore.d.ts +4 -3
- package/dist/auth/cline.d.ts +1 -1
- package/dist/extensions/plugin-sandbox-bootstrap.js +1 -1
- package/dist/extensions/tools/team/spawn-agent-tool.d.ts +1 -0
- package/dist/hub/daemon/entry.js +145 -145
- package/dist/hub/daemon/index.d.ts +1 -0
- package/dist/hub/index.js +162 -162
- package/dist/hub/runtime-host/hub-runtime-host.d.ts +2 -2
- package/dist/hub/server/hub-session-records.d.ts +2 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.js +162 -162
- package/dist/remote-config/integration.d.ts +17 -0
- package/dist/runtime/host/local/agent-event-bridge.d.ts +1 -0
- package/dist/runtime/host/local-runtime-host.d.ts +6 -2
- package/dist/runtime/host/runtime-host.d.ts +5 -1
- package/dist/services/agent-events.d.ts +1 -0
- package/dist/services/llms/provider-settings.d.ts +15 -15
- package/dist/services/usage.d.ts +1 -0
- package/dist/session/models/session-manifest.d.ts +2 -2
- package/dist/session/session-snapshot.d.ts +2 -0
- package/dist/types/chat-schema.d.ts +12 -12
- package/dist/types/session.d.ts +3 -0
- package/dist/types/sessions.d.ts +10 -0
- package/dist/types.d.ts +1 -1
- package/package.json +4 -8
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`)}function
|
|
3
|
-
`,"utf8")}function fJ(){return of().telemetryOptOut}function WA(f,$={}){E$({...of(),telemetryOptOut:f},$)}function cf(f){return new Set(f??of().disabledTools??[])}function X8(f){return new Set(f??of().disabledPlugins??[])}function QA(f){return cf().has(f)}function $J(f){let $=cf(),J=of();if($.has(f))return $.delete(f),E$({...J,disabledTools:[...$]}),!1;return $.add(f),E$({...J,disabledTools:[...$]}),!0}function x3(f,$){let J=[...new Set(f.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let H=of(),W=cf(H.disabledTools);for(let Q of J)if($)W.add(Q);else W.delete(Q);E$({...H,disabledTools:[...W]})}function g3(f,$){return x3([f],$),$}function ZA(f){return X8().has(f)}function jA(f,$){let J=f.trim();if(!J)return;let H=of(),W=X8(H.disabledPlugins);if($)W.add(J);else W.delete(J);E$({...H,disabledPlugins:[...W]})}function JJ(f,$){let J=X8($);if(J.size===0)return[...f];return f.filter((H)=>!J.has(H))}function S$(f,$){let J=cf($);if(J.size===0)return[...f];return f.filter((H)=>!J.has(H.name))}function HJ(f,$){if(!f||f.length===0)return f;let J=cf($);if(J.size===0)return f;return f.map((H)=>{if(!H.setup)return H;return{...H,setup:(W,Q)=>H.setup?.({...W,registerTool:(Z)=>{if(!J.has(Z.name))W.registerTool(Z)}},Q)}})}var k3,P8;var ef=G$(()=>{Af();k3=U1.preprocess((f)=>Array.isArray(f)?f.filter(($)=>typeof $==="string").map(($)=>$.trim()).filter(Boolean):void 0,U1.array(U1.string()).optional()).transform((f)=>{if(!f)return;let $=[...new Set(f)].sort((J,H)=>J.localeCompare(H));return $.length>0?$:void 0}),P8=U1.object({telemetryOptOut:U1.boolean().default(!1).catch(!1),disabledTools:k3.optional(),disabledPlugins:k3.optional()}).strip().transform((f)=>{let $={telemetryOptOut:f.telemetryOptOut};if(f.disabledTools?.length)$.disabledTools=f.disabledTools;if(f.disabledPlugins?.length)$.disabledPlugins=f.disabledPlugins;return $})});import{existsSync as DK,mkdirSync as MK,readFileSync as _K,writeFileSync as LK}from"node:fs";import{resolve as zK}from"node:path";import{resolveSessionDataDir as OK}from"@cline/shared/storage";import{nanoid as NK}from"nanoid";import*as qK from"node-machine-id";function j$(f){let $=f?.trim();if($)return $;let J=CK();if(J)return J;return EK()}function wK(){let f=qK;return f.machineIdSync??f.default?.machineIdSync}function CK(){try{let f=wK();if(!f)return;return f().trim()||void 0}catch{return}}function EK(){let f=OK(),$=zK(f,bK);try{if(DK($)){let H=_K($,"utf8").trim();if(H.length>0)return H}}catch{}let J=`cl-${NK()}`;try{MK(f,{recursive:!0}),LK($,J,"utf8")}catch{}return J}var bK="machine-id";var C8=()=>{};class $2{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(f){this.name=f.name??"OpenTelemetryAdapter",this.metadata={...f.metadata},this.meterProvider=f.meterProvider,this.loggerProvider=f.loggerProvider,this.meter=f.meterProvider?.getMeter("cline")??null,this.logger=f.loggerProvider?.getLogger("cline")??null,this.enabled=f.enabled??!0,this.distinctId=f.distinctId,this.commonProperties=f.commonProperties?{...f.commonProperties}:{}}emit(f,$){if(!this.isEnabled())return;this.emitLog(f,$,!1)}emitRequired(f,$){this.emitLog(f,$,!0)}recordCounter(f,$,J,H,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let Q=this.counters.get(f);if(!Q)Q=this.meter.createCounter(f,H?{description:H}:void 0),this.counters.set(f,Q);Q.add($,this.flattenProperties(this.buildAttributes(J)))}recordHistogram(f,$,J,H,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let Q=this.histograms.get(f);if(!Q)Q=this.meter.createHistogram(f,H?{description:H}:void 0),this.histograms.set(f,Q);Q.record($,this.flattenProperties(this.buildAttributes(J)))}recordGauge(f,$,J,H,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let Q=this.buildAttributes(J),Z=JSON.stringify(Q),j=this.gaugeValues.get(f);if($===null){if(j){if(j.delete(Z),j.size===0)this.gaugeValues.delete(f),this.gauges.delete(f)}return}let P=j;if(!P)P=new Map,this.gaugeValues.set(f,P);if(!this.gauges.has(f)){let X=this.meter.createObservableGauge(f,H?{description:H}:void 0);X.addCallback((V)=>{for(let Y of this.snapshotGaugeSeries(f))V.observe(Y.value,this.flattenProperties(Y.attributes))}),this.gauges.set(f,X)}P.set(Z,{value:$,attributes:Q})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(f){this.distinctId=f}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(f,$,J){if(!this.logger)return;let H=this.flattenProperties(this.buildAttributes($,J));this.logger.emit({severityText:"INFO",body:f,attributes:H})}buildAttributes(f,$=!1){return{...this.commonProperties,...this.metadata,...f,...this.distinctId?{distinct_id:this.distinctId}:{},...$?{_required:!0}:{}}}snapshotGaugeSeries(f){let $=this.gaugeValues.get(f);if(!$)return[];return Array.from($.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties(f,$="",J=new WeakSet,H=0){if(!f)return{};let W={},Q=100,Z=10;for(let[j,P]of Object.entries(f)){if(j==="__proto__"||j==="constructor"||j==="prototype")continue;let X=$?`${$}.${j}`:j;if(P===null||P===void 0){W[X]=String(P);continue}if(Array.isArray(P)){let V=P.length>Q?P.slice(0,Q):P;try{W[X]=JSON.stringify(V)}catch{W[X]="[UnserializableArray]"}if(P.length>Q)W[`${X}_truncated`]=!0,W[`${X}_original_length`]=P.length;continue}if(typeof P==="object"){if(P instanceof Date){W[X]=P.toISOString();continue}if(P instanceof Error){W[X]=P.message;continue}if(J.has(P)){W[X]="[Circular]";continue}if(H>=Z){W[X]="[MaxDepthExceeded]";continue}J.add(P),Object.assign(W,this.flattenProperties(P,X,J,H+1));continue}if(iT(P)){W[X]=P;continue}try{W[X]=JSON.stringify(P)}catch{W[X]=String(P)}}return W}}function iT(f){return typeof f==="string"||typeof f==="number"||typeof f==="boolean"}class y4{name;logger;enabled;constructor(f={}){this.name=f.name??"TelemetryLoggerSink",this.logger=f.logger,this.enabled=f.enabled??!0}emit(f,$){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:f,properties:$})}emitRequired(f,$){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:f,properties:$})}recordCounter(f,$,J,H,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:f,value:$,attributes:J,description:H,required:W===!0})}recordHistogram(f,$,J,H,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:f,value:$,attributes:J,description:H,required:W===!0})}recordGauge(f,$,J,H,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:f,value:$,attributes:J,description:H,required:W===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class J2{adapters;metadata;distinctId;commonProperties;constructor(f={}){if(this.adapters=[...f.adapters??[]],f.logger)this.adapters.push(new y4({logger:f.logger}));this.metadata={...f.metadata??{}},this.distinctId=f.distinctId,this.commonProperties={...f.commonProperties??{}}}addAdapter(f){this.adapters.push(f)}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return this.adapters.some((f)=>f.isEnabled())}capture(f){let $=this.buildAttributes(f.properties);for(let J of this.adapters)J.emit(f.event,$)}captureRequired(f,$){let J=this.buildAttributes($);for(let H of this.adapters)H.emitRequired(f,J)}recordCounter(f,$,J,H,W=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordCounter(f,$,Q,H,W)}recordHistogram(f,$,J,H,W=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordHistogram(f,$,Q,H,W)}recordGauge(f,$,J,H,W=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordGauge(f,$,Q,H,W)}async flush(){await Promise.all(this.adapters.map((f)=>f.flush()))}async dispose(){await Promise.all(this.adapters.map((f)=>f.dispose()))}buildAttributes(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var KW=()=>{};import{metrics as nT,trace as aT}from"@opentelemetry/api";import{logs as tT}from"@opentelemetry/api-logs";import{OTLPLogExporter as sT}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as oT}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as eT}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as fD}from"@opentelemetry/resources";import{BatchLogRecordProcessor as $D,ConsoleLogRecordExporter as JD,LoggerProvider as HD}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as WD,MeterProvider as QD,PeriodicExportingMetricReader as _j}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as ZD,ConsoleSpanExporter as jD,SimpleSpanProcessor as PD}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as XD}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as VD,ATTR_SERVICE_VERSION as YD}from"@opentelemetry/semantic-conventions";class Lj{distinctId;metadata;commonProperties;constructor(f={}){this.distinctId=f.distinctId,this.metadata={...f.metadata??{}},this.commonProperties={...f.commonProperties??{}}}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return!1}capture(f){this.resolveProperties(f.properties)}captureRequired(f,$){this.resolveProperties($)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class H2{meterProvider;loggerProvider;tracerProvider;options;constructor(f={}){this.options=f;let $=fD({[VD]:f.serviceName??"cline",...f.serviceVersion?{[YD]:f.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)nT.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)tT.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(f="cline",$){return aT.getTracer(f,$??this.options.serviceVersion)}createAdapter(f){return new $2({...f,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(f){let $=this.createAdapter({name:f.name,enabled:this.options.enabled,metadata:f.metadata});return new J2({...f,adapters:[$],distinctId:j$(f.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(f){let $=UW(this.options.metricsExporter);if($.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),H=Math.min(30000,Math.floor(J*0.8)),W=$.map((Q)=>RD(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:H})).filter((Q)=>Q!==null);if(W.length===0)return null;return new QD({resource:f,readers:W})}createTracerProvider(f){let $=UW(this.options.tracesExporter);if($.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,H=this.options.otlpTracesHeaders??this.options.otlpHeaders,W=[];for(let Q of $){let Z=AD(Q,{endpoint:J,headers:H,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(Z)W.push(Z)}if(W.length===0)return null;return new XD({resource:f,spanProcessors:W})}createLoggerProvider(f){let $=UW(this.options.logsExporter);if($.length===0)return null;let J=$.map((H)=>{let W=BD(H,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!W)return null;return new $D(W,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((H)=>H!==null);if(J.length===0)return null;return new HD({resource:f,processors:J})}}function K4(f){let $=new H2(f),J=$.createTelemetryService(f);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:f.enabled??!0,logsExporter:Array.isArray(f.logsExporter)?f.logsExporter.join(","):f.logsExporter,metricsExporter:Array.isArray(f.metricsExporter)?f.metricsExporter.join(","):f.metricsExporter,tracesExporter:Array.isArray(f.tracesExporter)?f.tracesExporter.join(","):f.tracesExporter,otlpProtocol:f.otlpProtocol,hasOtlpEndpoint:Boolean(f.otlpEndpoint),serviceName:f.serviceName,serviceVersion:f.serviceVersion}),{provider:$,telemetry:J}}function W2(f){if(fJ())return{telemetry:new Lj(f)};if(f.enabled!==!0)return{telemetry:new J2({...f,distinctId:j$(f.distinctId)})};return K4(f)}function U4(f){let{telemetry:$,provider:J}=W2(f);return{telemetry:$,provider:J,flush:async()=>{let Q=J;if(Q&&typeof Q.forceFlush==="function")try{await Q.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([$.dispose(),J?.dispose()])}}}function UW(f){if(!f)return[];return(Array.isArray(f)?f:f.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function BD(f,$){if(f==="console")return new JD;if(!$.endpoint)return null;let J=GW($.endpoint,"/v1/logs");return new sT({url:J,headers:$.headers})}function AD(f,$){if(f==="console")return new PD(new jD);if(!$.endpoint)return null;let J=GW($.endpoint,"/v1/traces");return new ZD(new eT({url:J,headers:$.headers}))}function RD(f,$){if(f==="console")return new _j({exporter:new WD,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let J=GW($.endpoint,"/v1/metrics");return new _j({exporter:new oT({url:J,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function GW(f,$){let J=new URL(f),H=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=H.endsWith($)?H:`${H}${$}`,J.toString()}var G4=G$(()=>{ef();C8();KW()});var gP={};dW(gP,{createOpenTelemetryTelemetryService:()=>K4,createConfiguredTelemetryService:()=>W2,createConfiguredTelemetryHandle:()=>U4,OpenTelemetryProvider:()=>H2,OpenTelemetryAdapter:()=>$2});var vP=G$(()=>{G4()});import*as Xv from"@cline/llms";import{buildClineSystemPrompt as Yv,ContributionRegistry as Bv,createClineTelemetryServiceConfig as Av,createClineTelemetryServiceMetadata as Rv,createContributionRegistry as Fv,createTool as yv,emptyWorkspaceManifest as Kv,formatDisplayUserInput as Uv,noopBasicLogger as Gv,normalizeUserInput as hv,parseUserCommandEnvelope as Tv,registerDisposable as Dv}from"@cline/shared";export*from"@cline/shared/storage";function pP(f){if(typeof f!=="object"||f===null||!("error"in f))return;let $=f.error;return typeof $==="string"&&$.trim()?$:void 0}function lW(f,$,J){let H=pP(J);if(H)return H;let W=$.trim();if(W){let Q=W.length>200?`${W.slice(0,200)}...`:W;return`Cline account request failed with status ${f}: ${Q}`}return`Cline account request failed with status ${f}`}class O4{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor(f){let $=f.apiBaseUrl.trim();if(!$)throw Error("apiBaseUrl is required");this.apiBaseUrl=$,this.getAuthTokenFn=f.getAuthToken,this.getCurrentUserIdFn=f.getCurrentUserId,this.getOrganizationMemberIdFn=f.getOrganizationMemberId,this.getHeadersFn=f.getHeaders,this.requestTimeoutMs=f.requestTimeoutMs??30000,this.fetchImpl=f.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance(f){let $=await this.resolveUserId(f);return this.request(`/api/v1/users/${encodeURIComponent($)}/balance`)}async fetchUsageTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/usages`)).items??[]}async fetchPaymentTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}`)}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}/balance`)}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId($,f.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent($)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount(f){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:f?.trim()||null},expectNoContent:!0})}async resolveUserId(f){let $=f?.trim();if($)return $;let H=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(H)return H;let W=await this.fetchMe();if(!W.id?.trim())throw Error("Unable to resolve current user id");return W.id}async resolveOrganizationMemberId(f,$){let J=$?.trim();if(J)return J;let W=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn(f):void 0)?.trim();if(W)return W;let Z=(await this.fetchUserOrganizations()).find((j)=>j.organizationId===f)?.memberId;if(!Z?.trim())throw Error(`Unable to resolve memberId for organization ${f}`);return Z}async request(f,$){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let H=this.getHeadersFn?await this.getHeadersFn():{},W=new AbortController,Q=setTimeout(()=>W.abort(),this.requestTimeoutMs);try{let Z=await this.fetchImpl(new URL(f,this.apiBaseUrl),{method:$?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...H??{}},body:$?.body!==void 0?JSON.stringify($.body):void 0,signal:W.signal});if(Z.status===204||$?.expectNoContent){if(!Z.ok)throw Error(`Cline account request failed with status ${Z.status}`);return}let j=await Z.text(),P;if(j.trim())try{P=JSON.parse(j)}catch{if(!Z.ok)throw Error(lW(Z.status,j,void 0));throw Error("Cline account response was not valid JSON")}if(!Z.ok)throw Error(lW(Z.status,j,P));if(typeof P==="object"&&P!==null){let X=P;if(typeof X.success==="boolean"){if(!X.success)throw Error(X.error||"Cline account request failed");if(X.data!==void 0)return X.data}}if(P===void 0||P===null)throw Error("Cline account response payload was empty");return P}finally{clearTimeout(Q)}}}function pW(f){return f.action==="clineAccount"}async function iW(f,$){switch(f.operation){case"fetchMe":return $.fetchMe();case"fetchBalance":return $.fetchBalance(f.userId);case"fetchUsageTransactions":return $.fetchUsageTransactions(f.userId);case"fetchPaymentTransactions":return $.fetchPaymentTransactions(f.userId);case"fetchUserOrganizations":return $.fetchUserOrganizations();case"fetchOrganizationBalance":return $.fetchOrganizationBalance(f.organizationId);case"fetchOrganizationUsageTransactions":return $.fetchOrganizationUsageTransactions({organizationId:f.organizationId,memberId:f.memberId});case"switchAccount":return await $.switchAccount(f.organizationId),{updated:!0};case"fetchFeaturebaseToken":return $.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String(f)}`)}}class N4{executor;constructor(f){this.executor=f}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance(f){return this.request({action:"clineAccount",operation:"fetchBalance",...f?.trim()?{userId:f.trim()}:{}})}async fetchUsageTransactions(f){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchPaymentTransactions(f){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:$})}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:$,...f.memberId?.trim()?{memberId:f.memberId.trim()}:{}})}async switchAccount(f){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:f?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request(f){return(await this.executor.runProviderAction(f)).result}}function q4(f){return{onAuth:({url:$,instructions:J})=>{if(f.onOutput?.(J??"Complete sign-in in your browser."),f.openUrl)try{Promise.resolve(f.openUrl($)).catch((H)=>{f.onOpenUrlError?.({url:$,error:H})})}catch(H){f.onOpenUrlError?.({url:$,error:H})}f.onOutput?.($)},onPrompt:f.onPrompt,onServerListening:f.onServerListening,onServerClose:f.onServerClose}}Af();function sP(){let f;return{promise:new Promise((J)=>{f=J}),resolve:f}}async function g0(f){let $=await import("node:http"),J=f.host??"127.0.0.1",H=f.timeoutMs??300000,W=f.successHtml??oP,Q=sP(),Z=!1,j=null,P=null,X=null,V=(A)=>{if(Z)return;Z=!0,Q.resolve(A)},Y=()=>{if(j)clearTimeout(j),j=null;let A=X;if(X=null,P)P.close(),P=null;if(A!==null&&f.onClose)Promise.resolve(f.onClose({host:J,port:A})).catch(()=>{})},B=async()=>{return j=setTimeout(()=>{Y(),V(null)},H),Q.promise};for(let A of f.ports){let R=$.createServer((y,F)=>{try{let K=new URL(y.url||"",`http://${J}:${A}`);if(K.pathname!==f.callbackPath){F.statusCode=404,F.end("Not found");return}let M={url:K,code:K.searchParams.get("code")??void 0,state:K.searchParams.get("state")??void 0,provider:K.searchParams.get("provider")??void 0,error:K.searchParams.get("error")??void 0};if(M.error){F.statusCode=400,F.end(`Authentication failed: ${M.error}`),Y(),V(M);return}if(!M.code){F.statusCode=400,F.end("Missing authorization code");return}if(f.expectedState&&M.state!==f.expectedState){F.statusCode=400,F.end("State mismatch");return}F.statusCode=200,F.setHeader("Content-Type","text/html; charset=utf-8"),F.end(W),Y(),V(M)}catch{F.statusCode=500,F.end("Internal error")}}),U=await new Promise((y)=>{let F=(K)=>{R.off("error",F),y({bound:!1,error:K})};R.once("error",F),R.listen(A,J,()=>{R.off("error",F),P=R,y({bound:!0})})});if(U.error){if(U.error.code==="EADDRINUSE")continue;throw Y(),U.error}if(U.bound){X=A;let y=`http://${J}:${A}${f.callbackPath}`;if(f.onListening)await Promise.resolve(f.onListening({host:J,port:A,callbackUrl:y})).catch(()=>{});return{callbackUrl:y,waitForCallback:B,cancelWait:()=>{Y(),V(null)},close:()=>{Y(),V(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var oP=`<!DOCTYPE html>
|
|
1
|
+
import{createRequire as oX}from"node:module";var aX=Object.defineProperty;var tX=(f)=>f;function sX(f,$){this[f]=tX.bind(null,$)}var JH=(f,$)=>{for(var J in $)aX(f,J,{get:$[J],enumerable:!0,configurable:!0,set:sX.bind($,J)})};var L$=(f,$)=>()=>(f&&($=f(f=0)),$);var WH=oX(import.meta.url);function c(f,$,J){f?.capture({event:$,properties:J})}function F2(f){if(!f)return;return f.substring(0,500)}function fA(f){if(typeof f==="string")return"Error";return f.name?.trim()||f.constructor?.name||"Error"}function $A(f){return typeof f==="string"?f:f.message}function jH(f,$){return f.some((J)=>$.has(J.trim().toLowerCase()))}function JA(f){c(f,x.CLIENT.EXTENSION_ACTIVATED)}function k4(f,$){let J=[...$.vcs_types],W={root_count:$.root_count,vcs_types:J,is_multi_root:$.root_count>1,has_git:jH(J,new Set(["git"])),has_mercurial:jH(J,new Set(["mercurial","hg"]))};if($.init_duration_ms!==void 0)W.init_duration_ms=$.init_duration_ms;if($.feature_flag_enabled!==void 0)W.feature_flag_enabled=$.feature_flag_enabled;if($.is_remote_workspace!==void 0)W.is_remote_workspace=$.is_remote_workspace;c(f,x.WORKSPACE.INITIALIZED,W)}function I4(f,$,J){c(f,x.WORKSPACE.INIT_ERROR,{error_type:fA($),error_message:F2($A($)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function WA(f,$){c(f,x.WORKSPACE.PATH_RESOLVED,{...$})}function V0(f,$){c(f,x.USER.AUTH_STARTED,{provider:$})}function R0(f,$){c(f,x.USER.AUTH_SUCCEEDED,{provider:$})}function F0(f,$,J){c(f,x.USER.AUTH_FAILED,{provider:$,errorMessage:F2(J)})}function c0(f,$,J){c(f,x.USER.AUTH_LOGGED_OUT,{provider:$,reason:J})}function XH(f,$){f?.captureRequired(x.USER.TELEMETRY_OPT_OUT,$)}function K0(f,$){let J=$.id?.trim();if(J)f?.setDistinctId(J);f?.updateCommonProperties({account_id:$.id,account_email:$.email,provider:$.provider,organization_id:$.organizationId,organization_name:$.organizationName,member_id:$.memberId})}function m4(f,$){c(f,x.TASK.CREATED,$)}function x4(f,$){c(f,x.TASK.RESTARTED,$)}function K2(f,$){c(f,x.TASK.COMPLETED,$)}function Q1(f,$){c(f,x.TASK.CONVERSATION_TURN,{...$,timestamp:new Date().toISOString()})}function g4(f,$){c(f,x.TASK.TOKEN_USAGE,$)}function v4(f,$,J){c(f,x.TASK.MODE_SWITCH,{ulid:$,mode:J})}function u4(f,$){c(f,x.TASK.TOOL_USED,$)}function c4(f,$){c(f,x.TASK.SKILL_USED,$)}function d4(f,$){c(f,x.TASK.DIFF_EDIT_FAILED,$)}function y2(f,$){c(f,x.TASK.PROVIDER_API_ERROR,{...$,errorMessage:F2($.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function r4(f,$,J){c(f,x.TASK.MENTION_USED,{mentionType:$,contentLength:J,timestamp:new Date().toISOString()})}function l4(f,$,J,W){c(f,x.TASK.MENTION_FAILED,{mentionType:$,errorType:J,errorMessage:F2(W),timestamp:new Date().toISOString()})}function p4(f,$,J,W,H){c(f,x.TASK.MENTION_SEARCH_RESULTS,{queryLength:$.length,resultCount:J,searchType:W,isEmpty:H,timestamp:new Date().toISOString()})}function d0(f,$){c(f,x.TASK.AGENT_CREATED,{...$,timestamp:new Date().toISOString()})}function i4(f,$){c(f,x.TASK.AGENT_TEAM_CREATED,{...$,timestamp:new Date().toISOString()})}function U2(f,$){c(f,$.event==="ended"?x.TASK.SUBAGENT_COMPLETED:x.TASK.SUBAGENT_STARTED,{...$,timestamp:new Date().toISOString()})}function n4(f,$,J,W){c(f,x.HOOKS.DISCOVERY_COMPLETED,{hookName:$,globalCount:J,workspaceCount:W,totalCount:J+W,timestamp:new Date().toISOString()})}var x;var Uf=L$(()=>{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",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"}}});var J3={};JH(J3,{normalizeUserMessage:()=>OY,buildInitialUserContent:()=>hY});async function hY(f,$,J,W){let H=zY($),Q=await qY(J,W);if(H.length===0&&!Q)return f;let Z=[{type:"text",text:f},...H];if(Q)Z.push(...Q);return Z}function OY(f){if(f==null)return"";if(typeof f==="string")return f;let $=f.content;if(typeof $==="string")return $;if(!Array.isArray($))return"";let J=[];for(let W of $)if(W&&typeof W==="object"&&W.type==="text"){let H=W.text;if(typeof H==="string")J.push(H)}return J.join(`
|
|
2
|
+
`)}function zY(f){if(!f||f.length===0)return[];let $=[];for(let J of f){let W=NY(J);if(W)$.push(W)}return $}function NY(f){let $=f.trim();if(!$)return;let J=$.match(/^data:([^;,]+);base64,(.+)$/);if(J){let W=J[1],H=J[2];if(!W||!H)return;return{type:"image",mediaType:W,data:H}}return{type:"image",mediaType:"image/png",data:$}}async function qY(f,$){if(!f||f.length===0)return;let J=$??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),W=await Promise.all(f.map(async(H)=>{let Q=H.replace(/\\/g,"/");try{let Z=await J(H);return{type:"file",path:Q,content:Z}}catch(Z){let j=Z instanceof Error?Z.message:String(Z);return{type:"file",path:Q,content:`Error fetching content: ${j}`}}}));if(W.length===0)return;return W}import{mkdirSync as yV,readFileSync as UV,writeFileSync as GV}from"node:fs";import{dirname as TV}from"node:path";import{resolveGlobalSettingsPath as c3}from"@cline/shared/storage";import{z as M1}from"zod";function u3(){return Y8.parse({})}function J0(){let f=c3(),$;try{$=JSON.parse(UV(f,"utf8"))}catch{return u3()}let J=Y8.safeParse($);return J.success?J.data:u3()}function x$(f,$={}){let J=c3(),W=J0();yV(TV(J),{recursive:!0});let H=Y8.parse(f);if(!W.telemetryOptOut&&H.telemetryOptOut)XH($.telemetry);GV(J,`${JSON.stringify(H,null,2)}
|
|
3
|
+
`,"utf8")}function jJ(){return J0().telemetryOptOut}function DV(f,$={}){x$({...J0(),telemetryOptOut:f},$)}function rf(f){return new Set(f??J0().disabledTools??[])}function V8(f){return new Set(f??J0().disabledPlugins??[])}function _V(f){return rf().has(f)}function XJ(f){let $=rf(),J=J0();if($.has(f))return $.delete(f),x$({...J,disabledTools:[...$]}),!1;return $.add(f),x$({...J,disabledTools:[...$]}),!0}function d3(f,$){let J=[...new Set(f.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let W=J0(),H=rf(W.disabledTools);for(let Q of J)if($)H.add(Q);else H.delete(Q);x$({...W,disabledTools:[...H]})}function r3(f,$){return d3([f],$),$}function MV(f){return V8().has(f)}function LV(f,$){let J=f.trim();if(!J)return;let W=J0(),H=V8(W.disabledPlugins);if($)H.add(J);else H.delete(J);x$({...W,disabledPlugins:[...H]})}function AJ(f,$){let J=V8($);if(J.size===0)return[...f];return f.filter((W)=>!J.has(W))}function g$(f,$){let J=rf($);if(J.size===0)return[...f];return f.filter((W)=>!J.has(W.name))}function PJ(f,$){if(!f||f.length===0)return f;let J=rf($);if(J.size===0)return f;return f.map((W)=>{if(!W.setup)return W;return{...W,setup:(H,Q)=>W.setup?.({...H,registerTool:(Z)=>{if(!J.has(Z.name))H.registerTool(Z)}},Q)}})}var v3,Y8;var W0=L$(()=>{Uf();v3=M1.preprocess((f)=>Array.isArray(f)?f.filter(($)=>typeof $==="string").map(($)=>$.trim()).filter(Boolean):void 0,M1.array(M1.string()).optional()).transform((f)=>{if(!f)return;let $=[...new Set(f)].sort((J,W)=>J.localeCompare(W));return $.length>0?$:void 0}),Y8=M1.object({telemetryOptOut:M1.boolean().default(!1).catch(!1),disabledTools:v3.optional(),disabledPlugins:v3.optional()}).strip().transform((f)=>{let $={telemetryOptOut:f.telemetryOptOut};if(f.disabledTools?.length)$.disabledTools=f.disabledTools;if(f.disabledPlugins?.length)$.disabledPlugins=f.disabledPlugins;return $})});import{existsSync as iy,mkdirSync as ny,readFileSync as ay,writeFileSync as ty}from"node:fs";import{resolve as sy}from"node:path";import{resolveSessionDataDir as oy}from"@cline/shared/storage";import{nanoid as ey}from"nanoid";import*as fU from"node-machine-id";function B$(f){let $=f?.trim();if($)return $;let J=WU();if(J)return J;return HU()}function JU(){let f=fU;return f.machineIdSync??f.default?.machineIdSync}function WU(){try{let f=JU();if(!f)return;return f().trim()||void 0}catch{return}}function HU(){let f=oy(),$=sy(f,$U);try{if(iy($)){let W=ay($,"utf8").trim();if(W.length>0)return W}}catch{}let J=`cl-${ey()}`;try{ny(f,{recursive:!0}),ty($,J,"utf8")}catch{}return J}var $U="machine-id";var k8=()=>{};class A2{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor(f){this.name=f.name??"OpenTelemetryAdapter",this.metadata={...f.metadata},this.meterProvider=f.meterProvider,this.loggerProvider=f.loggerProvider,this.meter=f.meterProvider?.getMeter("cline")??null,this.logger=f.loggerProvider?.getLogger("cline")??null,this.enabled=f.enabled??!0,this.distinctId=f.distinctId,this.commonProperties=f.commonProperties?{...f.commonProperties}:{}}emit(f,$){if(!this.isEnabled())return;this.emitLog(f,$,!1)}emitRequired(f,$){this.emitLog(f,$,!0)}recordCounter(f,$,J,W,H=!1){if(!this.meter||!H&&!this.isEnabled())return;let Q=this.counters.get(f);if(!Q)Q=this.meter.createCounter(f,W?{description:W}:void 0),this.counters.set(f,Q);Q.add($,this.flattenProperties(this.buildAttributes(J)))}recordHistogram(f,$,J,W,H=!1){if(!this.meter||!H&&!this.isEnabled())return;let Q=this.histograms.get(f);if(!Q)Q=this.meter.createHistogram(f,W?{description:W}:void 0),this.histograms.set(f,Q);Q.record($,this.flattenProperties(this.buildAttributes(J)))}recordGauge(f,$,J,W,H=!1){if(!this.meter||!H&&!this.isEnabled())return;let Q=this.buildAttributes(J),Z=JSON.stringify(Q),j=this.gaugeValues.get(f);if($===null){if(j){if(j.delete(Z),j.size===0)this.gaugeValues.delete(f),this.gauges.delete(f)}return}let X=j;if(!X)X=new Map,this.gaugeValues.set(f,X);if(!this.gauges.has(f)){let A=this.meter.createObservableGauge(f,W?{description:W}:void 0);A.addCallback((P)=>{for(let B of this.snapshotGaugeSeries(f))P.observe(B.value,this.flattenProperties(B.attributes))}),this.gauges.set(f,A)}X.set(Z,{value:$,attributes:Q})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId(f){this.distinctId=f}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog(f,$,J){if(!this.logger)return;let W=this.flattenProperties(this.buildAttributes($,J));this.logger.emit({severityText:"INFO",body:f,attributes:W})}buildAttributes(f,$=!1){return{...this.commonProperties,...this.metadata,...f,...this.distinctId?{distinct_id:this.distinctId}:{},...$?{_required:!0}:{}}}snapshotGaugeSeries(f){let $=this.gaugeValues.get(f);if(!$)return[];return Array.from($.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties(f,$="",J=new WeakSet,W=0){if(!f)return{};let H={},Q=100,Z=10;for(let[j,X]of Object.entries(f)){if(j==="__proto__"||j==="constructor"||j==="prototype")continue;let A=$?`${$}.${j}`:j;if(X===null||X===void 0){H[A]=String(X);continue}if(Array.isArray(X)){let P=X.length>Q?X.slice(0,Q):X;try{H[A]=JSON.stringify(P)}catch{H[A]="[UnserializableArray]"}if(X.length>Q)H[`${A}_truncated`]=!0,H[`${A}_original_length`]=X.length;continue}if(typeof X==="object"){if(X instanceof Date){H[A]=X.toISOString();continue}if(X instanceof Error){H[A]=X.message;continue}if(J.has(X)){H[A]="[Circular]";continue}if(W>=Z){H[A]="[MaxDepthExceeded]";continue}J.add(X),Object.assign(H,this.flattenProperties(X,A,J,W+1));continue}if(__(X)){H[A]=X;continue}try{H[A]=JSON.stringify(X)}catch{H[A]=String(X)}}return H}}function __(f){return typeof f==="string"||typeof f==="number"||typeof f==="boolean"}class D4{name;logger;enabled;constructor(f={}){this.name=f.name??"TelemetryLoggerSink",this.logger=f.logger,this.enabled=f.enabled??!0}emit(f,$){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:f,properties:$})}emitRequired(f,$){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:f,properties:$})}recordCounter(f,$,J,W,H){if(!H&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:f,value:$,attributes:J,description:W,required:H===!0})}recordHistogram(f,$,J,W,H){if(!H&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:f,value:$,attributes:J,description:W,required:H===!0})}recordGauge(f,$,J,W,H){if(!H&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:f,value:$,attributes:J,description:W,required:H===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class P2{adapters;metadata;distinctId;commonProperties;constructor(f={}){if(this.adapters=[...f.adapters??[]],f.logger)this.adapters.push(new D4({logger:f.logger}));this.metadata={...f.metadata??{}},this.distinctId=f.distinctId,this.commonProperties={...f.commonProperties??{}}}addAdapter(f){this.adapters.push(f)}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return this.adapters.some((f)=>f.isEnabled())}capture(f){let $=this.buildAttributes(f.properties);for(let J of this.adapters)J.emit(f.event,$)}captureRequired(f,$){let J=this.buildAttributes($);for(let W of this.adapters)W.emitRequired(f,J)}recordCounter(f,$,J,W,H=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordCounter(f,$,Q,W,H)}recordHistogram(f,$,J,W,H=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordHistogram(f,$,Q,W,H)}recordGauge(f,$,J,W,H=!1){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.recordGauge(f,$,Q,W,H)}async flush(){await Promise.all(this.adapters.map((f)=>f.flush()))}async dispose(){await Promise.all(this.adapters.map((f)=>f.dispose()))}buildAttributes(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var qW=()=>{};import{metrics as M_,trace as L_}from"@opentelemetry/api";import{logs as h_}from"@opentelemetry/api-logs";import{OTLPLogExporter as O_}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as z_}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as N_}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as q_}from"@opentelemetry/resources";import{BatchLogRecordProcessor as w_,ConsoleLogRecordExporter as b_,LoggerProvider as C_}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as E_,MeterProvider as S_,PeriodicExportingMetricReader as wj}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as k_,ConsoleSpanExporter as I_,SimpleSpanProcessor as m_}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as x_}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as g_,ATTR_SERVICE_VERSION as v_}from"@opentelemetry/semantic-conventions";class bj{distinctId;metadata;commonProperties;constructor(f={}){this.distinctId=f.distinctId,this.metadata={...f.metadata??{}},this.commonProperties={...f.commonProperties??{}}}setDistinctId(f){this.distinctId=f}setMetadata(f){this.metadata={...f}}updateMetadata(f){this.metadata={...this.metadata,...f}}setCommonProperties(f){this.commonProperties={...f}}updateCommonProperties(f){this.commonProperties={...this.commonProperties,...f}}isEnabled(){return!1}capture(f){this.resolveProperties(f.properties)}captureRequired(f,$){this.resolveProperties($)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties(f){return{...this.commonProperties,...f,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class B2{meterProvider;loggerProvider;tracerProvider;options;constructor(f={}){this.options=f;let $=q_({[g_]:f.serviceName??"cline",...f.serviceVersion?{[v_]:f.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider($),this.loggerProvider=this.createLoggerProvider($),this.tracerProvider=this.createTracerProvider($),this.meterProvider)M_.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)h_.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer(f="cline",$){return L_.getTracer(f,$??this.options.serviceVersion)}createAdapter(f){return new A2({...f,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService(f){let $=this.createAdapter({name:f.name,enabled:this.options.enabled,metadata:f.metadata});return new P2({...f,adapters:[$],distinctId:B$(f.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider(f){let $=wW(this.options.metricsExporter);if($.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),W=Math.min(30000,Math.floor(J*0.8)),H=$.map((Q)=>d_(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:W})).filter((Q)=>Q!==null);if(H.length===0)return null;return new S_({resource:f,readers:H})}createTracerProvider(f){let $=wW(this.options.tracesExporter);if($.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,W=this.options.otlpTracesHeaders??this.options.otlpHeaders,H=[];for(let Q of $){let Z=c_(Q,{endpoint:J,headers:W,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(Z)H.push(Z)}if(H.length===0)return null;return new x_({resource:f,spanProcessors:H})}createLoggerProvider(f){let $=wW(this.options.logsExporter);if($.length===0)return null;let J=$.map((W)=>{let H=u_(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!H)return null;return new w_(H,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((W)=>W!==null);if(J.length===0)return null;return new C_({resource:f,processors:J})}}function _4(f){let $=new B2(f),J=$.createTelemetryService(f);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:f.enabled??!0,logsExporter:Array.isArray(f.logsExporter)?f.logsExporter.join(","):f.logsExporter,metricsExporter:Array.isArray(f.metricsExporter)?f.metricsExporter.join(","):f.metricsExporter,tracesExporter:Array.isArray(f.tracesExporter)?f.tracesExporter.join(","):f.tracesExporter,otlpProtocol:f.otlpProtocol,hasOtlpEndpoint:Boolean(f.otlpEndpoint),serviceName:f.serviceName,serviceVersion:f.serviceVersion}),{provider:$,telemetry:J}}function G$(f){if(jJ())return{telemetry:new bj(f)};if(f.enabled!==!0)return{telemetry:new P2({...f,distinctId:B$(f.distinctId)})};return _4(f)}function M4(f){let{telemetry:$,provider:J}=G$(f);return{telemetry:$,provider:J,flush:async()=>{let Q=J;if(Q&&typeof Q.forceFlush==="function")try{await Q.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([$.dispose(),J?.dispose()])}}}function wW(f){if(!f)return[];return(Array.isArray(f)?f:f.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function u_(f,$){if(f==="console")return new b_;if(!$.endpoint)return null;let J=bW($.endpoint,"/v1/logs");return new O_({url:J,headers:$.headers})}function c_(f,$){if(f==="console")return new m_(new I_);if(!$.endpoint)return null;let J=bW($.endpoint,"/v1/traces");return new k_(new N_({url:J,headers:$.headers}))}function d_(f,$){if(f==="console")return new wj({exporter:new E_,exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout});if(!$.endpoint)return null;let J=bW($.endpoint,"/v1/metrics");return new wj({exporter:new z_({url:J,headers:$.headers}),exportIntervalMillis:$.interval,exportTimeoutMillis:$.timeout})}function bW(f,$){let J=new URL(f),W=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=W.endsWith($)?W:`${W}${$}`,J.toString()}var L4=L$(()=>{W0();k8();qW()});var MX={};JH(MX,{createOpenTelemetryTelemetryService:()=>_4,createConfiguredTelemetryService:()=>G$,createConfiguredTelemetryHandle:()=>M4,OpenTelemetryProvider:()=>B2,OpenTelemetryAdapter:()=>A2});var pW=L$(()=>{L4()});import*as Wu from"@cline/llms";import{buildClineSystemPrompt as Qu,ContributionRegistry as Zu,createClineTelemetryServiceConfig as ju,createClineTelemetryServiceMetadata as Xu,createContributionRegistry as Au,createTool as Pu,emptyWorkspaceManifest as Bu,formatDisplayUserInput as Yu,noopBasicLogger as Vu,normalizeUserInput as Ru,parseUserCommandEnvelope as Fu,registerDisposable as Ku}from"@cline/shared";export*from"@cline/shared/storage";function eX(f){if(typeof f!=="object"||f===null||!("error"in f))return;let $=f.error;return typeof $==="string"&&$.trim()?$:void 0}function HH(f,$,J){let W=eX(J);if(W)return W;let H=$.trim();if(H){let Q=H.length>200?`${H.slice(0,200)}...`:H;return`Cline account request failed with status ${f}: ${Q}`}return`Cline account request failed with status ${f}`}class C4{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor(f){let $=f.apiBaseUrl.trim();if(!$)throw Error("apiBaseUrl is required");this.apiBaseUrl=$,this.getAuthTokenFn=f.getAuthToken,this.getCurrentUserIdFn=f.getCurrentUserId,this.getOrganizationMemberIdFn=f.getOrganizationMemberId,this.getHeadersFn=f.getHeaders,this.requestTimeoutMs=f.requestTimeoutMs??30000,this.fetchImpl=f.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance(f){let $=await this.resolveUserId(f);return this.request(`/api/v1/users/${encodeURIComponent($)}/balance`)}async fetchUsageTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/usages`)).items??[]}async fetchPaymentTransactions(f){let $=await this.resolveUserId(f);return(await this.request(`/api/v1/users/${encodeURIComponent($)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}`)}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent($)}/balance`)}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId($,f.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent($)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount(f){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:f?.trim()||null},expectNoContent:!0})}async resolveUserId(f){let $=f?.trim();if($)return $;let W=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(W)return W;let H=await this.fetchMe();if(!H.id?.trim())throw Error("Unable to resolve current user id");return H.id}async resolveOrganizationMemberId(f,$){let J=$?.trim();if(J)return J;let H=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn(f):void 0)?.trim();if(H)return H;let Z=(await this.fetchUserOrganizations()).find((j)=>j.organizationId===f)?.memberId;if(!Z?.trim())throw Error(`Unable to resolve memberId for organization ${f}`);return Z}async request(f,$){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let W=this.getHeadersFn?await this.getHeadersFn():{},H=new AbortController,Q=setTimeout(()=>H.abort(),this.requestTimeoutMs);try{let Z=await this.fetchImpl(new URL(f,this.apiBaseUrl),{method:$?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...W??{}},body:$?.body!==void 0?JSON.stringify($.body):void 0,signal:H.signal});if(Z.status===204||$?.expectNoContent){if(!Z.ok)throw Error(`Cline account request failed with status ${Z.status}`);return}let j=await Z.text(),X;if(j.trim())try{X=JSON.parse(j)}catch{if(!Z.ok)throw Error(HH(Z.status,j,void 0));throw Error("Cline account response was not valid JSON")}if(!Z.ok)throw Error(HH(Z.status,j,X));if(typeof X==="object"&&X!==null){let A=X;if(typeof A.success==="boolean"){if(!A.success)throw Error(A.error||"Cline account request failed");if(A.data!==void 0)return A.data}}if(X===void 0||X===null)throw Error("Cline account response payload was empty");return X}finally{clearTimeout(Q)}}}function QH(f){return f.action==="clineAccount"}async function ZH(f,$){switch(f.operation){case"fetchMe":return $.fetchMe();case"fetchBalance":return $.fetchBalance(f.userId);case"fetchUsageTransactions":return $.fetchUsageTransactions(f.userId);case"fetchPaymentTransactions":return $.fetchPaymentTransactions(f.userId);case"fetchUserOrganizations":return $.fetchUserOrganizations();case"fetchOrganizationBalance":return $.fetchOrganizationBalance(f.organizationId);case"fetchOrganizationUsageTransactions":return $.fetchOrganizationUsageTransactions({organizationId:f.organizationId,memberId:f.memberId});case"switchAccount":return await $.switchAccount(f.organizationId),{updated:!0};case"fetchFeaturebaseToken":return $.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String(f)}`)}}class E4{executor;constructor(f){this.executor=f}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance(f){return this.request({action:"clineAccount",operation:"fetchBalance",...f?.trim()?{userId:f.trim()}:{}})}async fetchUsageTransactions(f){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchPaymentTransactions(f){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...f?.trim()?{userId:f.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance(f){let $=f.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:$})}async fetchOrganizationUsageTransactions(f){let $=f.organizationId.trim();if(!$)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:$,...f.memberId?.trim()?{memberId:f.memberId.trim()}:{}})}async switchAccount(f){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:f?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request(f){return(await this.executor.runProviderAction(f)).result}}function S4(f){return{onAuth:({url:$,instructions:J})=>{if(f.onOutput?.(J??"Complete sign-in in your browser."),f.openUrl)try{Promise.resolve(f.openUrl($)).catch((W)=>{f.onOpenUrlError?.({url:$,error:W})})}catch(W){f.onOpenUrlError?.({url:$,error:W})}f.onOutput?.($)},onPrompt:f.onPrompt,onServerListening:f.onServerListening,onServerClose:f.onServerClose}}Uf();import{getClineEnvironmentConfig as a4}from"@cline/shared";function HA(){let f;return{promise:new Promise((J)=>{f=J}),resolve:f}}async function r0(f){let $=await import("node:http"),J=f.host??"127.0.0.1",W=f.timeoutMs??300000,H=f.successHtml??QA,Q=HA(),Z=!1,j=null,X=null,A=null,P=(V)=>{if(Z)return;Z=!0,Q.resolve(V)},B=()=>{if(j)clearTimeout(j),j=null;let V=A;if(A=null,X)X.close(),X=null;if(V!==null&&f.onClose)Promise.resolve(f.onClose({host:J,port:V})).catch(()=>{})},Y=async()=>{return j=setTimeout(()=>{B(),P(null)},W),Q.promise};for(let V of f.ports){let R=$.createServer((K,F)=>{try{let y=new URL(K.url||"",`http://${J}:${V}`);if(y.pathname!==f.callbackPath){F.statusCode=404,F.end("Not found");return}let D={url:y,code:y.searchParams.get("code")??void 0,state:y.searchParams.get("state")??void 0,provider:y.searchParams.get("provider")??void 0,error:y.searchParams.get("error")??void 0};if(D.error){F.statusCode=400,F.end(`Authentication failed: ${D.error}`),B(),P(D);return}if(!D.code){F.statusCode=400,F.end("Missing authorization code");return}if(f.expectedState&&D.state!==f.expectedState){F.statusCode=400,F.end("State mismatch");return}F.statusCode=200,F.setHeader("Content-Type","text/html; charset=utf-8"),F.end(H),B(),P(D)}catch{F.statusCode=500,F.end("Internal error")}}),U=await new Promise((K)=>{let F=(y)=>{R.off("error",F),K({bound:!1,error:y})};R.once("error",F),R.listen(V,J,()=>{R.off("error",F),X=R,K({bound:!0})})});if(U.error){if(U.error.code==="EADDRINUSE")continue;throw B(),U.error}if(U.bound){A=V;let K=`http://${J}:${V}${f.callbackPath}`;if(f.onListening)await Promise.resolve(f.onListening({host:J,port:V,callbackUrl:K})).catch(()=>{});return{callbackUrl:K,waitForCallback:Y,cancelWait:()=>{B(),P(null)},close:()=>{B(),P(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var QA=`<!DOCTYPE html>
|
|
4
4
|
<html lang="en">
|
|
5
5
|
<head>
|
|
6
6
|
<meta charset="utf-8">
|
|
@@ -41,17 +41,17 @@ import{createRequire as lP}from"node:module";var cP=Object.defineProperty;var dP
|
|
|
41
41
|
</div>
|
|
42
42
|
<script>setTimeout(() => window.close(), 3000);</script>
|
|
43
43
|
</body>
|
|
44
|
-
</html>`;function tW(f){let $="";for(let J=0;J<f.length;J+=1)$+=String.fromCharCode(f[J]??0);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function eP(f){let J=new TextEncoder().encode(f),H=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(H)}function fX(f=32){let $=new Uint8Array(f);return crypto.getRandomValues($),tW($)}async function B2(){let f=fX(),$=tW(await eP(f));return{verifier:f,challenge:$}}function A2(f){return f.endsWith("/")?f.slice(0,-1):f}function v0(f,$){return new URL($,`${A2(f)}/`).toString()}function h$(f,$={}){let J=f.trim();if(!J)return{};try{let H=new URL(J);return{code:H.searchParams.get("code")??void 0,state:H.searchParams.get("state")??void 0,provider:$.includeProvider?H.searchParams.get("provider")??void 0:void 0}}catch{}if($.allowHashCodeState&&J.includes("#")){let[H,W]=J.split("#",2);return{code:H||void 0,state:W||void 0}}if(J.includes("code=")){let H=new URLSearchParams(J);return{code:H.get("code")??void 0,state:H.get("state")??void 0,provider:$.includeProvider?H.get("provider")??void 0:void 0}}return{code:J}}function $X(f){if(typeof atob==="function")try{return atob(f)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from(f,"base64").toString("utf8")}catch{return null}return null}function jf(f){if(!f)return null;try{let $=f.split(".");if($.length!==3)return null;let J=$[1];if(!J)return null;let H=J.replace(/-/g,"+").replace(/_/g,"/"),W=H.padEnd(H.length+(4-H.length%4)%4,"="),Q=$X(W);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function T$(f){try{let $=JSON.parse(f),J=$.error,H=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,W=typeof $.error_description==="string"?$.error_description:typeof $.message==="string"?$.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:H,message:W}}catch{return{}}}function u0(f,$){return Date.now()>=f.expires-$}async function D$(f){if(!f.onManualCodeInput){let Q=await f.waitForCallback();return{code:Q?.code,state:Q?.state,provider:Q?.provider,error:Q?.error}}let $,J,H=f.onManualCodeInput().then((Q)=>{$=Q,f.cancelWait()}).catch((Q)=>{J=Q instanceof Error?Q:Error(String(Q)),f.cancelWait()}),W=await f.waitForCallback();if(J)throw J;if(W?.code||W?.error)return{code:W.code,state:W.state,provider:W.provider,error:W.error};if($)return h$($,f.parseOptions);if(await H,J)throw J;if($)return h$($,f.parseOptions);return{}}var R2={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},f5={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},r4="https://api.workos.com",l4="client_01K3A541FN8TA3EPPHTD2325AR",JX="/auth",sW=Array.from({length:11},(f,$)=>48801+$),HX=300000,WX=30000,M$=30000,QX=300,ZX=5;class B0 extends Error{status;errorCode;constructor(f,$){super(f);this.name="ClineOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function jX(f){let $=Date.parse(f);if(Number.isNaN($))throw Error(`Invalid expiresAt value: ${f}`);return $}function p4(f,$,J={}){let H=f.userInfo.clineUserId??J.accountId,W=f.refreshToken??J.refresh;if(!W)throw Error("Token response did not include a refresh token");return{access:f.accessToken,refresh:W,expires:jX(f.expiresAt),accountId:H??void 0,email:f.userInfo.email||J.email,metadata:{provider:$,tokenType:f.tokenType,userInfo:f.userInfo}}}async function i4(f){if(!f)return{};return typeof f==="function"?await f():f}function oW(f,$){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return $;return Math.floor(f)}async function eW(f){await new Promise(($)=>setTimeout($,f))}function n4(f,$){if(!f.success||!f.data?.accessToken)throw Error($);return f.data}async function $5(f,$){let J=await fetch(v0(r4,f5.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:f}),signal:AbortSignal.timeout($?.requestTimeoutMs??M$)}),H=await J.json().catch(()=>({}));if(!J.ok)throw new B0(`Device authorization failed: ${J.status}${H.error_description?` - ${H.error_description}`:""}`,{status:J.status,errorCode:H.error});if(!H.device_code||!H.user_code||!H.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:H.device_code,userCode:H.user_code,verificationUri:H.verification_uri,verificationUriComplete:H.verification_uri_complete,expiresInSeconds:oW(H.expires_in,QX),pollIntervalSeconds:oW(H.interval,ZX)}}async function J5(f){let $=Date.now()+f.expiresInSeconds*1000,J=Math.max(1,f.initialPollIntervalSeconds);while(Date.now()<=$){let H=await fetch(v0(f.workosApiBaseUrl,f5.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:f.deviceCode,client_id:f.clientId}),signal:AbortSignal.timeout(f.requestTimeoutMs)}),W=await H.json().catch(()=>({}));if(H.ok){if(!W.access_token||!W.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:W.access_token,refreshToken:W.refresh_token,tokenType:W.token_type??"Bearer"}}switch(W.error){case"authorization_pending":{await eW(J*1000);break}case"slow_down":{J+=1,await eW(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new B0(W.error_description||"WorkOS authorization failed",{status:H.status,errorCode:W.error});default:throw new B0(`WorkOS token polling failed: ${H.status}${W.error_description?` - ${W.error_description}`:""}`,{status:H.status,errorCode:W.error})}f.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function H5(f,$,J){let H={accessToken:f.accessToken,refreshToken:f.refreshToken},W=await fetch(v0($.apiBaseUrl,R2.register),{method:"POST",headers:{"Content-Type":"application/json",...await i4($.headers)},body:JSON.stringify(H),signal:AbortSignal.timeout($.requestTimeoutMs??M$)});if(!W.ok){let Z=await W.text().catch(()=>""),j=T$(Z);throw new B0(`Token registration failed: ${W.status}${j.message?` - ${j.message}`:""}`,{status:W.status,errorCode:j.code})}let Q=await W.json();return p4(n4(Q,"Invalid token exchange response"),J??$.provider)}async function PX(f,$,J,H){let W={grant_type:"authorization_code",code:f,client_type:"extension",redirect_uri:$,provider:H??J.provider},Q=await fetch(v0(J.apiBaseUrl,R2.token),{method:"POST",headers:{"Content-Type":"application/json",...await i4(J.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(J.requestTimeoutMs??M$)});if(!Q.ok){let j=await Q.text().catch(()=>""),P=T$(j);throw new B0(`Token exchange failed: ${Q.status}${P.message?` - ${P.message}`:""}`,{status:Q.status,errorCode:P.code})}let Z=await Q.json();return p4(n4(Z,"Invalid token exchange response"),H??J.provider)}async function F2(f){P0(f.telemetry,f.provider??"cline");let $=f.useWorkOSDeviceAuth??!0,J=f.callbackPorts?.length?f.callbackPorts:sW,H=f.callbackPath??JX,W=$?null:await g0({ports:J,callbackPath:H,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),Q=W?.callbackUrl||`http://127.0.0.1:${J[0]??sW[0]}${H}`;try{let Z;if($){let j=l4,P=await $5(j,f);f.callbacks.onAuth({url:P.verificationUriComplete??P.verificationUri,instructions:`Enter this code in your browser: ${P.userCode}`});let X=await J5({clientId:j,deviceCode:P.deviceCode,expiresInSeconds:P.expiresInSeconds,initialPollIntervalSeconds:P.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??M$,workosApiBaseUrl:r4,onProgress:f.callbacks.onProgress});Z=await H5(X,f,f.provider)}else{let j=new URL(v0(f.apiBaseUrl,R2.authorize));j.searchParams.set("client_type","extension"),j.searchParams.set("callback_url",Q),j.searchParams.set("redirect_uri",Q),f.callbacks.onAuth({url:j.toString(),instructions:"Continue the authentication process in your browser."});let P,X=f.provider,V=await D$({waitForCallback:W?.waitForCallback??(async()=>null),cancelWait:W?.cancelWait??(()=>{}),onManualCodeInput:f.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(V.error)throw Error(`OAuth error: ${V.error}`);if(P=V.code,X=V.provider??X,!P){let Y=await f.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=h$(Y,{includeProvider:!0});P=B.code,X=B.provider??X}if(!P)throw Error("Missing authorization code");Z=await PX(P,Q,f,X)}return X0(f.telemetry,f.provider??"cline"),Y0(f.telemetry,{id:Z.accountId,email:Z.email,provider:f.provider??"cline"}),Z}catch(Z){throw V0(f.telemetry,f.provider??"cline",Z instanceof Error?Z.message:String(Z)),Z}finally{W?.close()}}async function XX(f){return await $5(l4,f)}async function VX(f){let $=f.provider??"cline";P0(f.telemetry,$);try{let J=await J5({clientId:l4,deviceCode:f.deviceCode,expiresInSeconds:f.expiresInSeconds,initialPollIntervalSeconds:f.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??M$,workosApiBaseUrl:r4}),H=await H5(J,{apiBaseUrl:f.apiBaseUrl,headers:f.headers,requestTimeoutMs:f.requestTimeoutMs,provider:f.provider},f.provider);return X0(f.telemetry,$),Y0(f.telemetry,{id:H.accountId,email:H.email,provider:$}),H}catch(J){throw V0(f.telemetry,$,J instanceof Error?J.message:String(J)),J}}async function a4(f,$){let J=await fetch(v0($.apiBaseUrl,R2.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await i4($.headers)},body:JSON.stringify({refreshToken:f.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout($.requestTimeoutMs??M$)});if(!J.ok){let Q=await J.text().catch(()=>""),Z=T$(Q);throw new B0(`Token refresh failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let H=await J.json(),W=f.metadata?.provider??$.provider;return p4(n4(H,"Invalid token refresh response"),W,f)}async function t4(f,$,J){if(!f)return null;let H=J?.refreshBufferMs??HX,W=J?.retryableTokenGraceMs??WX;if(J?.forceRefresh!==!0&&!u0(f,H))return f;try{return await a4(f,$)}catch(Z){if(Z instanceof B0&&Z.isLikelyInvalidGrant())return I0($.telemetry,$.provider??"cline","invalid_grant"),null;if(f.expires-Date.now()>W)return f;return null}}function YX(f){return{id:"cline",name:"Cline Account",usesCallbackServer:!(f.useWorkOSDeviceAuth??!0),async login($){return F2({...f,callbacks:$})},async refreshToken($){return a4($,f)},getApiKey($){return`workos:${$.access}`}}}Af();import{nanoid as BX}from"nanoid";var a={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 y2 extends Error{status;errorCode;constructor(f,$){super(f);this.name="OpenAICodexOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function AX(f,$,J=a.redirectUri){let H=await fetch(a.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:a.clientId,code:f,code_verifier:$,redirect_uri:J}),signal:AbortSignal.timeout(a.httpTimeoutMs)});if(!H.ok)return{type:"failed"};let W=await H.json();if(!W.access_token||!W.refresh_token||typeof W.expires_in!=="number")return{type:"failed"};return{type:"success",access:W.access_token,refresh:W.refresh_token,expires:Date.now()+W.expires_in*1000,email:W.email,idToken:W.id_token}}async function RX(f){try{let $=await fetch(a.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:f,client_id:a.clientId}),signal:AbortSignal.timeout(a.httpTimeoutMs)});if(!$.ok){let H=await $.text().catch(()=>""),W=T$(H);throw new y2(`Token refresh failed: ${$.status}${W.message?` - ${W.message}`:""}`,{status:$.status,errorCode:W.code})}let J=await $.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch($){if($ instanceof y2)throw $;return{type:"failed"}}}async function FX(f="pi"){let{verifier:$,challenge:J}=await B2(),H=BX(32),W=new URL(a.authorizationEndpoint);return W.searchParams.set("response_type","code"),W.searchParams.set("client_id",a.clientId),W.searchParams.set("redirect_uri",a.redirectUri),W.searchParams.set("scope",a.scopes),W.searchParams.set("code_challenge",J),W.searchParams.set("code_challenge_method","S256"),W.searchParams.set("state",H),W.searchParams.set("id_token_add_organizations","true"),W.searchParams.set("codex_cli_simplified_flow","true"),W.searchParams.set("originator",f),{verifier:$,state:H,url:W.toString()}}function yX(){try{let f=new URL(a.redirectUri),$=f.port.length>0?Number.parseInt(f.port,10):a.callbackPort;return{host:f.hostname||"localhost",port:Number.isFinite($)?$:a.callbackPort,callbackPath:f.pathname||"/auth/callback",redirectUri:f.toString()}}catch{return{host:"localhost",port:a.callbackPort,callbackPath:"/auth/callback",redirectUri:a.redirectUri}}}function W5(f,$){let J=$?jf($):jf(f),H=J?J:jf(f),Q=H?.[a.jwtClaimPath]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=H?.organizations;if(Array.isArray(Z)&&Z.length>0){let P=Z[0];if(typeof P?.id==="string"&&P.id.length>0)return P.id}let j=H?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return null}function Q5(f,$){let J=W5(f.access,f.idToken)??$?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:f.access,refresh:f.refresh||$?.refresh||"",expires:f.expires,accountId:J,email:f.email??$?.email,metadata:{...$?.metadata??{},provider:"openai-codex"}}}async function K2(f){P0(f.telemetry,"openai-codex");let $=yX(),{verifier:J,state:H,url:W}=await FX(f.originator),Q=await g0({host:$.host,ports:[$.port],callbackPath:$.callbackPath,expectedState:H});f.onAuth({url:W,instructions:"Continue the authentication process in your browser."});let Z;try{let j=await D$({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:f.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(j.state&&j.state!==H)throw Error("State mismatch");if(Z=j.code,!Z){let V=await f.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),Y=h$(V,{allowHashCodeState:!0});if(Y.state&&Y.state!==H)throw Error("State mismatch");Z=Y.code}if(!Z)throw Error("Missing authorization code");let P=await AX(Z,J,$.redirectUri);if(P.type!=="success")throw Error("Token exchange failed");let X=Q5(P);return X0(f.telemetry,"openai-codex"),Y0(f.telemetry,{id:X.accountId,email:X.email,provider:"openai-codex"}),X}catch(j){throw V0(f.telemetry,"openai-codex",j instanceof Error?j.message:String(j)),j}finally{Q.close()}}async function s4(f,$){let J=await RX(f);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let H=Q5(J,$);if(!H.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return H}async function o4(f,$){if(!f)return null;let J=$?.refreshBufferMs??a.refreshBufferMs,H=$?.retryableTokenGraceMs??a.retryableTokenGraceMs;if($?.forceRefresh!==!0&&!u0(f,J))return f;try{return await s4(f.refresh,f)}catch(Q){if(Q instanceof y2&&Q.isLikelyInvalidGrant())return I0($?.telemetry,"openai-codex","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function KX(f,$=a.refreshBufferMs){return u0(f,$)}function UX(f){let $=f.accountId??W5(f.access);if(!$)throw Error("Failed to extract accountId from token");return{...f,accountId:$,metadata:{...f.metadata??{},provider:"openai-codex"}}}var GX={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login(f){return K2({onAuth:f.onAuth,onPrompt:f.onPrompt,onProgress:f.onProgress,onManualCodeInput:f.onManualCodeInput})},async refreshToken(f){return s4(f.refresh,f)},getApiKey(f){return f.access}};Af();import{nanoid as Z5}from"nanoid";class e4{ttlMs;maxEntries;entries=new Map;constructor(f,$){this.ttlMs=f;this.maxEntries=$}get(f,$=Date.now()){this.pruneExpired($);let J=this.entries.get(f);if(!J)return;return this.entries.delete(f),this.entries.set(f,J),J.value}set(f,$,J=Date.now(),H=this.ttlMs){this.pruneExpired(J),this.entries.delete(f);while(this.entries.size>=this.maxEntries){let W=this.entries.keys().next().value;if(W===void 0)break;this.entries.delete(W)}this.entries.set(f,{value:$,expiresAt:J+H})}pruneExpired(f){for(let[$,J]of this.entries)if(J.expiresAt<=f)this.entries.delete($)}}var j5="a8331954c0cf48ba99b5dd223a14c6ea",P5="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",X5="openid offline_access",U2="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",V5="c1aba3deed5740659981a752714eba33",Y5="https://login-ext.identity.oraclecloud.com",B5="openid offline_access",G2="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",A5="opc-request-id",hX="/auth/oca",TX=Array.from({length:11},(f,$)=>48801+$),DX=300000,MX=30000,R5=30000,_X=600000;class h2 extends Error{status;errorCode;constructor(f,$){super(f);this.name="OcaOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var A0={internal:{clientId:j5,idcsUrl:P5,scopes:X5,baseUrl:U2},external:{clientId:V5,idcsUrl:Y5,scopes:B5,baseUrl:G2}},J1=new Map,LX=86400000,zX=300000,OX=32,f6=new e4(LX,OX);function F5(f){if(typeof f==="function")return f();return f??"internal"}function y5(f){return{internal:{clientId:f?.internal?.clientId??A0.internal.clientId,idcsUrl:f?.internal?.idcsUrl??A0.internal.idcsUrl,scopes:f?.internal?.scopes??A0.internal.scopes,baseUrl:f?.internal?.baseUrl??A0.internal.baseUrl},external:{clientId:f?.external?.clientId??A0.external.clientId,idcsUrl:f?.external?.idcsUrl??A0.external.idcsUrl,scopes:f?.external?.scopes??A0.external.scopes,baseUrl:f?.external?.baseUrl??A0.external.baseUrl}}}function NX(f=Date.now()){let $=f-_X;for(let[J,H]of J1.entries())if(H.createdAt<$)J1.delete(J)}function qX(f,$,J){if(typeof f.expires_in==="number"&&f.expires_in>0)return Date.now()+f.expires_in*1000;let W=jf($)?.exp;if(typeof W==="number"&&W>0)return W*1000;let Z=jf(J)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return Date.now()+3600000}function K5(f,$,J){let H=f.access_token;if(!H)throw Error("Token response did not include an access token");let W=f.refresh_token??J?.refresh;if(!W)throw Error("Token response did not include a refresh token");let Q=jf(f.id_token),Z=jf(H),j=Q?.sub??Z?.sub,P=Q?.email??Z?.email;return{access:H,refresh:W,expires:qX(f,H,f.id_token),accountId:j??J?.accountId,email:P??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:$,subject:j,idToken:f.id_token}}}async function U5(f,$){let J=A2(f),H=f6.get(J);if(H)return H;let W=`${J}/.well-known/openid-configuration`,Q=await fetch(W,{method:"GET",signal:AbortSignal.timeout($)});if(!Q.ok){let P=`${J}/oauth2/v1/token`;return f6.set(J,P,Date.now(),zX),P}let j=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return f6.set(J,j),j}function G5(f){return{code:f.error,message:f.error_description}}async function bX(f){let $=J1.get(f.state);if(!$)throw Error("No PKCE verifier found for this state");J1.delete(f.state);let J=f.mode==="external"?f.config.external:f.config.internal,H=await U5(J.idcsUrl,f.requestTimeoutMs),W=new URLSearchParams({grant_type:"authorization_code",code:f.code,redirect_uri:$.redirectUri,client_id:J.clientId,code_verifier:$.verifier}),Q=await fetch(H,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:W,signal:AbortSignal.timeout(f.requestTimeoutMs)}),Z=await Q.json();if(!Q.ok){let P=G5(Z);throw new h2(`Token exchange failed: ${Q.status}${P.message?` - ${P.message}`:""}`,{status:Q.status,errorCode:P.code})}let j=jf(Z.id_token);if(!Z.id_token||!j)throw Error("No ID token received from OCA");if(j.nonce!==$.nonce)throw Error("OIDC nonce verification failed");return K5(Z,f.mode)}function wX(f){let $=f.mode==="external"?f.config.external:f.config.internal,J=new URL(`${A2($.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",$.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",$.scopes),J.searchParams.set("code_challenge",f.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",f.callbackUrl),J.searchParams.set("state",f.state),J.searchParams.set("nonce",f.nonce),J.toString()}async function T2(f){P0(f.telemetry,"oca");let $=y5(f.config),J=F5(f.mode),H=f.callbackPorts?.length?f.callbackPorts:TX,W=f.callbackPath??hX,Q=f.requestTimeoutMs??R5,Z=await g0({ports:H,callbackPath:W,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),j=Z.callbackUrl;if(!j)throw Error("Unable to bind local OAuth callback server");let P=Z5(16),X=Z5(16),{verifier:V,challenge:Y}=await B2();NX(),J1.set(P,{verifier:V,nonce:X,mode:J,redirectUri:j,createdAt:Date.now()});let B=wX({callbackUrl:j,mode:J,state:P,nonce:X,challenge:Y,config:$});f.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let A=await D$({waitForCallback:Z.waitForCallback,cancelWait:Z.cancelWait,onManualCodeInput:f.callbacks.onManualCodeInput}),R=A.code,U=A.state;if(A.error)throw Error(`OAuth error: ${A.error}`);if(!R){if(!f.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!U||U!==P)throw Error("State mismatch");let y=await bX({code:R,state:U,mode:J,config:$,requestTimeoutMs:Q});return X0(f.telemetry,"oca"),Y0(f.telemetry,{id:y.accountId,email:y.email,provider:"oca"}),y}catch(A){throw V0(f.telemetry,"oca",A instanceof Error?A.message:String(A)),A}finally{Z.close()}}async function $6(f,$={}){let J=y5($.config),H=$.requestTimeoutMs??R5,W=f.metadata?.mode,Q=W==="internal"||W==="external"?W:F5($.mode),Z=Q==="external"?J.external:J.internal,j=await U5(Z.idcsUrl,H),P=new URLSearchParams({grant_type:"refresh_token",refresh_token:f.refresh,client_id:Z.clientId}),X=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:P,signal:AbortSignal.timeout(H)}),V=await X.json();if(!X.ok){let Y=G5(V);throw new h2(`Token refresh failed: ${X.status}${Y.message?` - ${Y.message}`:""}`,{status:X.status,errorCode:Y.code})}return K5(V,Q,f)}async function J6(f,$,J){if(!f)return null;let H=$?.refreshBufferMs??J?.refreshBufferMs??DX,W=$?.retryableTokenGraceMs??J?.retryableTokenGraceMs??MX;if($?.forceRefresh!==!0&&!u0(f,H))return f;try{return await $6(f,J)}catch(Z){if(Z instanceof h2&&Z.isLikelyInvalidGrant())return I0(J?.telemetry,"oca","invalid_grant"),null;if(f.expires-Date.now()>W)return f;return null}}function CX(f={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login($){return T2({...f,callbacks:$})},async refreshToken($){return $6($,f)},getApiKey($){return $.access}}}async function h5(f,$){let J=new TextEncoder,H=async(X)=>{let V=await crypto.subtle.digest("SHA-256",J.encode(X));return Array.from(new Uint8Array(V).slice(0,4),(Y)=>Y.toString(16).padStart(2,"0")).join("")},[W,Q]=await Promise.all([H($),H(f)]),Z=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),j=new Uint32Array(1);crypto.getRandomValues(j);let P=(j[0]??0).toString(16).padStart(8,"0");return W+Q+Z+P}async function EX(f){let $=await h5(f.taskId,f.accessToken);return{Authorization:`Bearer ${f.accessToken}`,"Content-Type":"application/json",client:f.metadata?.client??"Cline","client-version":f.metadata?.clientVersion??"unknown","client-ide":f.metadata?.clientIde??"unknown","client-ide-version":f.metadata?.clientIdeVersion??"unknown",[A5]:$}}import*as hf from"@cline/llms";import{z as _}from"zod";import*as Qf from"@cline/llms";function H6(f){if(!Array.isArray(f))return[];return f.map(($)=>{if(typeof $==="string")return $.trim();if($&&typeof $==="object"){let J=$;for(let H of[J.id,J.name,J.model])if(typeof H==="string"&&H.trim())return H.trim()}return""}).filter(($)=>$.length>0)}function SX(f,$){let J=H6(f);if(J.length>0)return J;if(!f||typeof f!=="object")return[];let H=f,W=H6(H.data??H.models);if(W.length>0)return W;if(H.models&&typeof H.models==="object"&&!Array.isArray(H.models)){let Z=Object.keys(H.models).filter((j)=>j.trim().length>0);if(Z.length>0)return Z}let Q=H.providers?.[$];if(Q&&typeof Q==="object"){let j=H6(Q.models??Q);if(j.length>0)return j}return[]}async function D2(f,$){let J=await fetch(f,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${f}: HTTP ${J.status}`);return SX(await J.json(),$)}function T5(f){return f.replace(/\/+$/,"")}function M2(f,$,J){let H=J?.trim();if(!H)return;let W=f?.trim();if(!W||!$?.trim())return H;try{let Q=new URL(H),Z=new URL($),j=new URL(W);if(Q.origin!==Z.origin)return H;let P=T5(Z.pathname),X=T5(j.pathname);if(P&&Q.pathname.startsWith(`${P}/`)){let V=Q.pathname.slice(P.length);j.pathname=`${X}${V}`}else j.pathname=Q.pathname;return j.search=Q.search,j.hash=Q.hash,j.toString()}catch{return H}}function kX(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{...J}]))}function mX(f){if(f.baseUrl.length===0)return!1;switch(f.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return f.protocol==="openai-chat"}}var IX=Object.values(Qf.MODEL_COLLECTIONS_BY_PROVIDER_ID).map((f)=>({id:f.provider.id,baseUrl:f.provider.baseUrl??"",modelsSourceUrl:f.provider.modelsSourceUrl,modelId:f.provider.defaultModelId,knownModels:kX(f.models),capabilities:f.provider.capabilities?[...f.provider.capabilities]:void 0,env:f.provider.env?[...f.provider.env]:void 0,client:f.provider.client,protocol:f.provider.protocol})),M5=Object.fromEntries(IX.map((f)=>[f.id,f]));function xX(f){return M5[f]}function gX(){return Object.fromEntries(Object.entries(M5).filter(([,f])=>mX(f)))}function _5(f=[]){let $=f.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return $.length>0?$:void 0}var L5="https://models.dev/api.json",vX=600000,z5=300000,uX=5000,L2=new Map,H1=new Map,Z6=new Map,_2=new Map;async function cX(){return Qf.getGeneratedProviderModels()}async function dX(f,$={},J={},H={},W={},Q={}){let Z=await cX(),j=Qf.resolveProviderModelCatalogKeys(f),P=Object.assign({},...j.map((Y)=>Z[Y]??{})),X=Boolean(Qf.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl),V=Object.keys(W).length>0;if(X&&V)return Qf.sortModelsByReleaseDate({...W,...Q});return Qf.sortModelsByReleaseDate({...P,...$,...J,...H,...W,...Q})}function rX(f,$){let J=Qf.resolveProviderModelCatalogKeys(f);return Object.assign({},...J.map((H)=>$[H]??{}))}function j6(f){let $=f?.trim();return $&&$.length>0?$:""}function P6(f){let $=f.apiKey?.trim()||f.accessToken?.trim();return $&&$.length>0?$:void 0}function lX(f){let $=2166136261;for(let J=0;J<f.length;J+=1)$^=f.charCodeAt(J),$+=($<<1)+($<<4)+($<<7)+($<<8)+($<<24);return($>>>0).toString(16)}function pX(f,$){return`${f}:${j6($.baseUrl)}:${lX(P6($)??"")}`}async function X6(f,$,J=uX){let H=new AbortController,W=setTimeout(()=>H.abort(),J);try{return await fetch(f,{...$,signal:H.signal})}finally{clearTimeout(W)}}function W6(f,$,J){if(J&&!f.includes($))f.push($)}function z2(f,$){let J=["streaming","tools"];return W6(J,"images",Boolean($.supportsImages)),W6(J,"prompt-cache",Boolean($.supportsPromptCache)),W6(J,"reasoning",Boolean($.supportsReasoning)),{id:f,name:$.name??f,contextWindow:$.contextWindow,maxTokens:$.maxTokens,capabilities:J,releaseDate:$.releaseDate,status:"active"}}async function iX(f,$){let J=await X6("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let W=(await J.json())?.data??[],Q={};for(let Z of W){let j=Z.id?.trim();if(!j)continue;if(j.includes("whisper")||j.includes("tts")||j.includes("embedding"))continue;let P=Z.supported_features??[];Q[j]=z2(j,{name:j,contextWindow:Z.context_length,maxTokens:Z.max_completion_tokens,supportsReasoning:P.includes("reasoning")||P.includes("reasoning_effort"),supportsImages:!1})}return Q}async function nX(f,$){let J=await X6("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":$}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let W=(await J.json())?.data??[],Q={};for(let Z of W){let j=Z.id?.trim();if(!j)continue;Q[j]=z2(j,{name:j,contextWindow:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}function aX(f){let $=j6(f);if(!$)return"http://localhost:4000";return $.endsWith("/v1")?$.slice(0,-3):$}async function tX(f,$){let H=`${aX(f.baseUrl)}/v1/model/info`,W=async(X)=>X6(H,{method:"GET",headers:{accept:"application/json",...X}}),Q=await W({"x-litellm-api-key":$});if(!Q.ok)Q=await W({Authorization:`Bearer ${$}`});if(!Q.ok)throw Error(`LiteLLM model refresh failed: HTTP ${Q.status}`);let j=(await Q.json())?.data??[],P={};for(let X of j){let V=X.model_name?.trim(),B=X.litellm_params?.model?.trim()||V;if(!B)continue;let A=X.model_info,R=z2(B,{name:V??B,maxTokens:A?.max_output_tokens??A?.max_tokens,contextWindow:A?.max_input_tokens??A?.max_tokens,supportsImages:A?.supports_vision,supportsPromptCache:A?.supports_prompt_caching,supportsReasoning:A?.supports_reasoning});if(P[B]=R,V)P[V]={...R,id:V,name:V}}return P}var O5={baseten:iX,hicap:nX,litellm:tX},D5=new Map,Q6=new Map;function sX(f,$){return`${f}:${j6($.baseUrl)}`}async function oX(f,$,J){let H=Qf.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],W=M2(J.baseUrl,H?.provider.baseUrl,H?.provider.modelsSourceUrl);if(!W)return{};let Q=$?.cacheTtlMs??z5,Z=sX(f,J),j=Date.now(),P=D5.get(Z);if(P&&P.expiresAt>j)return P.data;let X=Q6.get(Z);if(X)return X;let V=D2(W,f).then((Y)=>{let B=Object.fromEntries(Y.map((A)=>[A,z2(A,{name:A})]));return D5.set(Z,{data:B,expiresAt:j+Q}),B}).finally(()=>{Q6.delete(Z)});return Q6.set(Z,V),V}async function eX(f,$){let J=P6($);if(!J)return{};let H=O5[f];if(!H)return{};return H($,J)}function fV(f,$,J){if(!J)return!1;if(!O5[f])return!1;if($?.loadPrivateOnAuth===!1)return!1;return Boolean(P6(J))}async function $V(f,$,J){let H=$?.cacheTtlMs??z5,W=pX(f,J),Q=Date.now(),Z=Z6.get(W);if(Z&&Z.expiresAt>Q)return Z.data;let j=_2.get(W);if(j)return j;let P=eX(f,J).then((X)=>{return Z6.set(W,{data:X,expiresAt:Q+H}),X}).finally(()=>{_2.delete(W)});return _2.set(W,P),P}async function JV(f){return Qf.fetchModelsDevProviderModels(f)}async function O2(f={}){let $=f.url??L5,J=f.cacheTtlMs??vX,H=Date.now(),W=L2.get($);if(W&&W.expiresAt>H)return W.data;let Q=H1.get($);if(Q)return Q;let Z=JV($).then((j)=>{return L2.set($,{data:j,expiresAt:H+J}),j}).finally(()=>{H1.delete($)});return H1.set($,Z),Z}function HV(f){if(f){L2.delete(f),H1.delete(f);return}L2.clear(),H1.clear()}function WV(){Z6.clear(),_2.clear()}function QV(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:_5(J.capabilities)}]))}var V6=QV(gX());function N5(f){let $=xX(f);if(!$||!$.baseUrl)return;return{baseUrl:$.baseUrl,modelId:$.modelId,knownModels:$.knownModels,capabilities:_5($.capabilities)}}async function Y6(f,$,J){let H=N5(f);if(!H)return;try{let W=$?.loadLatestOnInit?await O2($):void 0,Q=W?rX(f,W):{},Z=J&&fV(f,$,J)?await $V(f,$,J):{},P=Boolean(Qf.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl)?J??{providerId:f,modelId:H.modelId,baseUrl:H.baseUrl}:J,X=P?await oX(f,$,P).catch(()=>({})):{},V=await dX(f,H.knownModels,Q,Z,X,J?.knownModels);return{...H,knownModels:V}}catch(W){if($?.failOnError)throw W;return H}}var B6=hf.BUILT_IN_PROVIDER,ZV=hf.BUILT_IN_PROVIDER_IDS,jV=hf.isBuiltInProviderId,N2=hf.normalizeProviderId,A6=_.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),q5=_.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),b5=_.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),w5=_.object({apiKey:_.string().optional(),accessToken:_.string().optional(),refreshToken:_.string().optional(),expiresAt:_.number().int().positive().optional(),accountId:_.string().optional()}),PV=_.enum(["none","low","medium","high","xhigh"]),C5=_.object({enabled:_.boolean().optional(),effort:PV.optional(),budgetTokens:_.number().int().positive().optional()}),E5=_.object({accessKey:_.string().optional(),secretKey:_.string().optional(),sessionToken:_.string().optional(),region:_.string().optional(),profile:_.string().optional(),authentication:_.enum(["iam","api-key","profile"]).optional(),usePromptCache:_.boolean().optional(),useCrossRegionInference:_.boolean().optional(),useGlobalInference:_.boolean().optional(),endpoint:_.string().url().optional(),customModelBaseId:_.string().optional()}),S5=_.object({projectId:_.string().optional(),region:_.string().optional()}),k5=_.object({apiVersion:_.string().optional(),useIdentity:_.boolean().optional()}),m5=_.object({clientId:_.string().optional(),clientSecret:_.string().optional(),tokenUrl:_.string().url().optional(),resourceGroup:_.string().optional(),deploymentId:_.string().optional(),useOrchestrationMode:_.boolean().optional(),api:_.enum(["orchestration","foundation-models"]).optional(),defaultSettings:_.record(_.string(),_.unknown()).optional()}),I5=_.object({mode:_.enum(["internal","external"]).optional(),usePromptCache:_.boolean().optional()}),x5=_.object({loadLatestOnInit:_.boolean().optional(),loadPrivateOnAuth:_.boolean().optional(),url:_.string().url().optional(),cacheTtlMs:_.number().int().positive().optional(),failOnError:_.boolean().optional()}),_$=_.object({provider:A6,apiKey:_.string().optional(),auth:w5.optional(),model:_.string().optional(),protocol:q5.optional(),client:b5.optional(),routingProviderId:A6.optional(),maxTokens:_.number().int().positive().optional(),contextWindow:_.number().int().positive().optional(),baseUrl:_.string().url().optional(),headers:_.record(_.string(),_.string()).optional(),timeout:_.number().int().positive().optional(),reasoning:C5.optional(),aws:E5.optional(),gcp:S5.optional(),azure:k5.optional(),sap:m5.optional(),oca:I5.optional(),region:_.string().optional(),apiLine:_.enum(["china","international"]).optional(),capabilities:_.array(_.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth"])).optional(),modelCatalog:x5.optional()});function g5(f){return _$.parse(f)}function v5(f){return _$.safeParse(f)}function XV(f){return f.protocol==="openai-responses"||f.client==="openai"}function tf(f,$={}){let J=f.provider,H=N2(J),W=$.includeKnownModels!==!1,Q=f.reasoning?.effort||"none",Z=Q==="none"?void 0:Q,j=V6[H],P=Object.assign({},...hf.resolveProviderModelCatalogKeys(H).map((U)=>hf.getGeneratedModelsForProvider(U))),X=Object.keys(P)[0],V=f.auth?.accessToken??f.apiKey??f.auth?.apiKey,Y=f.baseUrl??(H==="oca"?f.oca?.mode==="internal"?U2:G2:j?.baseUrl),B=f.routingProviderId??(XV(f)&&H!==B6.OPENAI_NATIVE?B6.OPENAI_NATIVE:void 0),A=W?j?.knownModels??(Object.keys(P).length>0?P:void 0):void 0,R={providerId:J,clientType:f.client,routingProviderId:B,modelId:f.model??j?.modelId??X??"default",...W?{knownModels:A}:{},apiKey:V,accessToken:f.auth?.accessToken,refreshToken:f.auth?.refreshToken,accountId:f.auth?.accountId,baseUrl:Y,headers:f.headers,timeoutMs:f.timeout,maxOutputTokens:f.maxTokens,maxContextTokens:f.contextWindow,thinking:f.reasoning?.enabled,reasoningEffort:Z,thinkingBudgetTokens:f.reasoning?.budgetTokens,region:f.region??f.aws?.region??f.gcp?.region,apiLine:f.apiLine,useCrossRegionInference:f.aws?.useCrossRegionInference,useGlobalInference:f.aws?.useGlobalInference,aws:f.aws?{accessKey:f.aws.accessKey,secretKey:f.aws.secretKey,sessionToken:f.aws.sessionToken,authentication:f.aws.authentication,profile:f.aws.profile,usePromptCache:f.aws.usePromptCache,endpoint:f.aws.endpoint,customModelBaseId:f.aws.customModelBaseId}:void 0,gcp:f.gcp?{projectId:f.gcp.projectId,region:f.gcp.region}:void 0,azure:f.azure,sap:f.sap,oca:f.oca,capabilities:f.capabilities??j?.capabilities,modelCatalog:f.modelCatalog?{loadLatestOnInit:f.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:f.modelCatalog.loadPrivateOnAuth,url:f.modelCatalog.url,cacheTtlMs:f.modelCatalog.cacheTtlMs,failOnError:f.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(R).filter(([U,y])=>y!==void 0))}function VV(f){let $=g5(f);return tf($)}function YV(f){let $=v5(f);if($.success)return{success:!0,config:tf($.data)};return{success:!1,error:$.error}}import{SESSION_STATUS_VALUES as BV}from"@cline/shared";var R6=BV,Pf={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};function u5(f){if(f===!0)return{};if(!f)return;return f}function c5(f){if(f==="user")return"global";return f}class F6{getService;constructor(f){this.getService=f}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent(f){let $=this.getService().ingestEvent(f);return{event:$.event,duplicate:$.duplicate,matchedSpecIds:$.matchedSpecs.map((J)=>J.specId),queuedRuns:$.queuedRuns,suppressions:$.suppressions}}listEvents(f){return this.getService().listEventLogs(f)}getEvent(f){return this.getService().getEventLog(f)}listSpecs(f){return this.getService().listSpecs(f)}listRuns(f){return this.getService().listRuns(f)}}function d5(f){let{host:$}=f;return{async startSession(J){let H=(J.cwd?.trim()||J.workspaceRoot).trim(),W=await $.startSession({source:J.source?.trim()||Pf.CLI,interactive:!1,config:{providerId:N2(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:H,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:FV(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:f.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(J,H){let W=await $.runTurn({sessionId:J,prompt:H.prompt,userImages:H.attachments?.userImages,userFiles:H.attachments?.userFiles?.map((Q)=>Q.content),delivery:H.delivery});if(!W)throw Error("ClineCore automation runtime returned no result");return{result:RV(W)}},async abortSession(J){return await $.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function q2(f){let $=AV(f.automationService,f.automation),J=f.context?.client??(f.clientName?{name:f.clientName}:void 0),H=f.context?.user??(f.distinctId?{distinctId:f.distinctId}:void 0),W=f.context?.logger??f.logger,Q=f.context?.telemetry??f.telemetry;if(!$&&!J&&!H&&!W&&!Q)return f.context;return{...f.context??{},...J?{client:J}:{},...H?{user:H}:{},...W?{logger:W}:{},...Q?{telemetry:Q}:{},...$?{automation:$}:{}}}function AV(f,$){if(!f)return;return{ingestEvent:(J)=>{$.ingestEvent(J)}}}function RV(f){return{text:f.text,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost},inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function FV(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}import{existsSync as FJ}from"node:fs";import{basename as H7,isAbsolute as pA,relative as iA}from"node:path";import{createHash as yV}from"node:crypto";import{watch as KV}from"node:fs";import{readdir as UV,readFile as GV}from"node:fs/promises";import{join as hV}from"node:path";function TV(f){return yV("sha1").update(f).digest("hex")}function p5(f){return Boolean(f&&typeof f==="object"&&"code"in f)}function r5(f){return p5(f)&&f.code==="ENOENT"}function l5(f){return p5(f)&&(f.code==="EACCES"||f.code==="EPERM")}class W1{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor(f,$){if(f.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=f,this.debounceMs=$?.debounceMs??75,this.emitParseErrors=$?.emitParseErrors??!1;for(let J of f){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let H of J.directories){let W=this.baseTypesByDirectory.get(H);if(W)W.add(J.type);else this.baseTypesByDirectory.set(H,new Set([J.type]))}}}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let f of this.watchersByDirectory.values())f.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let f of this.definitions)await this.refreshTypeInternal(f)})}async refreshType(f){let $=this.definitionsByType.get(f);if(!$)throw Error(`Unknown unified config type '${f}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal($)})}getSnapshot(f){let $=this.recordsByType.get(f);return new Map([...$?.entries()??[]].map(([J,H])=>[J,{...H}]))}getAllSnapshots(){let f=new Map;for(let[$,J]of this.recordsByType.entries())f.set($,new Map([...J.entries()].map(([H,W])=>[H,{...W}])));return f}emit(f){for(let $ of this.listeners)$(f)}enqueueRefresh(f){return this.refreshQueue=this.refreshQueue.then(f,f),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let f=this.buildDesiredTypesByDirectory();for(let[$,J]of this.watchersByDirectory.entries()){if(f.has($))continue;J.close(),this.watchersByDirectory.delete($)}this.watchedTypesByDirectory=f;for(let $ of f.keys()){if(this.watchersByDirectory.has($))continue;try{let J=KV($,()=>{let H=this.watchedTypesByDirectory.get($);if(!H)return;for(let W of H)this.pendingTypes.add(W);this.scheduleFlush()});this.watchersByDirectory.set($,J),J.on("error",(H)=>{let W=this.watchedTypesByDirectory.get($);if(!W)return;for(let Q of W)this.emit({kind:"error",type:Q,error:H,filePath:$})})}catch(J){if(!r5(J)&&!l5(J)){let H=f.get($);if(!H)continue;for(let W of H)this.emit({kind:"error",type:W,error:J,filePath:$})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let f=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let $ of f){let J=this.definitionsByType.get($);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal(f){let{records:$,discoveredDirectories:J}=await this.loadDefinition(f),H=this.recordsByType.get(f.type)??new Map;for(let[W,Q]of H.entries()){if($.has(W))continue;this.emit({kind:"remove",type:f.type,id:W,filePath:Q.filePath})}for(let[W,Q]of $.entries()){let Z=H.get(W);if(Z&&Z.filePath===Q.filePath&&Z.fingerprint===Q.fingerprint)continue;this.emit({kind:"upsert",record:{type:Q.type,id:W,item:Q.item,filePath:Q.filePath}})}if(this.recordsByType.set(f.type,$),this.discoveredDirectoriesByType.set(f.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition(f){let $=new Map,J=new Set;for(let H of f.directories){J.add(H);let W=f.discoverFiles?await f.discoverFiles(H):await this.readDirectoryFileCandidates(H);for(let Q of W){let{fileName:Z,filePath:j}=Q;if(J.add(Q.directoryPath),f.includeFile&&!f.includeFile(Z,j))continue;try{let P=await GV(j,"utf8"),X={type:f.type,directoryPath:Q.directoryPath,fileName:Z,filePath:j,content:P},V=f.parseFile(X),Y=f.resolveId(V,X).trim();if(!Y)continue;$.set(Y,{type:f.type,id:Y,item:V,filePath:j,fingerprint:TV(P)})}catch(P){if(this.emitParseErrors)this.emit({kind:"error",type:f.type,error:P,filePath:j})}}}return{records:$,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let f=new Map;for(let[$,J]of this.baseTypesByDirectory.entries())f.set($,new Set(J));for(let[$,J]of this.discoveredDirectoriesByType.entries())for(let H of J){let W=f.get(H);if(W)W.add($);else f.set(H,new Set([$]))}return f}async readDirectoryFileCandidates(f){try{return(await UV(f,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:f,fileName:J.name,filePath:hV(f,J.name)})).sort((J,H)=>J.fileName.localeCompare(H.fileName))}catch($){if(r5($)||l5($))return[];throw $}}}import{readdir as y6,readFile as DV,stat as i5}from"node:fs/promises";import{basename as c0,dirname as MV,extname as K6,join as Rf}from"node:path";import{RULES_CONFIG_DIRECTORY_NAME as n5,resolveRulesConfigSearchPaths as _V,resolveSkillsConfigSearchPaths as LV,resolveWorkflowsConfigSearchPaths as zV,SKILLS_CONFIG_DIRECTORY_NAME as U6,WORKFLOWS_CONFIG_DIRECTORY_NAME as G6}from"@cline/shared/storage";import OV from"yaml";var b2="SKILL.md",NV="managed.json",qV=new Set([".md",".markdown",".txt"]);function h6(f){return f.trim().toLowerCase()}function Q1(f){let $=f;return $?.code==="ENOENT"||$?.code==="EACCES"||$?.code==="EPERM"}function w2(f){return qV.has(K6(f).toLowerCase())}async function T6(f){try{let $=await y6(f,{withFileTypes:!0}),J=[];for(let H of $){if(!H.isDirectory())continue;let W=Rf(f,H.name),Q=Rf(W,NV);try{let Z=await DV(Q,"utf8"),j=JSON.parse(Z);if(j&&typeof j==="object")J.push(W)}catch(Z){if(Q1(Z))continue;if(Z?.name==="SyntaxError")continue;throw Z}}return J.sort((H,W)=>H.localeCompare(W))}catch($){if(Q1($))return[];throw $}}function D6(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,H,W]=J;try{let Q=OV.parse(H);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:W,hadFrontmatter:!0}}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);return{data:{},body:f,hadFrontmatter:!0,parseError:Z}}}function C2(f,$,J){if(f===void 0||f===null){if(J)throw Error(`Missing required frontmatter field '${$}'.`);return}if(typeof f!=="string")throw Error(`Frontmatter field '${$}' must be a string.`);let H=f.trim();if(!H&&J)throw Error(`Frontmatter field '${$}' cannot be empty.`);return H||void 0}function L$(f,$){if(f===void 0||f===null)return;if(typeof f!=="boolean")throw Error(`Frontmatter field '${$}' must be a boolean.`);return f}function M6(f,$){let{data:J,body:H,parseError:W}=D6(f);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let Q=H.trim();if(!Q)throw Error("Missing instructions body in skill file.");let j=C2(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing skill name.");return{name:j,description:C2(J.description,"description",!1),disabled:L$(J.disabled,"disabled")??(L$(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function _6(f,$){let{data:J,body:H,parseError:W}=D6(f);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let Q=H.trim();if(!Q)throw Error("Missing instructions body in rule file.");let Z=C2(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing rule name.");return{name:Z,disabled:L$(J.disabled,"disabled")??(L$(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function L6(f,$){let{data:J,body:H,parseError:W}=D6(f);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let Q=H.trim();if(!Q)throw Error("Missing instructions body in workflow file.");let Z=C2(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing workflow name.");return{name:Z,disabled:L$(J.disabled,"disabled")??(L$(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function z6(f){return LV(f)}function O6(f){return _V(f)}function N6(f){return zV(f)}async function a5(f){if(c0(f)===".cline"){let $=await T6(f);return(await Promise.all($.map((H)=>a5(Rf(H,U6))))).flat()}try{let $=await y6(f,{withFileTypes:!0}),J=[];for(let H of $){if(H.isFile()&&H.name===b2){J.push({directoryPath:f,fileName:H.name,filePath:Rf(f,H.name)});continue}if(H.isDirectory())J.push({directoryPath:Rf(f,H.name),fileName:b2,filePath:Rf(f,H.name,b2)})}return J}catch($){if(Q1($))return[];throw $}}async function E2(f){if(c0(f)===".cline"){let $=await T6(f);return(await Promise.all($.map((H)=>E2(Rf(H,"rules.md"))))).flat()}try{if((await i5(f)).isFile())return[{directoryPath:MV(f),fileName:c0(f),filePath:f}]}catch($){if(!Q1($))throw $}try{let J=(await y6(f,{withFileTypes:!0})).filter((W)=>W.isFile()&&w2(W.name)).map((W)=>({directoryPath:f,fileName:W.name,filePath:Rf(f,W.name)})),H=Rf(f,"AGENTS.md");try{if((await i5(H)).isFile()){if(!J.some((Z)=>Z.fileName==="AGENTS.md"))J.push({directoryPath:f,fileName:"AGENTS.md",filePath:H})}}catch{}return J}catch($){if(Q1($))return[];throw $}}async function bV(f){if(c0(f)===".cline"){let $=await T6(f);return(await Promise.all($.map((H)=>E2(Rf(H,G6))))).flat()}return E2(f)}function q6(f){let $=f?.directories??z6(f?.workspacePath),J=f?.workspacePath?Rf(f.workspacePath,".cline"):void 0;return{type:"skill",directories:J?[...$,J]:$,discoverFiles:a5,includeFile:(H)=>H===b2,parseFile:(H)=>M6(H.content,c0(H.directoryPath)),resolveId:(H)=>h6(H.name)}}function b6(f){let $=f?.directories??O6(f?.workspacePath),J=f?.workspacePath?Rf(f.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...$,J]:$,discoverFiles:E2,includeFile:(H,W)=>H===".clinerules"||w2(H)||w2(W),parseFile:(H)=>_6(H.content,c0(H.filePath,K6(H.filePath))),resolveId:(H)=>h6(H.name)}}function w6(f){let $=f?.directories??N6(f?.workspacePath),J=f?.workspacePath?Rf(f.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...$,J]:$,discoverFiles:bV,includeFile:(H)=>w2(H),parseFile:(H)=>L6(H.content,c0(H.filePath,K6(H.filePath))),resolveId:(H)=>h6(H.name)}}function t5(f){let $=[q6(f?.skills),b6(f?.rules),w6(f?.workflows)];return new W1($,{debounceMs:f?.debounceMs,emitParseErrors:f?.emitParseErrors})}import{truncateSplit as s5}from"@cline/shared";function wV(f,$){if(f.description?.trim())return s5(f.description,".");if($==="workflow")return;return s5(f.instructions,".")}function CV(f){return f.disabled!==!0}function o5(f,$){return[...f.getSnapshot($).entries()].map(([J,H])=>({id:J,record:H})).filter(({record:J})=>CV(J.item)).map(({id:J,record:H})=>({id:J,name:H.item.name,instructions:H.item.instructions,description:wV(H.item,$),kind:$})).sort((J,H)=>J.name.localeCompare(H.name))}function Z1(f){let $=new Map;for(let J of[...o5(f,"workflow"),...o5(f,"skill")])if(!$.has(J.name))$.set(J.name,J);return[...$.values()].sort((J,H)=>J.name.localeCompare(H.name))}function e5(f,$){if(!f.startsWith("/")||f.length<2)return f;let J=f.match(/^\/(\S+)/);if(!J)return f;let H=J[1];if(!H)return f;let W=H.length+1,Q=f.slice(W),Z=Z1($).find((j)=>j.name===H);return Z?`${Z.instructions}${Q}`:f}function f9(f){return f.disabled!==!0}function S2(f){if(f.length===0)return"";return`
|
|
44
|
+
</html>`;function AH(f){let $="";for(let J=0;J<f.length;J+=1)$+=String.fromCharCode(f[J]??0);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function ZA(f){let J=new TextEncoder().encode(f),W=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(W)}function jA(f=32){let $=new Uint8Array(f);return crypto.getRandomValues($),AH($)}async function G2(){let f=jA(),$=AH(await ZA(f));return{verifier:f,challenge:$}}function T2(f){return f.endsWith("/")?f.slice(0,-1):f}function l0(f,$){return new URL($,`${T2(f)}/`).toString()}function h$(f,$={}){let J=f.trim();if(!J)return{};try{let W=new URL(J);return{code:W.searchParams.get("code")??void 0,state:W.searchParams.get("state")??void 0,provider:$.includeProvider?W.searchParams.get("provider")??void 0:void 0}}catch{}if($.allowHashCodeState&&J.includes("#")){let[W,H]=J.split("#",2);return{code:W||void 0,state:H||void 0}}if(J.includes("code=")){let W=new URLSearchParams(J);return{code:W.get("code")??void 0,state:W.get("state")??void 0,provider:$.includeProvider?W.get("provider")??void 0:void 0}}return{code:J}}function XA(f){if(typeof atob==="function")try{return atob(f)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from(f,"base64").toString("utf8")}catch{return null}return null}function Zf(f){if(!f)return null;try{let $=f.split(".");if($.length!==3)return null;let J=$[1];if(!J)return null;let W=J.replace(/-/g,"+").replace(/_/g,"/"),H=W.padEnd(W.length+(4-W.length%4)%4,"="),Q=XA(H);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function O$(f){try{let $=JSON.parse(f),J=$.error,W=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,H=typeof $.error_description==="string"?$.error_description:typeof $.message==="string"?$.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:W,message:H}}catch{return{}}}function p0(f,$){return Date.now()>=f.expires-$}async function z$(f){if(!f.onManualCodeInput){let Q=await f.waitForCallback();return{code:Q?.code,state:Q?.state,provider:Q?.provider,error:Q?.error}}let $,J,W=f.onManualCodeInput().then((Q)=>{$=Q,f.cancelWait()}).catch((Q)=>{J=Q instanceof Error?Q:Error(String(Q)),f.cancelWait()}),H=await f.waitForCallback();if(J)throw J;if(H?.code||H?.error)return{code:H.code,state:H.state,provider:H.provider,error:H.error};if($)return h$($,f.parseOptions);if(await W,J)throw J;if($)return h$($,f.parseOptions);return{}}var D2={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},VH={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},t4="https://api.workos.com",AA="/auth",PH=Array.from({length:11},(f,$)=>48801+$),PA=300000,BA=30000,N$=30000,YA=300,VA=5;class y0 extends Error{status;errorCode;constructor(f,$){super(f);this.name="ClineOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function RA(f){let $=Date.parse(f);if(Number.isNaN($))throw Error(`Invalid expiresAt value: ${f}`);return $}function s4(f,$,J={}){let W=f.userInfo.clineUserId??J.accountId,H=f.refreshToken??J.refresh;if(!H)throw Error("Token response did not include a refresh token");return{access:f.accessToken,refresh:H,expires:RA(f.expiresAt),accountId:W??void 0,email:f.userInfo.email||J.email,metadata:{provider:$,tokenType:f.tokenType,userInfo:f.userInfo}}}async function o4(f){if(!f)return{};return typeof f==="function"?await f():f}function BH(f,$){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return $;return Math.floor(f)}async function YH(f){await new Promise(($)=>setTimeout($,f))}function e4(f,$){if(!f.success||!f.data?.accessToken)throw Error($);return f.data}async function RH(f,$){let J=await fetch(l0(t4,VH.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:f}),signal:AbortSignal.timeout($?.requestTimeoutMs??N$)}),W=await J.json().catch(()=>({}));if(!J.ok)throw new y0(`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:BH(W.expires_in,YA),pollIntervalSeconds:BH(W.interval,VA)}}async function FH(f){let $=Date.now()+f.expiresInSeconds*1000,J=Math.max(1,f.initialPollIntervalSeconds);while(Date.now()<=$){let W=await fetch(l0(f.workosApiBaseUrl,VH.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:f.deviceCode,client_id:f.clientId}),signal:AbortSignal.timeout(f.requestTimeoutMs)}),H=await W.json().catch(()=>({}));if(W.ok){if(!H.access_token||!H.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:H.access_token,refreshToken:H.refresh_token,tokenType:H.token_type??"Bearer"}}switch(H.error){case"authorization_pending":{await YH(J*1000);break}case"slow_down":{J+=1,await YH(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new y0(H.error_description||"WorkOS authorization failed",{status:W.status,errorCode:H.error});default:throw new y0(`WorkOS token polling failed: ${W.status}${H.error_description?` - ${H.error_description}`:""}`,{status:W.status,errorCode:H.error})}f.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function KH(f,$,J){let W={accessToken:f.accessToken,refreshToken:f.refreshToken},H=await fetch(l0($.apiBaseUrl,D2.register),{method:"POST",headers:{"Content-Type":"application/json",...await o4($.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout($.requestTimeoutMs??N$)});if(!H.ok){let Z=await H.text().catch(()=>""),j=O$(Z);throw new y0(`Token registration failed: ${H.status}${j.message?` - ${j.message}`:""}`,{status:H.status,errorCode:j.code})}let Q=await H.json();return s4(e4(Q,"Invalid token exchange response"),J??$.provider)}async function FA(f,$,J,W){let H={grant_type:"authorization_code",code:f,client_type:"extension",redirect_uri:$,provider:W??J.provider},Q=await fetch(l0(J.apiBaseUrl,D2.token),{method:"POST",headers:{"Content-Type":"application/json",...await o4(J.headers)},body:JSON.stringify(H),signal:AbortSignal.timeout(J.requestTimeoutMs??N$)});if(!Q.ok){let j=await Q.text().catch(()=>""),X=O$(j);throw new y0(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let Z=await Q.json();return s4(e4(Z,"Invalid token exchange response"),W??J.provider)}async function _2(f){V0(f.telemetry,f.provider??"cline");let $=f.useWorkOSDeviceAuth??!0,J=f.callbackPorts?.length?f.callbackPorts:PH,W=f.callbackPath??AA,H=$?null:await r0({ports:J,callbackPath:W,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),Q=H?.callbackUrl||`http://127.0.0.1:${J[0]??PH[0]}${W}`;try{let Z;if($){let j=a4().workOsClientId,X=await RH(j,f);f.callbacks.onAuth({url:X.verificationUriComplete??X.verificationUri,instructions:`Enter this code in your browser: ${X.userCode}`});let A=await FH({clientId:j,deviceCode:X.deviceCode,expiresInSeconds:X.expiresInSeconds,initialPollIntervalSeconds:X.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??N$,workosApiBaseUrl:t4,onProgress:f.callbacks.onProgress});Z=await KH(A,f,f.provider)}else{let j=new URL(l0(f.apiBaseUrl,D2.authorize));j.searchParams.set("client_type","extension"),j.searchParams.set("callback_url",Q),j.searchParams.set("redirect_uri",Q),f.callbacks.onAuth({url:j.toString(),instructions:"Continue the authentication process in your browser."});let X,A=f.provider,P=await z$({waitForCallback:H?.waitForCallback??(async()=>null),cancelWait:H?.cancelWait??(()=>{}),onManualCodeInput:f.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(P.error)throw Error(`OAuth error: ${P.error}`);if(X=P.code,A=P.provider??A,!X){let B=await f.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),Y=h$(B,{includeProvider:!0});X=Y.code,A=Y.provider??A}if(!X)throw Error("Missing authorization code");Z=await FA(X,Q,f,A)}return R0(f.telemetry,f.provider??"cline"),K0(f.telemetry,{id:Z.accountId,email:Z.email,provider:f.provider??"cline"}),Z}catch(Z){throw F0(f.telemetry,f.provider??"cline",Z instanceof Error?Z.message:String(Z)),Z}finally{H?.close()}}async function KA(f){return await RH(a4().workOsClientId,f)}async function yA(f){let $=f.provider??"cline";V0(f.telemetry,$);try{let J=await FH({clientId:a4().workOsClientId,deviceCode:f.deviceCode,expiresInSeconds:f.expiresInSeconds,initialPollIntervalSeconds:f.pollIntervalSeconds,requestTimeoutMs:f.requestTimeoutMs??N$,workosApiBaseUrl:t4}),W=await KH(J,{apiBaseUrl:f.apiBaseUrl,headers:f.headers,requestTimeoutMs:f.requestTimeoutMs,provider:f.provider},f.provider);return R0(f.telemetry,$),K0(f.telemetry,{id:W.accountId,email:W.email,provider:$}),W}catch(J){throw F0(f.telemetry,$,J instanceof Error?J.message:String(J)),J}}async function f6(f,$){let J=await fetch(l0($.apiBaseUrl,D2.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await o4($.headers)},body:JSON.stringify({refreshToken:f.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout($.requestTimeoutMs??N$)});if(!J.ok){let Q=await J.text().catch(()=>""),Z=O$(Q);throw new y0(`Token refresh failed: ${J.status}${Z.message?` - ${Z.message}`:""}`,{status:J.status,errorCode:Z.code})}let W=await J.json(),H=f.metadata?.provider??$.provider;return s4(e4(W,"Invalid token refresh response"),H,f)}async function $6(f,$,J){if(!f)return null;let W=J?.refreshBufferMs??PA,H=J?.retryableTokenGraceMs??BA;if(J?.forceRefresh!==!0&&!p0(f,W))return f;try{return await f6(f,$)}catch(Z){if(Z instanceof y0&&Z.isLikelyInvalidGrant())return c0($.telemetry,$.provider??"cline","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function UA(f){return{id:"cline",name:"Cline Account",usesCallbackServer:!(f.useWorkOSDeviceAuth??!0),async login($){return _2({...f,callbacks:$})},async refreshToken($){return f6($,f)},getApiKey($){return`workos:${$.access}`}}}Uf();import{nanoid as GA}from"nanoid";var t={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 M2 extends Error{status;errorCode;constructor(f,$){super(f);this.name="OpenAICodexOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function TA(f,$,J=t.redirectUri){let W=await fetch(t.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,code:f,code_verifier:$,redirect_uri:J}),signal:AbortSignal.timeout(t.httpTimeoutMs)});if(!W.ok)return{type:"failed"};let H=await W.json();if(!H.access_token||!H.refresh_token||typeof H.expires_in!=="number")return{type:"failed"};return{type:"success",access:H.access_token,refresh:H.refresh_token,expires:Date.now()+H.expires_in*1000,email:H.email,idToken:H.id_token}}async function DA(f){try{let $=await fetch(t.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:f,client_id:t.clientId}),signal:AbortSignal.timeout(t.httpTimeoutMs)});if(!$.ok){let W=await $.text().catch(()=>""),H=O$(W);throw new M2(`Token refresh failed: ${$.status}${H.message?` - ${H.message}`:""}`,{status:$.status,errorCode:H.code})}let J=await $.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch($){if($ instanceof M2)throw $;return{type:"failed"}}}async function _A(f="pi"){let{verifier:$,challenge:J}=await G2(),W=GA(32),H=new URL(t.authorizationEndpoint);return H.searchParams.set("response_type","code"),H.searchParams.set("client_id",t.clientId),H.searchParams.set("redirect_uri",t.redirectUri),H.searchParams.set("scope",t.scopes),H.searchParams.set("code_challenge",J),H.searchParams.set("code_challenge_method","S256"),H.searchParams.set("state",W),H.searchParams.set("id_token_add_organizations","true"),H.searchParams.set("codex_cli_simplified_flow","true"),H.searchParams.set("originator",f),{verifier:$,state:W,url:H.toString()}}function MA(){try{let f=new URL(t.redirectUri),$=f.port.length>0?Number.parseInt(f.port,10):t.callbackPort;return{host:f.hostname||"localhost",port:Number.isFinite($)?$:t.callbackPort,callbackPath:f.pathname||"/auth/callback",redirectUri:f.toString()}}catch{return{host:"localhost",port:t.callbackPort,callbackPath:"/auth/callback",redirectUri:t.redirectUri}}}function yH(f,$){let J=$?Zf($):Zf(f),W=J?J:Zf(f),Q=W?.[t.jwtClaimPath]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=W?.organizations;if(Array.isArray(Z)&&Z.length>0){let X=Z[0];if(typeof X?.id==="string"&&X.id.length>0)return X.id}let j=W?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return null}function UH(f,$){let J=yH(f.access,f.idToken)??$?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:f.access,refresh:f.refresh||$?.refresh||"",expires:f.expires,accountId:J,email:f.email??$?.email,metadata:{...$?.metadata??{},provider:"openai-codex"}}}async function L2(f){V0(f.telemetry,"openai-codex");let $=MA(),{verifier:J,state:W,url:H}=await _A(f.originator),Q=await r0({host:$.host,ports:[$.port],callbackPath:$.callbackPath,expectedState:W});f.onAuth({url:H,instructions:"Continue the authentication process in your browser."});let Z;try{let j=await z$({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:f.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(j.state&&j.state!==W)throw Error("State mismatch");if(Z=j.code,!Z){let P=await f.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=h$(P,{allowHashCodeState:!0});if(B.state&&B.state!==W)throw Error("State mismatch");Z=B.code}if(!Z)throw Error("Missing authorization code");let X=await TA(Z,J,$.redirectUri);if(X.type!=="success")throw Error("Token exchange failed");let A=UH(X);return R0(f.telemetry,"openai-codex"),K0(f.telemetry,{id:A.accountId,email:A.email,provider:"openai-codex"}),A}catch(j){throw F0(f.telemetry,"openai-codex",j instanceof Error?j.message:String(j)),j}finally{Q.close()}}async function J6(f,$){let J=await DA(f);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=UH(J,$);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function W6(f,$){if(!f)return null;let J=$?.refreshBufferMs??t.refreshBufferMs,W=$?.retryableTokenGraceMs??t.retryableTokenGraceMs;if($?.forceRefresh!==!0&&!p0(f,J))return f;try{return await J6(f.refresh,f)}catch(Q){if(Q instanceof M2&&Q.isLikelyInvalidGrant())return c0($?.telemetry,"openai-codex","invalid_grant"),null;if(f.expires-Date.now()>W)return f;return null}}function LA(f,$=t.refreshBufferMs){return p0(f,$)}function hA(f){let $=f.accountId??yH(f.access);if(!$)throw Error("Failed to extract accountId from token");return{...f,accountId:$,metadata:{...f.metadata??{},provider:"openai-codex"}}}var OA={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login(f){return L2({onAuth:f.onAuth,onPrompt:f.onPrompt,onProgress:f.onProgress,onManualCodeInput:f.onManualCodeInput})},async refreshToken(f){return J6(f.refresh,f)},getApiKey(f){return f.access}};Uf();import{nanoid as GH}from"nanoid";class H6{ttlMs;maxEntries;entries=new Map;constructor(f,$){this.ttlMs=f;this.maxEntries=$}get(f,$=Date.now()){this.pruneExpired($);let J=this.entries.get(f);if(!J)return;return this.entries.delete(f),this.entries.set(f,J),J.value}set(f,$,J=Date.now(),W=this.ttlMs){this.pruneExpired(J),this.entries.delete(f);while(this.entries.size>=this.maxEntries){let H=this.entries.keys().next().value;if(H===void 0)break;this.entries.delete(H)}this.entries.set(f,{value:$,expiresAt:J+W})}pruneExpired(f){for(let[$,J]of this.entries)if(J.expiresAt<=f)this.entries.delete($)}}var zA="a8331954c0cf48ba99b5dd223a14c6ea",NA="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",qA="openid offline_access",Z6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",wA="c1aba3deed5740659981a752714eba33",bA="https://login-ext.identity.oraclecloud.com",CA="openid offline_access",j6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",EA="opc-request-id",SA="/auth/oca",kA=Array.from({length:11},(f,$)=>48801+$),IA=300000,mA=30000,TH=30000,xA=600000;class h2 extends Error{status;errorCode;constructor(f,$){super(f);this.name="OcaOAuthTokenError",this.status=$?.status,this.errorCode=$?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var U0={internal:{clientId:zA,idcsUrl:NA,scopes:qA,baseUrl:Z6},external:{clientId:wA,idcsUrl:bA,scopes:CA,baseUrl:j6}},Z1=new Map,gA=86400000,vA=300000,uA=32,Q6=new H6(gA,uA);function DH(f){if(typeof f==="function")return f();return f??"internal"}function _H(f){return{internal:{clientId:f?.internal?.clientId??U0.internal.clientId,idcsUrl:f?.internal?.idcsUrl??U0.internal.idcsUrl,scopes:f?.internal?.scopes??U0.internal.scopes,baseUrl:f?.internal?.baseUrl??U0.internal.baseUrl},external:{clientId:f?.external?.clientId??U0.external.clientId,idcsUrl:f?.external?.idcsUrl??U0.external.idcsUrl,scopes:f?.external?.scopes??U0.external.scopes,baseUrl:f?.external?.baseUrl??U0.external.baseUrl}}}function cA(f=Date.now()){let $=f-xA;for(let[J,W]of Z1.entries())if(W.createdAt<$)Z1.delete(J)}function dA(f,$,J){if(typeof f.expires_in==="number"&&f.expires_in>0)return Date.now()+f.expires_in*1000;let H=Zf($)?.exp;if(typeof H==="number"&&H>0)return H*1000;let Z=Zf(J)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return Date.now()+3600000}function MH(f,$,J){let W=f.access_token;if(!W)throw Error("Token response did not include an access token");let H=f.refresh_token??J?.refresh;if(!H)throw Error("Token response did not include a refresh token");let Q=Zf(f.id_token),Z=Zf(W),j=Q?.sub??Z?.sub,X=Q?.email??Z?.email;return{access:W,refresh:H,expires:dA(f,W,f.id_token),accountId:j??J?.accountId,email:X??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:$,subject:j,idToken:f.id_token}}}async function LH(f,$){let J=T2(f),W=Q6.get(J);if(W)return W;let H=`${J}/.well-known/openid-configuration`,Q=await fetch(H,{method:"GET",signal:AbortSignal.timeout($)});if(!Q.ok){let X=`${J}/oauth2/v1/token`;return Q6.set(J,X,Date.now(),vA),X}let j=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return Q6.set(J,j),j}function hH(f){return{code:f.error,message:f.error_description}}async function rA(f){let $=Z1.get(f.state);if(!$)throw Error("No PKCE verifier found for this state");Z1.delete(f.state);let J=f.mode==="external"?f.config.external:f.config.internal,W=await LH(J.idcsUrl,f.requestTimeoutMs),H=new URLSearchParams({grant_type:"authorization_code",code:f.code,redirect_uri:$.redirectUri,client_id:J.clientId,code_verifier:$.verifier}),Q=await fetch(W,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H,signal:AbortSignal.timeout(f.requestTimeoutMs)}),Z=await Q.json();if(!Q.ok){let X=hH(Z);throw new h2(`Token exchange failed: ${Q.status}${X.message?` - ${X.message}`:""}`,{status:Q.status,errorCode:X.code})}let j=Zf(Z.id_token);if(!Z.id_token||!j)throw Error("No ID token received from OCA");if(j.nonce!==$.nonce)throw Error("OIDC nonce verification failed");return MH(Z,f.mode)}function lA(f){let $=f.mode==="external"?f.config.external:f.config.internal,J=new URL(`${T2($.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",$.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",$.scopes),J.searchParams.set("code_challenge",f.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",f.callbackUrl),J.searchParams.set("state",f.state),J.searchParams.set("nonce",f.nonce),J.toString()}async function O2(f){V0(f.telemetry,"oca");let $=_H(f.config),J=DH(f.mode),W=f.callbackPorts?.length?f.callbackPorts:kA,H=f.callbackPath??SA,Q=f.requestTimeoutMs??TH,Z=await r0({ports:W,callbackPath:H,onListening:f.callbacks.onServerListening,onClose:f.callbacks.onServerClose}),j=Z.callbackUrl;if(!j)throw Error("Unable to bind local OAuth callback server");let X=GH(16),A=GH(16),{verifier:P,challenge:B}=await G2();cA(),Z1.set(X,{verifier:P,nonce:A,mode:J,redirectUri:j,createdAt:Date.now()});let Y=lA({callbackUrl:j,mode:J,state:X,nonce:A,challenge:B,config:$});f.callbacks.onAuth({url:Y,instructions:"Continue the authentication process in your browser."});try{let V=await z$({waitForCallback:Z.waitForCallback,cancelWait:Z.cancelWait,onManualCodeInput:f.callbacks.onManualCodeInput}),R=V.code,U=V.state;if(V.error)throw Error(`OAuth error: ${V.error}`);if(!R){if(!f.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!U||U!==X)throw Error("State mismatch");let K=await rA({code:R,state:U,mode:J,config:$,requestTimeoutMs:Q});return R0(f.telemetry,"oca"),K0(f.telemetry,{id:K.accountId,email:K.email,provider:"oca"}),K}catch(V){throw F0(f.telemetry,"oca",V instanceof Error?V.message:String(V)),V}finally{Z.close()}}async function X6(f,$={}){let J=_H($.config),W=$.requestTimeoutMs??TH,H=f.metadata?.mode,Q=H==="internal"||H==="external"?H:DH($.mode),Z=Q==="external"?J.external:J.internal,j=await LH(Z.idcsUrl,W),X=new URLSearchParams({grant_type:"refresh_token",refresh_token:f.refresh,client_id:Z.clientId}),A=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:X,signal:AbortSignal.timeout(W)}),P=await A.json();if(!A.ok){let B=hH(P);throw new h2(`Token refresh failed: ${A.status}${B.message?` - ${B.message}`:""}`,{status:A.status,errorCode:B.code})}return MH(P,Q,f)}async function A6(f,$,J){if(!f)return null;let W=$?.refreshBufferMs??J?.refreshBufferMs??IA,H=$?.retryableTokenGraceMs??J?.retryableTokenGraceMs??mA;if($?.forceRefresh!==!0&&!p0(f,W))return f;try{return await X6(f,J)}catch(Z){if(Z instanceof h2&&Z.isLikelyInvalidGrant())return c0(J?.telemetry,"oca","invalid_grant"),null;if(f.expires-Date.now()>H)return f;return null}}function pA(f={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login($){return O2({...f,callbacks:$})},async refreshToken($){return X6($,f)},getApiKey($){return $.access}}}async function OH(f,$){let J=new TextEncoder,W=async(A)=>{let P=await crypto.subtle.digest("SHA-256",J.encode(A));return Array.from(new Uint8Array(P).slice(0,4),(B)=>B.toString(16).padStart(2,"0")).join("")},[H,Q]=await Promise.all([W($),W(f)]),Z=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),j=new Uint32Array(1);crypto.getRandomValues(j);let X=(j[0]??0).toString(16).padStart(8,"0");return H+Q+Z+X}async function iA(f){let $=await OH(f.taskId,f.accessToken);return{Authorization:`Bearer ${f.accessToken}`,"Content-Type":"application/json",client:f.metadata?.client??"Cline","client-version":f.metadata?.clientVersion??"unknown","client-ide":f.metadata?.clientIde??"unknown","client-ide-version":f.metadata?.clientIdeVersion??"unknown",[EA]:$}}import*as hf from"@cline/llms";import{z as h}from"zod";import*as s from"@cline/llms";function P6(f){if(!Array.isArray(f))return[];return f.map(($)=>{if(typeof $==="string")return $.trim();if($&&typeof $==="object"){let J=$;for(let W of[J.id,J.name,J.model])if(typeof W==="string"&&W.trim())return W.trim()}return""}).filter(($)=>$.length>0)}function nA(f,$){let J=P6(f);if(J.length>0)return J;if(!f||typeof f!=="object")return[];let W=f,H=P6(W.data??W.models);if(H.length>0)return H;if(W.models&&typeof W.models==="object"&&!Array.isArray(W.models)){let Z=Object.keys(W.models).filter((j)=>j.trim().length>0);if(Z.length>0)return Z}let Q=W.providers?.[$];if(Q&&typeof Q==="object"){let j=P6(Q.models??Q);if(j.length>0)return j}return[]}async function z2(f,$){let J=await fetch(f,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${f}: HTTP ${J.status}`);return nA(await J.json(),$)}function zH(f){return f.replace(/\/+$/,"")}function N2(f,$,J){let W=J?.trim();if(!W)return;let H=f?.trim();if(!H||!$?.trim())return W;try{let Q=new URL(W),Z=new URL($),j=new URL(H);if(Q.origin!==Z.origin)return W;let X=zH(Z.pathname),A=zH(j.pathname);if(X&&Q.pathname.startsWith(`${X}/`)){let P=Q.pathname.slice(X.length);j.pathname=`${A}${P}`}else j.pathname=Q.pathname;return j.search=Q.search,j.hash=Q.hash,j.toString()}catch{return W}}function aA(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{...J}]))}function tA(f){if(f.baseUrl.length===0)return!1;switch(f.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return f.protocol==="openai-chat"}}var sA=Object.values(s.MODEL_COLLECTIONS_BY_PROVIDER_ID).map((f)=>({id:f.provider.id,baseUrl:f.provider.baseUrl??"",modelsSourceUrl:f.provider.modelsSourceUrl,modelId:f.provider.defaultModelId,knownModels:aA(f.models),capabilities:f.provider.capabilities?[...f.provider.capabilities]:void 0,env:f.provider.env?[...f.provider.env]:void 0,client:f.provider.client,protocol:f.provider.protocol})),qH=Object.fromEntries(sA.map((f)=>[f.id,f]));function oA(f){return qH[f]}function eA(){return Object.fromEntries(Object.entries(qH).filter(([,f])=>tA(f)))}function wH(f=[]){let $=f.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return $.length>0?$:void 0}var bH="https://models.dev/api.json",fP=600000,CH=300000,$P=5000,w2=new Map,j1=new Map,V6=new Map,q2=new Map;async function JP(){return s.getGeneratedProviderModels()}async function WP(f,$={},J={},W={},H={},Q={}){let Z=await JP(),j=s.resolveProviderModelCatalogKeys(f),X=Object.assign({},...j.map((Y)=>Z[Y]??{})),A=Boolean(s.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl),P=Object.keys(H).length>0;if(A&&P)return s.sortModelsByReleaseDate({...H,...Q});let B=Object.keys(W).length>0;if(f==="openai-codex"&&B)return s.sortModelsByReleaseDate({...W,...Q});return s.sortModelsByReleaseDate({...X,...$,...J,...W,...H,...Q})}function HP(f,$){let J=s.resolveProviderModelCatalogKeys(f);return Object.assign({},...J.map((W)=>$[W]??{}))}function R6(f){let $=f?.trim();return $&&$.length>0?$:""}function F6(f){let $=f.apiKey?.trim()||f.accessToken?.trim();return $&&$.length>0?$:void 0}function QP(f){let $=2166136261;for(let J=0;J<f.length;J+=1)$^=f.charCodeAt(J),$+=($<<1)+($<<4)+($<<7)+($<<8)+($<<24);return($>>>0).toString(16)}function ZP(f,$){return`${f}:${R6($.baseUrl)}:${QP(F6($)??"")}`}function jP(f){let $=f?.trim();if(!$)return;let J=Zf($),W=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let H=J?.organizations?.[0]?.id;if(typeof H==="string"&&H.length>0)return H;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}async function K6(f,$,J=$P){let W=new AbortController,H=setTimeout(()=>W.abort(),J);try{return await fetch(f,{...$,signal:W.signal})}finally{clearTimeout(H)}}function B6(f,$,J){if(J&&!f.includes($))f.push($)}function X1(f,$){let J=["streaming","tools"];return B6(J,"images",Boolean($.supportsImages)),B6(J,"prompt-cache",Boolean($.supportsPromptCache)),B6(J,"reasoning",Boolean($.supportsReasoning)),{id:f,name:$.name??f,contextWindow:$.contextWindow,maxTokens:$.maxTokens,capabilities:J,releaseDate:$.releaseDate,status:"active"}}function XP(f){let $=s.getGeneratedModelsForProvider("openai")[f.id];if($)return{...$,id:f.id,name:f.name??$.name??f.id};return X1(f.id,{name:f.name??f.id})}async function AP(f,$){let J=await K6("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${$}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let H=(await J.json())?.data??[],Q={};for(let Z of H){let j=Z.id?.trim();if(!j)continue;if(j.includes("whisper")||j.includes("tts")||j.includes("embedding"))continue;let X=Z.supported_features??[];Q[j]=X1(j,{name:j,contextWindow:Z.context_length,maxTokens:Z.max_completion_tokens,supportsReasoning:X.includes("reasoning")||X.includes("reasoning_effort"),supportsImages:!1})}return Q}async function PP(f,$){let J=await K6("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":$}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let H=(await J.json())?.data??[],Q={};for(let Z of H){let j=Z.id?.trim();if(!j)continue;Q[j]=X1(j,{name:j,contextWindow:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}function BP(f){let $=R6(f);if(!$)return"http://localhost:4000";return $.endsWith("/v1")?$.slice(0,-3):$}async function YP(f,$){let W=`${BP(f.baseUrl)}/v1/model/info`,H=async(A)=>K6(W,{method:"GET",headers:{accept:"application/json",...A}}),Q=await H({"x-litellm-api-key":$});if(!Q.ok)Q=await H({Authorization:`Bearer ${$}`});if(!Q.ok)throw Error(`LiteLLM model refresh failed: HTTP ${Q.status}`);let j=(await Q.json())?.data??[],X={};for(let A of j){let P=A.model_name?.trim(),Y=A.litellm_params?.model?.trim()||P;if(!Y)continue;let V=A.model_info,R=X1(Y,{name:P??Y,maxTokens:V?.max_output_tokens??V?.max_tokens,contextWindow:V?.max_input_tokens??V?.max_tokens,supportsImages:V?.supports_vision,supportsPromptCache:V?.supports_prompt_caching,supportsReasoning:V?.supports_reasoning});if(X[Y]=R,P)X[P]={...R,id:P,name:P}}return X}async function VP(f,$){let J=await s.listOpenAICodexModels({accessToken:$,accountId:f.accountId??jP($),cwd:typeof f.codex?.defaultSettings?.cwd==="string"?f.codex.defaultSettings.cwd:void 0,codexPath:typeof f.codex?.defaultSettings?.codexPath==="string"?f.codex.defaultSettings.codexPath:void 0,env:f.codex?.defaultSettings?.env&&typeof f.codex.defaultSettings.env==="object"&&!Array.isArray(f.codex.defaultSettings.env)?f.codex.defaultSettings.env:void 0});return Object.fromEntries(J.map((W)=>[W.id,XP(W)]))}var EH={baseten:AP,hicap:PP,litellm:YP,"openai-codex":VP},NH=new Map,Y6=new Map;function RP(f,$){return`${f}:${R6($.baseUrl)}`}async function FP(f,$,J){let W=s.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],H=N2(J.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!H)return{};let Q=$?.cacheTtlMs??CH,Z=RP(f,J),j=Date.now(),X=NH.get(Z);if(X&&X.expiresAt>j)return X.data;let A=Y6.get(Z);if(A)return A;let P=z2(H,f).then((B)=>{let Y=Object.fromEntries(B.map((V)=>[V,X1(V,{name:V})]));return NH.set(Z,{data:Y,expiresAt:j+Q}),Y}).finally(()=>{Y6.delete(Z)});return Y6.set(Z,P),P}async function KP(f,$){let J=F6($);if(!J)return{};let W=EH[f];if(!W)return{};return W($,J)}function yP(f,$,J){if(!J)return!1;if(!EH[f])return!1;if($?.loadPrivateOnAuth===!1)return!1;return Boolean(F6(J))}async function UP(f,$,J){let W=$?.cacheTtlMs??CH,H=ZP(f,J),Q=Date.now(),Z=V6.get(H);if(Z&&Z.expiresAt>Q)return Z.data;let j=q2.get(H);if(j)return j;let X=KP(f,J).then((A)=>{return V6.set(H,{data:A,expiresAt:Q+W}),A}).finally(()=>{q2.delete(H)});return q2.set(H,X),X}async function GP(f){return s.fetchModelsDevProviderModels(f)}async function b2(f={}){let $=f.url??bH,J=f.cacheTtlMs??fP,W=Date.now(),H=w2.get($);if(H&&H.expiresAt>W)return H.data;let Q=j1.get($);if(Q)return Q;let Z=GP($).then((j)=>{return w2.set($,{data:j,expiresAt:W+J}),j}).finally(()=>{j1.delete($)});return j1.set($,Z),Z}function TP(f){if(f){w2.delete(f),j1.delete(f);return}w2.clear(),j1.clear()}function DP(){V6.clear(),q2.clear()}function _P(f){return Object.fromEntries(Object.entries(f).map(([$,J])=>[$,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:wH(J.capabilities)}]))}var y6=_P(eA());function SH(f){let $=oA(f);if(!$||!$.baseUrl)return;return{baseUrl:$.baseUrl,modelId:$.modelId,knownModels:$.knownModels,capabilities:wH($.capabilities)}}async function U6(f,$,J){let W=SH(f);if(!W)return;try{let H=$?.loadLatestOnInit?await b2($):void 0,Q=H?HP(f,H):{},Z=J&&yP(f,$,J)?await UP(f,$,J):{},X=Boolean(s.MODEL_COLLECTIONS_BY_PROVIDER_ID[f]?.provider.modelsSourceUrl)?J??{providerId:f,modelId:W.modelId,baseUrl:W.baseUrl}:J,A=X?await FP(f,$,X).catch(()=>({})):{},P=await WP(f,W.knownModels,Q,Z,A,J?.knownModels);return{...W,knownModels:P}}catch(H){if($?.failOnError)throw H;return W}}var G6=hf.BUILT_IN_PROVIDER,MP=hf.BUILT_IN_PROVIDER_IDS,LP=hf.isBuiltInProviderId,C2=hf.normalizeProviderId,T6=h.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),kH=h.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),IH=h.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),mH=h.object({apiKey:h.string().optional(),accessToken:h.string().optional(),refreshToken:h.string().optional(),expiresAt:h.number().int().positive().optional(),accountId:h.string().optional()}),hP=h.enum(["none","low","medium","high","xhigh"]),xH=h.object({enabled:h.boolean().optional(),effort:hP.optional(),budgetTokens:h.number().int().positive().optional()}),gH=h.object({accessKey:h.string().optional(),secretKey:h.string().optional(),sessionToken:h.string().optional(),region:h.string().optional(),profile:h.string().optional(),authentication:h.enum(["iam","api-key","profile"]).optional(),usePromptCache:h.boolean().optional(),useCrossRegionInference:h.boolean().optional(),useGlobalInference:h.boolean().optional(),endpoint:h.string().url().optional(),customModelBaseId:h.string().optional()}),vH=h.object({projectId:h.string().optional(),region:h.string().optional()}),uH=h.object({apiVersion:h.string().optional(),useIdentity:h.boolean().optional()}),cH=h.object({clientId:h.string().optional(),clientSecret:h.string().optional(),tokenUrl:h.string().url().optional(),resourceGroup:h.string().optional(),deploymentId:h.string().optional(),useOrchestrationMode:h.boolean().optional(),api:h.enum(["orchestration","foundation-models"]).optional(),defaultSettings:h.record(h.string(),h.unknown()).optional()}),dH=h.object({mode:h.enum(["internal","external"]).optional(),usePromptCache:h.boolean().optional()}),rH=h.object({loadLatestOnInit:h.boolean().optional(),loadPrivateOnAuth:h.boolean().optional(),url:h.string().url().optional(),cacheTtlMs:h.number().int().positive().optional(),failOnError:h.boolean().optional()}),q$=h.object({provider:T6,apiKey:h.string().optional(),auth:mH.optional(),model:h.string().optional(),protocol:kH.optional(),client:IH.optional(),routingProviderId:T6.optional(),maxTokens:h.number().int().positive().optional(),contextWindow:h.number().int().positive().optional(),baseUrl:h.string().url().optional(),headers:h.record(h.string(),h.string()).optional(),timeout:h.number().int().positive().optional(),reasoning:xH.optional(),aws:gH.optional(),gcp:vH.optional(),azure:uH.optional(),sap:cH.optional(),oca:dH.optional(),region:h.string().optional(),apiLine:h.enum(["china","international"]).optional(),capabilities:h.array(h.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth"])).optional(),modelCatalog:rH.optional()});function lH(f){return q$.parse(f)}function pH(f){return q$.safeParse(f)}function OP(f){return f.protocol==="openai-responses"||f.client==="openai"}function f0(f,$={}){let J=f.provider,W=C2(J),H=$.includeKnownModels!==!1,Q=f.reasoning?.effort||"none",Z=Q==="none"?void 0:Q,j=y6[W],X=Object.assign({},...hf.resolveProviderModelCatalogKeys(W).map((U)=>hf.getGeneratedModelsForProvider(U))),A=Object.keys(X)[0],P=f.auth?.accessToken??f.apiKey??f.auth?.apiKey,B=f.baseUrl??(W==="oca"?f.oca?.mode==="internal"?Z6:j6:j?.baseUrl),Y=f.routingProviderId??(OP(f)&&W!==G6.OPENAI_NATIVE?G6.OPENAI_NATIVE:void 0),V=H?j?.knownModels??(Object.keys(X).length>0?X:void 0):void 0,R={providerId:J,clientType:f.client,routingProviderId:Y,modelId:f.model??j?.modelId??A??"default",...H?{knownModels:V}:{},apiKey:P,accessToken:f.auth?.accessToken,refreshToken:f.auth?.refreshToken,accountId:f.auth?.accountId,baseUrl:B,headers:f.headers,timeoutMs:f.timeout,maxOutputTokens:f.maxTokens,maxContextTokens:f.contextWindow,thinking:f.reasoning?.enabled,reasoningEffort:Z,thinkingBudgetTokens:f.reasoning?.budgetTokens,region:f.region??f.aws?.region??f.gcp?.region,apiLine:f.apiLine,useCrossRegionInference:f.aws?.useCrossRegionInference,useGlobalInference:f.aws?.useGlobalInference,aws:f.aws?{accessKey:f.aws.accessKey,secretKey:f.aws.secretKey,sessionToken:f.aws.sessionToken,authentication:f.aws.authentication,profile:f.aws.profile,usePromptCache:f.aws.usePromptCache,endpoint:f.aws.endpoint,customModelBaseId:f.aws.customModelBaseId}:void 0,gcp:f.gcp?{projectId:f.gcp.projectId,region:f.gcp.region}:void 0,azure:f.azure,sap:f.sap,oca:f.oca,capabilities:f.capabilities??j?.capabilities,modelCatalog:f.modelCatalog?{loadLatestOnInit:f.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:f.modelCatalog.loadPrivateOnAuth,url:f.modelCatalog.url,cacheTtlMs:f.modelCatalog.cacheTtlMs,failOnError:f.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(R).filter(([U,K])=>K!==void 0))}function zP(f){let $=lH(f);return f0($)}function NP(f){let $=pH(f);if($.success)return{success:!0,config:f0($.data)};return{success:!1,error:$.error}}import{SESSION_STATUS_VALUES as qP}from"@cline/shared";var D6=qP,Rf={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"};function iH(f){if(f===!0)return{};if(!f)return;return f}function nH(f){if(f==="user")return"global";return f}class _6{getService;constructor(f){this.getService=f}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent(f){let $=this.getService().ingestEvent(f);return{event:$.event,duplicate:$.duplicate,matchedSpecIds:$.matchedSpecs.map((J)=>J.specId),queuedRuns:$.queuedRuns,suppressions:$.suppressions}}listEvents(f){return this.getService().listEventLogs(f)}getEvent(f){return this.getService().getEventLog(f)}listSpecs(f){return this.getService().listSpecs(f)}listRuns(f){return this.getService().listRuns(f)}}function aH(f){let{host:$}=f;return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),H=await $.startSession({source:J.source?.trim()||Rf.CLI,interactive:!1,config:{providerId:C2(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:CP(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:f.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:H.sessionId,startResult:{sessionId:H.sessionId,manifestPath:H.manifestPath,messagesPath:H.messagesPath}}},async sendSession(J,W){let H=await $.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content),delivery:W.delivery});if(!H)throw Error("ClineCore automation runtime returned no result");return{result:bP(H)}},async abortSession(J){return await $.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function E2(f){let $=wP(f.automationService,f.automation),J=f.context?.client??(f.clientName?{name:f.clientName}:void 0),W=f.context?.user??(f.distinctId?{distinctId:f.distinctId}:void 0),H=f.context?.logger??f.logger,Q=f.context?.telemetry??f.telemetry;if(!$&&!J&&!W&&!H&&!Q)return f.context;return{...f.context??{},...J?{client:J}:{},...W?{user:W}:{},...H?{logger:H}:{},...Q?{telemetry:Q}:{},...$?{automation:$}:{}}}function wP(f,$){if(!f)return;return{ingestEvent:(J)=>{$.ingestEvent(J)}}}function bP(f){return{text:f.text,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost},inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function CP(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}import{existsSync as LJ}from"node:fs";import{basename as PQ,isAbsolute as VR,relative as RR}from"node:path";import{createHash as EP}from"node:crypto";import{watch as SP}from"node:fs";import{readdir as kP,readFile as IP}from"node:fs/promises";import{join as mP}from"node:path";function xP(f){return EP("sha1").update(f).digest("hex")}function oH(f){return Boolean(f&&typeof f==="object"&&"code"in f)}function tH(f){return oH(f)&&f.code==="ENOENT"}function sH(f){return oH(f)&&(f.code==="EACCES"||f.code==="EPERM")}class A1{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor(f,$){if(f.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=f,this.debounceMs=$?.debounceMs??75,this.emitParseErrors=$?.emitParseErrors??!1;for(let J of f){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let W of J.directories){let H=this.baseTypesByDirectory.get(W);if(H)H.add(J.type);else this.baseTypesByDirectory.set(W,new Set([J.type]))}}}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let f of this.watchersByDirectory.values())f.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let f of this.definitions)await this.refreshTypeInternal(f)})}async refreshType(f){let $=this.definitionsByType.get(f);if(!$)throw Error(`Unknown unified config type '${f}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal($)})}getSnapshot(f){let $=this.recordsByType.get(f);return new Map([...$?.entries()??[]].map(([J,W])=>[J,{...W}]))}getAllSnapshots(){let f=new Map;for(let[$,J]of this.recordsByType.entries())f.set($,new Map([...J.entries()].map(([W,H])=>[W,{...H}])));return f}emit(f){for(let $ of this.listeners)$(f)}enqueueRefresh(f){return this.refreshQueue=this.refreshQueue.then(f,f),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let f=this.buildDesiredTypesByDirectory();for(let[$,J]of this.watchersByDirectory.entries()){if(f.has($))continue;J.close(),this.watchersByDirectory.delete($)}this.watchedTypesByDirectory=f;for(let $ of f.keys()){if(this.watchersByDirectory.has($))continue;try{let J=SP($,()=>{let W=this.watchedTypesByDirectory.get($);if(!W)return;for(let H of W)this.pendingTypes.add(H);this.scheduleFlush()});this.watchersByDirectory.set($,J),J.on("error",(W)=>{let H=this.watchedTypesByDirectory.get($);if(!H)return;for(let Q of H)this.emit({kind:"error",type:Q,error:W,filePath:$})})}catch(J){if(!tH(J)&&!sH(J)){let W=f.get($);if(!W)continue;for(let H of W)this.emit({kind:"error",type:H,error:J,filePath:$})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let f=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let $ of f){let J=this.definitionsByType.get($);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal(f){let{records:$,discoveredDirectories:J}=await this.loadDefinition(f),W=this.recordsByType.get(f.type)??new Map;for(let[H,Q]of W.entries()){if($.has(H))continue;this.emit({kind:"remove",type:f.type,id:H,filePath:Q.filePath})}for(let[H,Q]of $.entries()){let Z=W.get(H);if(Z&&Z.filePath===Q.filePath&&Z.fingerprint===Q.fingerprint)continue;this.emit({kind:"upsert",record:{type:Q.type,id:H,item:Q.item,filePath:Q.filePath}})}if(this.recordsByType.set(f.type,$),this.discoveredDirectoriesByType.set(f.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition(f){let $=new Map,J=new Set;for(let W of f.directories){J.add(W);let H=f.discoverFiles?await f.discoverFiles(W):await this.readDirectoryFileCandidates(W);for(let Q of H){let{fileName:Z,filePath:j}=Q;if(J.add(Q.directoryPath),f.includeFile&&!f.includeFile(Z,j))continue;try{let X=await IP(j,"utf8"),A={type:f.type,directoryPath:Q.directoryPath,fileName:Z,filePath:j,content:X},P=f.parseFile(A),B=f.resolveId(P,A).trim();if(!B)continue;$.set(B,{type:f.type,id:B,item:P,filePath:j,fingerprint:xP(X)})}catch(X){if(this.emitParseErrors)this.emit({kind:"error",type:f.type,error:X,filePath:j})}}}return{records:$,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let f=new Map;for(let[$,J]of this.baseTypesByDirectory.entries())f.set($,new Set(J));for(let[$,J]of this.discoveredDirectoriesByType.entries())for(let W of J){let H=f.get(W);if(H)H.add($);else f.set(W,new Set([$]))}return f}async readDirectoryFileCandidates(f){try{return(await kP(f,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:f,fileName:J.name,filePath:mP(f,J.name)})).sort((J,W)=>J.fileName.localeCompare(W.fileName))}catch($){if(tH($)||sH($))return[];throw $}}}import{readdir as M6,readFile as gP,stat as eH}from"node:fs/promises";import{basename as i0,dirname as vP,extname as L6,join as Gf}from"node:path";import{RULES_CONFIG_DIRECTORY_NAME as f9,resolveRulesConfigSearchPaths as uP,resolveSkillsConfigSearchPaths as cP,resolveWorkflowsConfigSearchPaths as dP,SKILLS_CONFIG_DIRECTORY_NAME as h6,WORKFLOWS_CONFIG_DIRECTORY_NAME as O6}from"@cline/shared/storage";import rP from"yaml";var S2="SKILL.md",lP="managed.json",pP=new Set([".md",".markdown",".txt"]);function z6(f){return f.trim().toLowerCase()}function P1(f){let $=f;return $?.code==="ENOENT"||$?.code==="EACCES"||$?.code==="EPERM"}function k2(f){return pP.has(L6(f).toLowerCase())}async function N6(f){try{let $=await M6(f,{withFileTypes:!0}),J=[];for(let W of $){if(!W.isDirectory())continue;let H=Gf(f,W.name),Q=Gf(H,lP);try{let Z=await gP(Q,"utf8"),j=JSON.parse(Z);if(j&&typeof j==="object")J.push(H)}catch(Z){if(P1(Z))continue;if(Z?.name==="SyntaxError")continue;throw Z}}return J.sort((W,H)=>W.localeCompare(H))}catch($){if(P1($))return[];throw $}}function q6(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,W,H]=J;try{let Q=rP.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:H,hadFrontmatter:!0}}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);return{data:{},body:f,hadFrontmatter:!0,parseError:Z}}}function I2(f,$,J){if(f===void 0||f===null){if(J)throw Error(`Missing required frontmatter field '${$}'.`);return}if(typeof f!=="string")throw Error(`Frontmatter field '${$}' must be a string.`);let W=f.trim();if(!W&&J)throw Error(`Frontmatter field '${$}' cannot be empty.`);return W||void 0}function w$(f,$){if(f===void 0||f===null)return;if(typeof f!=="boolean")throw Error(`Frontmatter field '${$}' must be a boolean.`);return f}function w6(f,$){let{data:J,body:W,parseError:H}=q6(f);if(H)throw Error(`Failed to parse YAML frontmatter: ${H}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in skill file.");let j=I2(J.name,"name",!1)??$.trim();if(!j)throw Error("Missing skill name.");return{name:j,description:I2(J.description,"description",!1),disabled:w$(J.disabled,"disabled")??(w$(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function b6(f,$){let{data:J,body:W,parseError:H}=q6(f);if(H)throw Error(`Failed to parse YAML frontmatter: ${H}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in rule file.");let Z=I2(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing rule name.");return{name:Z,disabled:w$(J.disabled,"disabled")??(w$(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function C6(f,$){let{data:J,body:W,parseError:H}=q6(f);if(H)throw Error(`Failed to parse YAML frontmatter: ${H}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in workflow file.");let Z=I2(J.name,"name",!1)??$.trim();if(!Z)throw Error("Missing workflow name.");return{name:Z,disabled:w$(J.disabled,"disabled")??(w$(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function E6(f){return cP(f)}function S6(f){return uP(f)}function k6(f){return dP(f)}async function $9(f){if(i0(f)===".cline"){let $=await N6(f);return(await Promise.all($.map((W)=>$9(Gf(W,h6))))).flat()}try{let $=await M6(f,{withFileTypes:!0}),J=[];for(let W of $){if(W.isFile()&&W.name===S2){J.push({directoryPath:f,fileName:W.name,filePath:Gf(f,W.name)});continue}if(W.isDirectory())J.push({directoryPath:Gf(f,W.name),fileName:S2,filePath:Gf(f,W.name,S2)})}return J}catch($){if(P1($))return[];throw $}}async function m2(f){if(i0(f)===".cline"){let $=await N6(f);return(await Promise.all($.map((W)=>m2(Gf(W,"rules.md"))))).flat()}try{if((await eH(f)).isFile())return[{directoryPath:vP(f),fileName:i0(f),filePath:f}]}catch($){if(!P1($))throw $}try{let J=(await M6(f,{withFileTypes:!0})).filter((H)=>H.isFile()&&k2(H.name)).map((H)=>({directoryPath:f,fileName:H.name,filePath:Gf(f,H.name)})),W=Gf(f,"AGENTS.md");try{if((await eH(W)).isFile()){if(!J.some((Z)=>Z.fileName==="AGENTS.md"))J.push({directoryPath:f,fileName:"AGENTS.md",filePath:W})}}catch{}return J}catch($){if(P1($))return[];throw $}}async function iP(f){if(i0(f)===".cline"){let $=await N6(f);return(await Promise.all($.map((W)=>m2(Gf(W,O6))))).flat()}return m2(f)}function I6(f){let $=f?.directories??E6(f?.workspacePath),J=f?.workspacePath?Gf(f.workspacePath,".cline"):void 0;return{type:"skill",directories:J?[...$,J]:$,discoverFiles:$9,includeFile:(W)=>W===S2,parseFile:(W)=>w6(W.content,i0(W.directoryPath)),resolveId:(W)=>z6(W.name)}}function m6(f){let $=f?.directories??S6(f?.workspacePath),J=f?.workspacePath?Gf(f.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...$,J]:$,discoverFiles:m2,includeFile:(W,H)=>W===".clinerules"||k2(W)||k2(H),parseFile:(W)=>b6(W.content,i0(W.filePath,L6(W.filePath))),resolveId:(W)=>z6(W.name)}}function x6(f){let $=f?.directories??k6(f?.workspacePath),J=f?.workspacePath?Gf(f.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...$,J]:$,discoverFiles:iP,includeFile:(W)=>k2(W),parseFile:(W)=>C6(W.content,i0(W.filePath,L6(W.filePath))),resolveId:(W)=>z6(W.name)}}function J9(f){let $=[I6(f?.skills),m6(f?.rules),x6(f?.workflows)];return new A1($,{debounceMs:f?.debounceMs,emitParseErrors:f?.emitParseErrors})}import{truncateSplit as W9}from"@cline/shared";function nP(f,$){if(f.description?.trim())return W9(f.description,".");if($==="workflow")return;return W9(f.instructions,".")}function aP(f){return f.disabled!==!0}function H9(f,$){return[...f.getSnapshot($).entries()].map(([J,W])=>({id:J,record:W})).filter(({record:J})=>aP(J.item)).map(({id:J,record:W})=>({id:J,name:W.item.name,instructions:W.item.instructions,description:nP(W.item,$),kind:$})).sort((J,W)=>J.name.localeCompare(W.name))}function B1(f){let $=new Map;for(let J of[...H9(f,"workflow"),...H9(f,"skill")])if(!$.has(J.name))$.set(J.name,J);return[...$.values()].sort((J,W)=>J.name.localeCompare(W.name))}function Q9(f,$){if(!f.startsWith("/")||f.length<2)return f;let J=f.match(/^\/(\S+)/);if(!J)return f;let W=J[1];if(!W)return f;let H=W.length+1,Q=f.slice(H),Z=B1($).find((j)=>j.name===W);return Z?`${Z.instructions}${Q}`:f}function Z9(f){return f.disabled!==!0}function x2(f){if(f.length===0)return"";return`
|
|
45
45
|
|
|
46
46
|
# Rules
|
|
47
47
|
${f.map((J)=>`## ${J.name}
|
|
48
48
|
${J.instructions}`).join(`
|
|
49
49
|
|
|
50
|
-
`)}`}function
|
|
50
|
+
`)}`}function g2(f,$){let J=f?.trim(),W=$?.trim();if(J&&W)return`${J}
|
|
51
51
|
|
|
52
|
-
${
|
|
52
|
+
${W}`;return J||W||void 0}function tP(f){return[...f.getSnapshot("rule").values()].map((J)=>J.item).filter(Z9).sort((J,W)=>J.name.localeCompare(W.name))}function j9(f){return x2(tP(f))}import{validateWithZod as oz,zodToJsonSchema as ez}from"@cline/shared";var Hf={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"},b$=[Hf.READ_FILES,Hf.SEARCH_CODEBASE,Hf.RUN_COMMANDS,Hf.FETCH_WEB_CONTENT,Hf.APPLY_PATCH,Hf.EDITOR,Hf.SKILLS,Hf.ASK,Hf.SUBMIT_AND_EXIT];import{createTool as $0,validateWithZod as D0,zodToJsonSchema as cf}from"@cline/shared";import{validateWithZod as K9}from"@cline/shared";import{z as G}from"zod";var G0=6000,g6=G.string().describe("The absolute file path of a text file to read content from"),X9=G.object({start_line:G.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:G.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),n0=G.object({path:g6,start_line:X9.shape.start_line,end_line:X9.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),v2=G.object({files:G.array(n0).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.")}),A9=G.union([v2,n0,G.array(n0),G.array(G.string()),G.string(),G.object({files:n0}),G.object({file_paths:G.array(g6)}),G.object({file_paths:G.string()}),G.object({paths:G.array(G.union([g6,n0]))}),G.object({paths:n0}),G.object({paths:G.string()})]),u2=G.object({queries:G.array(G.string()).describe("Array of regex search queries to execute")}),P9=G.union([u2,G.array(G.string()),G.string(),G.object({queries:G.string()})]),a0=G.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${G0*2} characters) to avoid timeouts.`),Y1=G.object({commands:G.array(a0).describe("Array of shell commands to execute")}),B9=G.union([Y1,G.object({commands:a0}),G.object({command:a0}),G.object({cmd:a0}),G.array(G.string()),G.string()]),v6=G.object({command:G.string().min(1).describe("The executable to run directly without shell parsing."),args:G.array(G.string()).optional().describe("Optional argv list passed directly to the executable.")}),Y9=G.union([a0,v6]),u6=G.object({commands:G.array(Y9).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.")}),V9=G.union([Y1,u6,G.object({commands:Y9}),G.array(v6),v6,G.object({command:a0}),G.object({cmd:a0}),G.array(G.string()),G.string()]),R9=G.object({url:G.string().describe("The URL to fetch"),prompt:G.string().min(2).describe("Analysis prompt for the fetched content")}),c2=G.object({requests:G.array(R9).describe("Array of the URLs for the web fetch requests")}),d2=G.object({path:G.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:G.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${G0} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:G.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${G0} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:G.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),r2=G.object({input:G.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),F9=G.union([r2,G.string()]),l2=G.object({skill:G.string().min(1).describe("Name of the skill to execute."),args:G.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),p2=G.object({question:G.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:G.array(G.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),i2=G.object({summary:G.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:G.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
|
|
53
53
|
'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
|
|
54
|
-
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
|
|
54
|
+
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 T0(f){if(f instanceof Error)return f.message;return String(f)}function y9(f){if(typeof f.old_text==="string"&&f.old_text.length>G0)return`Editor input too large: old_text was ${f.old_text.length} characters, exceeding the recommended limit of ${G0}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if(f.new_text.length>G0)return`Editor input too large: new_text was ${f.new_text.length} characters, exceeding the recommended limit of ${G0}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}function uf(f,$,J){return Promise.race([f,new Promise((W,H)=>{setTimeout(()=>H(Error(J)),$)})])}function U9(f){let $=K9(A9,f);if(typeof $==="string")return[{path:$}];if(Array.isArray($))return $.map((J)=>typeof J==="string"?{path:J}:J);if("files"in $)return Array.isArray($.files)?$.files:[$.files];if("file_paths"in $)return(Array.isArray($.file_paths)?$.file_paths:[$.file_paths]).map((W)=>({path:W}));if("paths"in $)return(Array.isArray($.paths)?$.paths:[$.paths]).map((W)=>typeof W==="string"?{path:W}:W);return[$]}function n2(f){let{path:$,start_line:J,end_line:W}=f;if(J==null&&W==null)return $;return`${$}:${J??1}-${W??"EOF"}`}function G9(f){let{start_line:$,end_line:J}=f;if($==null||J==null||$<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${$}, end_line: ${J})`}function T9(f){let $=K9(V9,f);if(typeof $==="string")return[$];if(Array.isArray($))return $;if("commands"in $)return Array.isArray($.commands)?$.commands:[$.commands];if("command"in $)return"args"in $?[$]:[$.command];if("cmd"in $)return[$.cmd];return[$]}function c6(f){if(typeof f==="string")return f;let $=f.args??[];if($.length===0)return f.command;let J=$.map((W)=>/[\s"]/u.test(W)?JSON.stringify(W):W);return`${f.command} ${J.join(" ")}`}function D9(f,$={}){let J=$.fileReadTimeoutMs??1e4;return $0({name:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Returns file contents or error messages for each path.",inputSchema:cf(v2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(W,H)=>{let Q=U9(W);return Promise.all(Q.map(async(Z)=>{let j=G9(Z);if(j)return{query:n2(Z),result:"",error:`Invalid file range: ${j}`,success:!1};try{let X=await uf(f(Z,H),J,`File read timed out after ${J}ms`);return{query:n2(Z),result:X,success:!0}}catch(X){let A=T0(X);return{query:n2(Z),result:"",error:`Error reading file: ${A}`,success:!1}}}))}})}function _9(f,$={}){let J=$.searchTimeoutMs??30000,W=$.cwd??process.cwd();return $0({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:cf(u2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(H,Q)=>{let Z=D0(P9,H),j=Array.isArray(Z)?Z:typeof Z==="object"?Array.isArray(Z.queries)?Z.queries:[Z.queries]:[Z];return Promise.all(j.map(async(X)=>{try{let A=await uf(f(X,W,Q),J,`Search timed out after ${J}ms`),P=A.length>0&&!A.includes("No results found");return{query:X,result:A,success:P}}catch(A){let P=T0(A);return{query:X,result:"",error:`Search failed: ${P}`,success:!1}}}))}})}function M9(f,$={}){let J=$.bashTimeoutMs??30000,W=$.cwd??process.cwd();return $0({name:"run_commands",description:"Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped.",inputSchema:cf(Y1),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=D0(B9,H),j;if(typeof Z==="string")j=[Z];else if(Array.isArray(Z))j=Z;else if("commands"in Z)j=Array.isArray(Z.commands)?Z.commands:[Z.commands];else if("command"in Z)j=[Z.command];else j=[Z.cmd];return Promise.all(j.map(async(X)=>{try{let A=await uf(f(X,W,Q),J,`Command timed out after ${J}ms`);return{query:X,result:A,success:!0}}catch(A){let P=T0(A);return{query:X,result:"",error:`Command failed: ${P}`,success:!1}}}))}})}function L9(f,$={}){let J=$.bashTimeoutMs??30000,W=$.cwd??process.cwd();return $0({name:"run_commands",description:"Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped.",inputSchema:cf(u6),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=T9(H);return Promise.all(Z.map(async(j)=>{try{let X=await uf(f(j,W,Q),J,`Command timed out after ${J}ms`);return{query:c6(j),result:X,success:!0}}catch(X){let A=T0(X);return{query:c6(j),result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function h9(f,$={}){let J=$.webFetchTimeoutMs??30000;return $0({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract.",inputSchema:cf(c2),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(W,H)=>{let Q=D0(c2,W);return Promise.all(Q.requests.map(async(Z)=>{try{let j=await uf(f(Z.url,Z.prompt,H),J,`Web fetch timed out after ${J}ms`);return{query:Z.url,result:j,success:!0}}catch(j){let X=T0(j);return{query:Z.url,result:"",error:`Error fetching web content: ${X}`,success:!1}}}))}})}var sP=`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:
|
|
55
55
|
|
|
56
56
|
*** Begin Patch
|
|
57
57
|
*** Update File: path/to/file.ts
|
|
@@ -87,79 +87,79 @@ Example:
|
|
|
87
87
|
</div>
|
|
88
88
|
);
|
|
89
89
|
}
|
|
90
|
-
*** End Patch`;function
|
|
91
|
-
`),
|
|
92
|
-
${this.lines[this.index]}`);if(j?.trim()){let
|
|
93
|
-
`);this.addWarning({path:this.currentPath||$,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${U.toFixed(2)}). Chunk skipped.`,context:
|
|
94
|
-
`),chunks:[]}}}function
|
|
95
|
-
`));for(let
|
|
96
|
-
`));if(
|
|
97
|
-
`)),
|
|
98
|
-
`));if(
|
|
99
|
-
`)),
|
|
100
|
-
`));if(
|
|
101
|
-
`)),
|
|
102
|
-
`).map(($)=>$.replace(/\r$/,""))}function
|
|
103
|
-
`),
|
|
104
|
-
`)}async function
|
|
105
|
-
`)}return Q}function
|
|
106
|
-
`)}}import{spawn as
|
|
90
|
+
*** End Patch`;function O9(f,$={}){let J=$.applyPatchTimeoutMs??30000,W=$.cwd??process.cwd();return $0({name:"apply_patch",description:sP,inputSchema:cf(r2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=D0(F9,H),j=typeof Z==="string"?Z:Z.input;try{return{query:"apply_patch",result:await uf(f({input:j},W,Q),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(X){return{query:"apply_patch",result:"",error:`apply_patch failed: ${T0(X)}`,success:!1}}}})}function z9(f,$={}){let J=$.editorTimeoutMs??30000,W=$.cwd??process.cwd();return $0({name:"editor",description:"An editor for controlled filesystem edits on the text file at the provided path. Provide `insert_line` to insert `new_text` at a specific line number. Otherwise, the tool replaces `old_text` with `new_text`, or creates the file with `new_text` if file does not exist. Use this tools for making small, precise edits to existing files or creating new files over shell commands.",inputSchema:cf(d2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(H,Q)=>{let Z=D0(d2,H),j=Z.insert_line==null?"edit":"insert",X=y9(Z);if(X)return{query:`${j}:${Z.path}`,result:"",error:X,success:!1};try{let A=await uf(f(Z,W,Q),J,`Editor operation timed out after ${J}ms`);return{query:`${j}:${Z.path}`,result:A,success:!0}}catch(A){let P=T0(A);return{query:`${j}:${Z.path}`,result:"",error:`Editor operation failed: ${P}`,success:!1}}}})}function C$(f,$={}){let J=$.skillsTimeoutMs??15000,W='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',H=$0({name:"skills",description:W,inputSchema:cf(l2),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,Z)=>{let j=D0(l2,Q);return uf(f(j.skill,j.args||void 0,Z),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(H,"description",{get(){let Q=f.configuredSkills?.filter((Z)=>!Z.disabled).map((Z)=>Z.name);if(Q&&Q.length>0)return`${W} Available skills: ${Q.join(", ")}.`;return W},enumerable:!0,configurable:!0}),H}function N9(f){return{name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:cf(p2),retryable:!1,maxRetries:0,execute:async($,J)=>{let W=D0(p2,$);return f(W.question,W.options,J)}}}function q9(f,$={}){let J=$.submitTimeoutMs??15000;return $0({name:"submit_and_exit",description:"Submit the final answer and exit the conversation. For example, submit a summary of the investigation and confirm the issue is resolved. You should only submit once all necessary steps are completed. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:cf(i2),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,H)=>{let Q=D0(i2,W);return uf(f(Q.summary,Q.verified,H),J,`submit_and_exit timed out after ${J}ms`)}})}function E$(f){let{executors:$,enableReadFiles:J=!0,enableSearch:W=!0,enableBash:H=!0,enableWebFetch:Q=!0,enableApplyPatch:Z=!1,enableEditor:j=!0,enableSkills:X=!0,enableAskQuestion:A=!0,enableSubmitAndExit:P=!1,...B}=f,Y=[];if(J&&$.readFile)Y.push(D9($.readFile,B));if(W&&$.search)Y.push(_9($.search,B));if(H&&$.bash)if(process.platform==="win32")Y.push(L9($.bash,B));else Y.push(M9($.bash,B));if(Q&&$.webFetch)Y.push(h9($.webFetch,B));if(j&&$.editor)Y.push(z9($.editor,B));else if(Z&&$.applyPatch)Y.push(O9($.applyPatch,B));if(X&&$.skills)Y.push(C$($.skills,B));let V=P?$.submit:void 0;if(A&&$.askQuestion&&!V)Y.push(N9($.askQuestion));if(V)Y.push(q9(V,B));return Y}import*as zf from"node:fs/promises";import*as Nf from"node:path";var k={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},b9=["%%bash","apply_patch","EOF","```"];class $f extends Error{constructor(f){super(f);this.name="DiffError"}}function Of(f){let $={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return f.normalize("NFC").replace(/./gu,(J)=>$[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class d6{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor(f,$){this.lines=f;this.currentFiles=$}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning(f){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push(f)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(k.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(k.END)??!1}parseNextAction(){let f=this.lines[this.index];if(f?.startsWith(k.UPDATE)){this.parseUpdate(f.substring(k.UPDATE.length).trim());return}if(f?.startsWith(k.DELETE)){this.parseDelete(f.substring(k.DELETE.length).trim());return}if(f?.startsWith(k.ADD)){this.parseAdd(f.substring(k.ADD.length).trim());return}throw new $f(`Unknown line while parsing: ${f}`)}checkDuplicate(f,$){if(f in this.patch.actions)throw new $f(`Duplicate ${$} for file: ${f}`)}parseUpdate(f){this.checkDuplicate(f,"update"),this.currentPath=f,this.index++;let $=this.lines[this.index]?.startsWith(k.MOVE)?(this.lines[this.index++]??"").substring(k.MOVE.length).trim():void 0;if(!(f in this.currentFiles))throw new $f(`Update File Error: Missing File: ${f}`);let J=this.currentFiles[f]??"",W=this.parseUpdateFile(J,f);W.movePath=$,this.patch.actions[f]=W,this.currentPath=void 0}parseUpdateFile(f,$){let J={type:"update",chunks:[]},W=f.split(`
|
|
91
|
+
`),H=0,Q=[k.END,k.UPDATE,k.DELETE,k.ADD,k.END_FILE];while(!Q.some((Z)=>this.lines[this.index]?.startsWith(Z.trim()))){let Z=this.lines[this.index],j=Z?.startsWith("@@ ")?Z.substring(3):void 0;if(j!==void 0||(Z==="@@"?Z:void 0)!==void 0)this.index++;else if(H!==0)throw new $f(`Invalid Line:
|
|
92
|
+
${this.lines[this.index]}`);if(j?.trim()){let K=Of(j.trim());for(let F=H;F<W.length;F++){let y=W[F];if(y&&(Of(y)===K||Of(y.trim())===K)){if(H=F+1,Of(y.trim())===K&&Of(y)!==K)this.fuzz++;break}}}let[A,P,B,Y]=fB(this.lines,this.index),[V,R,U]=eP(W,A,H,Y);if(V===-1){let K=A.join(`
|
|
93
|
+
`);this.addWarning({path:this.currentPath||$,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${U.toFixed(2)}). Chunk skipped.`,context:K.length>200?`${K.substring(0,200)}...`:K}),this.index=B}else{this.fuzz+=R;for(let K of P)K.origIndex+=V,J.chunks.push(K);H=V+A.length,this.index=B}}return J}parseDelete(f){if(this.checkDuplicate(f,"delete"),!(f in this.currentFiles))throw new $f(`Delete File Error: Missing File: ${f}`);this.patch.actions[f]={type:"delete",chunks:[]},this.index++}parseAdd(f){if(this.checkDuplicate(f,"add"),f in this.currentFiles)throw new $f(`Add File Error: File already exists: ${f}`);this.index++;let $=[],J=[k.END,k.UPDATE,k.DELETE,k.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 $f(`Invalid Add File line (missing '+'): ${W}`);$.push(W.substring(1))}this.patch.actions[f]={type:"add",newFile:$.join(`
|
|
94
|
+
`),chunks:[]}}}function w9(f,$){let J=f.length>$.length?f:$,W=f.length>$.length?$:f;if(J.length===0)return 1;let H=oP(W,J);return(J.length-H)/J.length}function oP(f,$){let J=$.length+1,W=f.length+1,H=Array(J*W).fill(0),Q=(j,X)=>H[j*W+X]??0,Z=(j,X,A)=>{H[j*W+X]=A};for(let j=0;j<=$.length;j++)Z(j,0,j);for(let j=0;j<=f.length;j++)Z(0,j,j);for(let j=1;j<=$.length;j++)for(let X=1;X<=f.length;X++)if($[j-1]===f[X-1])Z(j,X,Q(j-1,X-1));else Z(j,X,1+Math.min(Q(j-1,X-1),Q(j,X-1),Q(j-1,X)));return Q($.length,f.length)}function eP(f,$,J,W){if($.length===0)return[J,0,1];let H=0,Q=(Z)=>{let j=Of($.join(`
|
|
95
|
+
`));for(let A=Z;A<f.length;A++){let P=Of(f.slice(A,A+$.length).join(`
|
|
96
|
+
`));if(P===j)return[A,0,1];let B=w9(P,j);if(B>H)H=B}for(let A=Z;A<f.length;A++){let P=Of(f.slice(A,A+$.length).map((Y)=>Y.trimEnd()).join(`
|
|
97
|
+
`)),B=Of($.map((Y)=>Y.trimEnd()).join(`
|
|
98
|
+
`));if(P===B)return[A,1,1]}for(let A=Z;A<f.length;A++){let P=Of(f.slice(A,A+$.length).map((Y)=>Y.trim()).join(`
|
|
99
|
+
`)),B=Of($.map((Y)=>Y.trim()).join(`
|
|
100
|
+
`));if(P===B)return[A,100,1]}let X=0.66;for(let A=Z;A<f.length;A++){let P=Of(f.slice(A,A+$.length).join(`
|
|
101
|
+
`)),B=w9(P,j);if(B>=X)return[A,1000,B];if(B>H)H=B}return[-1,0,H]};if(W){let[Z,j,X]=Q(f.length-$.length);if(Z!==-1)return[Z,j,X];return[Z,j,X]=Q(J),[Z,j+1e4,X]}return Q(J)}function fB(f,$){let J=$,W=[],H=[],Q=[],Z=[],j="keep",X=["@@",k.END,k.UPDATE,k.DELETE,k.ADD,k.END_FILE];while(J<f.length){let A=f[J];if(!A||X.some((Y)=>A.startsWith(Y.trim())))break;if(A==="***")break;if(A.startsWith("***"))throw new $f(`Invalid line: ${A}`);J++;let P=j,B=A;if(B[0]==="+")j="add";else if(B[0]==="-")j="delete";else if(B[0]===" ")j="keep";else j="keep",B=` ${B}`;if(B=B.slice(1),j==="keep"&&P!==j){if(Q.length||H.length)Z.push({origIndex:W.length-H.length,delLines:H,insLines:Q});H=[],Q=[]}if(j==="delete")H.push(B),W.push(B);else if(j==="add")Q.push(B);else W.push(B)}if(Q.length||H.length)Z.push({origIndex:W.length-H.length,delLines:H,insLines:Q});if(J<f.length&&f[J]===k.END_FILE)return J++,[W,Z,J,!0];return[W,Z,J,!1]}function r6(f,$,J){let W=Nf.isAbsolute($),H=W?Nf.normalize($):Nf.resolve(f,$);if(!J||W)return H;let Q=Nf.relative(f,H);if(Q.startsWith("..")||Nf.isAbsolute(Q))throw new $f(`Path must stay within cwd: ${$}`);return H}function $B(f){return f.split(`
|
|
102
|
+
`).map(($)=>$.replace(/\r$/,""))}function C9(f){if(f.trim()==="")return!1;return b9.some(($)=>f.startsWith($))}function JB(f){let $=0,J=f.length;while($<J&&C9(f[$]??""))$++;while(J>$&&C9(f[J-1]??""))J--;return f.slice($,J)}function WB(f){let $=$B(f),J=$.findIndex((Z)=>Z.startsWith(k.BEGIN)),W=-1;for(let Z=$.length-1;Z>=0;Z--)if($[Z]?.startsWith(k.END)){W=Z;break}if(J!==-1||W!==-1){if(J===-1||W===-1||W<J)throw new $f("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:$.slice(J,W+1)}}let H=JB($);while(H.length>0&&H[0]==="")H.shift();while(H.length>0&&H[H.length-1]==="")H.pop();return{lines:[k.BEGIN,...H,k.END]}}function HB(f,$){let J=new Set;for(let W of f)for(let H of $)if(W.startsWith(H)){J.add(W.substring(H.length).trim());break}return[...J]}function QB(f,$,J){if($.length===0)return f;let W=f.split(`
|
|
103
|
+
`),H=[],Q=0;for(let Z of $){if(Z.origIndex>W.length)throw new $f(`${J}: chunk.origIndex ${Z.origIndex} > lines.length ${W.length}`);if(Q>Z.origIndex)throw new $f(`${J}: currentIndex ${Q} > chunk.origIndex ${Z.origIndex}`);H.push(...W.slice(Q,Z.origIndex)),H.push(...Z.insLines),Q=Z.origIndex+Z.delLines.length}return H.push(...W.slice(Q)),H.join(`
|
|
104
|
+
`)}async function ZB(f,$,J,W){let H=HB(f,[k.UPDATE,k.DELETE]),Q={};for(let Z of H){let j=r6($,Z,W),X;try{X=await zf.readFile(j,J)}catch{throw new $f(`File not found: ${Z}`)}Q[Z]=X.replace(/\r\n/g,`
|
|
105
|
+
`)}return Q}function jB(f,$){let J={};for(let[W,H]of Object.entries(f.actions))switch(H.type){case"delete":J[W]={type:"delete",oldContent:$[W]};break;case"add":if(H.newFile===void 0)throw new $f("ADD action without file content");J[W]={type:"add",newContent:H.newFile};break;case"update":J[W]={type:"update",oldContent:$[W],newContent:QB($[W]??"",H.chunks,W),movePath:H.movePath};break}return J}async function XB(f,$,J,W){let H=[];for(let[Q,Z]of Object.entries(f)){let j=r6($,Q,W);switch(Z.type){case"delete":await zf.rm(j,{force:!0}),H.push(`${Q}: [deleted]`);break;case"add":if(Z.newContent===void 0)throw new $f(`Cannot create ${Q} with no content`);await zf.mkdir(Nf.dirname(j),{recursive:!0}),await zf.writeFile(j,Z.newContent,{encoding:J}),H.push(Q);break;case"update":{if(Z.newContent===void 0)throw new $f(`UPDATE change for ${Q} has no new content`);if(Z.movePath){let X=r6($,Z.movePath,W);await zf.mkdir(Nf.dirname(X),{recursive:!0}),await zf.writeFile(X,Z.newContent,{encoding:J}),await zf.rm(j,{force:!0}),H.push(`${Q} -> ${Z.movePath}`)}else await zf.writeFile(j,Z.newContent,{encoding:J}),H.push(Q);break}}}return H}function a2(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0}=f;return async(W,H,Q)=>{let Z=WB(W.input),j=await ZB(Z.lines,H,$,J),X=new d6(Z.lines,j),{patch:A,fuzz:P}=X.parse(),B=jB(A,j),Y=await XB(B,H,$,J),V=["Successfully applied patch to the following files:"];for(let R of Y)V.push(R);if(P>0)V.push(`Note: Patch applied with fuzz factor ${P}`);if(A.warnings&&A.warnings.length>0)for(let R of A.warnings)V.push(`Warning (${R.path}): ${R.message}`);return V.join(`
|
|
106
|
+
`)}}import{spawn as E9}from"node:child_process";import{getDefaultShell as AB,getShellArgs as PB}from"@cline/shared";function BB(f,$,J,W,H){return new Promise((Q,Z)=>{let j=process.platform==="win32",X=E9(f.executable,f.args,{cwd:f.cwd,env:{...process.env,...f.env},stdio:["pipe","pipe","pipe"],detached:!j}),A=X.pid,P="",B="",Y=0,V=!1,R=!1,U=(T)=>{if(R)return;R=!0,T()},K=()=>{if(!A)return;if(j){E9("taskkill",["/pid",String(A),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-A,"SIGKILL")}catch{X.kill("SIGKILL")}},F=(T)=>{V=!0,K(),U(()=>Z(T))},y=setTimeout(()=>F(Error(`Command timed out after ${J}ms`)),J),D=()=>F(Error("Command was aborted"));if($.signal)$.signal.addEventListener("abort",D);let M=()=>{clearTimeout(y),$.signal?.removeEventListener("abort",D)};X.stdout?.on("data",(T)=>{if(Y+=T.length,Y<=W)P+=T.toString()}),X.stderr?.on("data",(T)=>{if(Y+=T.length,Y<=W)B+=T.toString()}),X.on("close",(T)=>{if(M(),V)return;let _=H?P+(B?`
|
|
107
107
|
[stderr]
|
|
108
|
-
${
|
|
108
|
+
${B}`:""):P;if(Y>W)_+=`
|
|
109
109
|
|
|
110
|
-
[Output truncated: ${
|
|
111
|
-
`),
|
|
112
|
-
`),Q=Math.max(
|
|
113
|
-
`)}async function
|
|
114
|
-
${
|
|
110
|
+
[Output truncated: ${Y} bytes total, showing first ${W} bytes]`;if(T!==0)U(()=>Z(Error(B||`Command exited with code ${T}`)));else U(()=>Q(_))}),X.on("error",(T)=>{M(),U(()=>Z(Error(`Failed to execute command: ${T.message}`)))})})}function t2(f={}){let{shell:$=AB(process.platform),timeoutMs:J=30000,maxOutputBytes:W=1e6,env:H={},combineOutput:Q=!0}=f;return(Z,j,X)=>{let A=typeof Z!=="string";return BB({executable:A?Z.command:$,args:A?Z.args??[]:PB($,Z),cwd:j,env:H},X,J,W,Q)}}import*as xf from"node:fs/promises";import*as mf from"node:path";function YB(f,$,J){let W=mf.isAbsolute($),H=W?mf.normalize($):mf.resolve(f,$);if(!J)return H;if(W)return H;let Q=mf.relative(f,H);if(Q.startsWith("..")||mf.isAbsolute(Q))throw Error(`Path must stay within cwd: ${$}`);return H}function VB(f,$){if($.length===0)return 0;return f.split($).length-1}function RB(f,$,J){let W=f.split(`
|
|
111
|
+
`),H=$.split(`
|
|
112
|
+
`),Q=Math.max(W.length,H.length),Z=["```diff"],j=0;for(let X=0;X<Q;X++){if(j>=J){Z.push("... diff truncated ...");break}let A=W[X],P=H[X];if(A===P)continue;let B=X+1;if(A!==void 0)Z.push(`-${B}: ${A}`),j++;if(P!==void 0&&j<J)Z.push(`+${B}: ${P}`),j++}return Z.push("```"),Z.join(`
|
|
113
|
+
`)}async function FB(f,$,J){return await xf.mkdir(mf.dirname(f),{recursive:!0}),await xf.writeFile(f,$,{encoding:J}),`File created successfully at: ${f}`}async function KB(f){try{return await xf.access(f),!0}catch{return!1}}async function yB(f,$,J,W,H){let Q=await xf.readFile(f,W),Z=VB(Q,$);if(Z===0)throw Error(`No replacement performed: text not found in ${f}.`);if(Z>1)throw Error(`No replacement performed: multiple occurrences of text found in ${f}.`);let j=Q.replace($,J??"");await xf.writeFile(f,j,{encoding:W});let X=RB(Q,j,H);return`Edited ${f}
|
|
114
|
+
${X}`}async function UB(f,$,J,W){let Q=(await xf.readFile(f,W)).split(`
|
|
115
115
|
`),Z=Q.length+1;if($<1||$>Z)throw Error(`Invalid insert_line: ${$}. insert_line must be a positive one-based boundary line in the range 1-${Z}. Use ${Z} to append at EOF.`);let j=$-1;return Q.splice(j,0,...J.split(`
|
|
116
|
-
`)),await
|
|
117
|
-
`),{encoding:
|
|
118
|
-
`),U=Math.max((j??1)-1,0),
|
|
116
|
+
`)),await xf.writeFile(f,Q.join(`
|
|
117
|
+
`),{encoding:W}),`Inserted content at line ${$} in ${f}.`}function s2(f={}){let{encoding:$="utf-8",restrictToCwd:J=!0,maxDiffLines:W=200}=f;return async(H,Q,Z)=>{let j=YB(Q,H.path,J);if(H.insert_line!=null)return UB(j,H.insert_line,H.new_text,$);if(!await KB(j))return FB(j,H.new_text,$);if(H.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return yB(j,H.old_text,H.new_text,$,W)}}import*as V1 from"node:fs/promises";import*as _0 from"node:path";var GB=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),TB={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function o2(f={}){let{maxFileSizeBytes:$,encoding:J,includeLineNumbers:W}={...TB,...f};return async(H,Q)=>{let{path:Z,start_line:j,end_line:X}=H,A=_0.isAbsolute(Z)?_0.normalize(Z):_0.resolve(process.cwd(),Z),P=_0.extname(A).toLowerCase(),B=GB.get(P),Y=await V1.stat(A);if(!Y.isFile())throw Error(`Path is not a file: ${A}`);if(Y.size>$)throw Error(`File too large: ${Y.size} bytes (max: ${$} bytes). Consider reading specific sections or using a different approach.`);if(B){if(Q.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let y=await V1.readFile(A);return[{type:"text",text:"Successfully read image"},{type:"image",data:y.toString("base64"),mediaType:B}]}let R=(await V1.readFile(A,J)).split(`
|
|
118
|
+
`),U=Math.max((j??1)-1,0),K=Math.min(X??R.length,R.length),F=R.slice(U,K);if(W){let y=String(R.length).length;return F.map((D,M)=>`${String(U+M+1).padStart(y," ")} | ${D}`).join(`
|
|
119
119
|
`)}return F.join(`
|
|
120
|
-
`)}}import{spawn as
|
|
121
|
-
`).filter((
|
|
122
|
-
`)}let
|
|
123
|
-
`);for(let
|
|
124
|
-
Searched ${U} files.`;let F=[`Found ${R.length} result${R.length===1?"":"s"} for pattern: ${
|
|
125
|
-
`)}}function
|
|
120
|
+
`)}}import{spawn as v9}from"node:child_process";import*as u9 from"node:fs/promises";import*as $8 from"node:path";import{spawn as DB}from"node:child_process";import{readdir as _B}from"node:fs/promises";import p6 from"node:path";import{isMainThread as I9,parentPort as S9,Worker as MB}from"node:worker_threads";var LB=15000,hB=600000,OB=1000,zB=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function k9(f){let $=f&&typeof f==="object"&&"code"in f?String(f.code??""):"";return $==="EACCES"||$==="EPERM"||$==="ENOENT"}var S$=new Map;function NB(f){if(S$.size<=1)return;for(let[$,J]of S$.entries()){if(J.pending)continue;if(f-J.lastAccessedAt>hB)S$.delete($)}}function qB(f,$){return p6.relative(f,$).split(p6.sep).join("/")}async function wB(f){let J=(await new Promise((W,H)=>{let Q=DB("rg",["--files","--hidden","-g","!.git"],{cwd:f,stdio:["ignore","pipe","pipe"]}),Z="",j="";Q.stdout.on("data",(X)=>{Z+=X.toString()}),Q.stderr.on("data",(X)=>{j+=X.toString()}),Q.on("error",H),Q.on("close",(X)=>{if(X===0){W(Z);return}H(Error(j||`rg exited with code ${X}`))})})).split(/\r?\n/).map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>W.replace(/\\/g,"/"));return new Set(J)}async function m9(f,$,J){let W;try{W=await _B($,{withFileTypes:!0})}catch(H){if(k9(H))return;throw H}for(let H of W){let Q=p6.join($,H.name);if(H.isDirectory()){if(zB.has(H.name))continue;try{await m9(f,Q,J)}catch(Z){if(k9(Z))continue;throw Z}continue}if(H.isFile())J.add(qB(f,Q))}}async function bB(f){let $=new Set;return await m9(f,f,$),$}async function e2(f){try{return await wB(f)}catch{return bB(f)}}function CB(){if(I9||!S9)return;let f=S9;f.on("message",($)=>{if($.type!=="index")return;e2($.cwd).then((J)=>{let W={type:"indexResult",requestId:$.requestId,files:Array.from(J)};f.postMessage(W)}).catch((J)=>{let W={type:"indexResult",requestId:$.requestId,error:J instanceof Error?J.message:"Failed to build file index"};f.postMessage(W)})})}class x9{worker=new MB(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",(f)=>{if(f.type!=="indexResult")return;let $=this.pending.get(f.requestId);if(!$)return;if(this.pending.delete(f.requestId),f.error){$.reject(Error(f.error));return}$.resolve(f.files??[])}),this.worker.on("error",(f)=>{this.flushPending(f)}),this.worker.on("exit",(f)=>{if(f!==0)this.flushPending(Error(`File index worker exited with code ${f}`))})}requestIndex(f){let $=++this.nextRequestId,J=new Promise((H,Q)=>{let Z=setTimeout(()=>{this.pending.delete($),H(null)},OB);Z.unref(),this.pending.set($,{resolve:(j)=>{clearTimeout(Z),H(j)},reject:(j)=>{clearTimeout(Z),Q(j)}})}),W={type:"index",requestId:$,cwd:f};return this.worker.postMessage(W),J}flushPending(f){for(let[$,J]of this.pending.entries())J.reject(f),this.pending.delete($)}}CB();var l6;function EB(){if(!I9)return null;if(l6===void 0)l6=new x9;return l6}async function SB(f){let $=EB();if(!$)return e2(f);try{let J=await $.requestIndex(f);if(J===null)return e2(f);return new Set(J)}catch{return e2(f)}}async function t0(f,$={}){let J=$.ttlMs??LB,W=Date.now();NB(W);let H=S$.get(f);if(H&&J>0&&W-H.lastBuiltAt<=J&&H.files.size>0)return H.lastAccessedAt=W,H.files;if(H?.pending)return H.lastAccessedAt=W,H.pending;let Q=SB(f).then((Z)=>{return S$.set(f,{files:Z,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),Z});return S$.set(f,{files:H?.files??new Set,lastBuiltAt:H?.lastBuiltAt??0,lastAccessedAt:W,pending:Q}),Q}async function g9(f,$={}){await t0(f,{...$,ttlMs:0})}import{stat as kB}from"node:fs/promises";import s0 from"node:path";var IB=/[),.:;!?`'"]+$/,mB=/^[(`'"]+/;function xB(f){let $=f.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let W of $){let H=(W[2]??"").trim();if(H.length===0)continue;let Q=H.replace(mB,"").replace(IB,"");if(Q.length===0||Q.includes("@"))continue;J.push(Q)}return Array.from(new Set(J))}function gB(f,$){let J=f.replace(/\\/g,"/"),W=s0.isAbsolute(J)?s0.resolve(J):s0.resolve($,J),H=s0.relative($,W);if(H.startsWith("..")||s0.isAbsolute(H))return;return H.split(s0.sep).join("/")}async function f8(f,$,J={}){let W=xB(f);if(W.length===0)return{prompt:f,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:H,maxFileBytes:Q,maxTotalBytes:Z}=J,j=await t0($,{ttlMs:J.ttlMs}),X=[],A=[],P=[],B=0;for(let Y of W){if(H&&P.length>=H){A.push(Y);continue}let V=gB(Y,$);if(!V||!j.has(V)){A.push(Y);continue}if(!Q||!Z){X.push(V);continue}let R=s0.join($,V);try{if(!(await kB(R)).isFile()){A.push(Y);continue}let K=B+Q;if(K>Z){A.push(Y);continue}B=K,X.push(V)}catch{A.push(Y)}}return{prompt:f,mentions:W,matchedFiles:X,ignoredMentions:A}}var vB=["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"],uB=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],o0=null;function cB(){if(o0!==null)return Promise.resolve(o0);return new Promise((f)=>{let $=v9("rg",["--version"],{stdio:["ignore","pipe","pipe"]});$.on("close",(J)=>{o0=J===0,f(o0)}),$.on("error",()=>{o0=!1,f(!1)}),setTimeout(()=>{if(!$.killed)$.kill("SIGTERM");if(o0===null)o0=!1,f(!1)},1000)})}function dB(f,$,J,W,H=5000,Q){return new Promise((Z)=>{let j=v9("rg",["--json",`--context=${W}`,"--max-count=1","-i",f],{cwd:$,stdio:["ignore","pipe","pipe"]}),X="",A=!1,P=()=>{if(!j.killed)j.kill("SIGTERM")},B=setTimeout(()=>{if(!A)A=!0,P(),Z(null)},H),Y=(V)=>{if(!A)A=!0,clearTimeout(B),P(),Z(V)};if(Q?.aborted){P(),Z(null);return}Q?.addEventListener("abort",()=>{Y(null)}),j.stdout.on("data",(V)=>{X+=V.toString()}),j.stderr.on("data",()=>{}),j.on("close",(V)=>{if(V===0||V===1){try{let R=[],U=X.split(`
|
|
121
|
+
`).filter((K)=>K.trim());for(let K of U){if(R.length>=J)break;let F=JSON.parse(K);if(F.type==="match"){let y=F.data,D=[];if(F.data.submatches&&F.data.submatches.length>0){let M=F.data.submatches[0];R.push({file:y.path.text,line:y.line_number,column:(M?.start??0)+1,match:M?.match?.text??"",context:D})}}else if(F.type==="context"&&R.length>0){let y=R[R.length-1],D=F.data.line_number===y.line?">":" ";y.context.push(`${D} ${F.data.line_number}: ${F.data.lines?.text??F.data.line?.text??""}`)}}Y(R.length>0?R:null)}catch{Y(null)}return}Y(null)}),j.on("error",()=>{Y(null)})})}function rB(f,$,J,W){let H=f.split("/"),Q=H[H.length-1]??"";if(H.length-1>W)return!1;for(let X=0;X<H.length-1;X++)if($.has(H[X]??""))return!1;let j=$8.posix.extname(Q).slice(1).toLowerCase();return J.has(j)||!j&&!Q.startsWith(".")}function J8(f={}){let{includeExtensions:$=vB,excludeDirs:J=uB,maxResults:W=100,contextLines:H=2,maxDepth:Q=20}=f,Z=new Set(J),j=new Set($.map((X)=>X.toLowerCase()));return async(X,A,P)=>{if(P.signal?.aborted)throw Error("Search operation aborted");let B=await cB(),Y=null;if(B)Y=await dB(X,A,W,H,5000,P.signal);if(Y){let y=[`Found ${Y.length} result${Y.length===1?"":"s"} for pattern: ${X}`,""];for(let D of Y)y.push(`${D.file}:${D.line}:${D.column}`),y.push(...D.context),y.push("");if(Y.length>=W)y.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return y.join(`
|
|
122
|
+
`)}let V;try{V=new RegExp(X,"gim")}catch(y){throw Error(`Invalid regex pattern: ${X}. ${y instanceof Error?y.message:""}`)}let R=[],U=0,K=await t0(A);for(let y of K){if(P.signal?.aborted)throw Error("Search operation aborted");if(!rB(y,Z,j,Q))continue;if(R.length>=W)break;U++;let D=$8.join(A,y);try{let T=(await u9.readFile(D,"utf-8")).split(`
|
|
123
|
+
`);for(let _=0;_<T.length;_++){let L=T[_];V.lastIndex=0;let O=V.exec(L);while(O!==null){if(R.length>=W)break;let e=Math.max(0,_-H),ff=Math.min(T.length-1,_+H),a=[];for(let g=e;g<=ff;g++){let Pf=g===_?">":" ";a.push(`${Pf} ${g+1}: ${T[g]}`)}if(R.push({file:y,line:_+1,column:O.index+1,match:O[0],context:a}),O.index===V.lastIndex)V.lastIndex++;O=V.exec(L)}}}catch{}}if(R.length===0)return`No results found for pattern: ${X}
|
|
124
|
+
Searched ${U} files.`;let F=[`Found ${R.length} result${R.length===1?"":"s"} for pattern: ${X}`,`Searched ${U} files.`,""];for(let y of R)F.push(`${y.file}:${y.line}:${y.column}`),F.push(...y.context),F.push("");if(R.length>=W)F.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return F.join(`
|
|
125
|
+
`)}}function lB(f){return f.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
|
|
126
126
|
`).replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/&#(\d+);/g,($,J)=>String.fromCharCode(parseInt(J,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
|
|
127
127
|
`).replace(/\n{3,}/g,`
|
|
128
128
|
|
|
129
|
-
`).trim()}function
|
|
130
|
-
[Content truncated: showing first 50000 of ${
|
|
131
|
-
`)}catch(
|
|
129
|
+
`).trim()}function W8(f={}){let{timeoutMs:$=30000,maxResponseBytes:J=5000000,userAgent:W="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:H={},followRedirects:Q=!0}=f;return async(Z,j,X)=>{let A;try{A=new URL(Z)}catch{throw Error(`Invalid URL: ${Z}`)}if(!["http:","https:"].includes(A.protocol))throw Error(`Invalid protocol: ${A.protocol}. Only http and https are supported.`);let P=new AbortController,B=setTimeout(()=>P.abort(),$),Y;if(X.signal)Y=()=>P.abort(),X.signal.addEventListener("abort",Y);try{let V=await fetch(Z,{method:"GET",headers:{"User-Agent":W,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...H},redirect:Q?"follow":"manual",signal:P.signal});if(clearTimeout(B),!Q&&V.status>=300&&V.status<400)return`Redirect to: ${V.headers.get("location")}`;if(!V.ok)throw Error(`HTTP ${V.status}: ${V.statusText}`);let R=V.headers.get("content-type")||"",U=V.body?.getReader();if(!U)throw Error("Failed to read response body");let K=[],F=0;while(!0){let{done:L,value:O}=await U.read();if(L)break;if(F+=O.length,F>J)throw U.cancel(),Error(`Response too large: exceeded ${J} bytes`);K.push(O)}let y=new Uint8Array(F),D=0;for(let L of K)y.set(L,D),D+=L.length;let M=new TextDecoder("utf-8").decode(y),T;if(R.includes("text/html")||R.includes("application/xhtml"))T=lB(M);else if(R.includes("application/json"))try{let L=JSON.parse(M);T=JSON.stringify(L,null,2)}catch{T=M}else T=M;let _=[`URL: ${Z}`,`Content-Type: ${R}`,`Size: ${F} bytes`,"","--- Content ---",T.slice(0,50000)];if(T.length>50000)_.push(`
|
|
130
|
+
[Content truncated: showing first 50000 of ${T.length} characters]`);return _.push("","--- Analysis Request ---",`Prompt: ${j}`),_.join(`
|
|
131
|
+
`)}catch(V){if(clearTimeout(B),V instanceof Error){if(V.name==="AbortError")throw Error(`Request timed out after ${$}ms`);throw V}throw Error(`Fetch failed: ${String(V)}`)}finally{if(X.signal&&Y)X.signal.removeEventListener("abort",Y)}}}function H8(f={}){return{readFile:o2(f.fileRead),search:J8(f.search),bash:t2(f.bash),webFetch:W8(f.webFetch),applyPatch:a2(f.applyPatch),editor:s2(f.editor)}}var pB={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"},R1=[{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 c9(f,$){if(!$||$.length===0)return!0;let J=f.toLowerCase();return $.some((W)=>J.includes(W.toLowerCase()))}function iB(f,$,J,W){if(f.mode&&f.mode!=="any"&&f.mode!==W)return!1;return c9($,f.providerIdIncludes)&&c9(J,f.modelIdIncludes)}function F1(f,$,J,W){if(!W||W.length===0)return{};let H=new Map;for(let Z of W){if(!iB(Z,f,$,J))continue;for(let j of Z.disableTools??[])H.set(j,!1);for(let j of Z.enableTools??[])H.set(j,!0)}let Q={};for(let[Z,j]of H.entries())Q[pB[Z]]=j;return Q}var df={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 M0(f){if(f.mode==="plan")return"plan";if(f.mode==="yolo")return"yolo";return"act"}function d9(f){if(f!=="yolo")return{};let $={enabled:!0,autoApprove:!0},J={"*":$};for(let W of b$)J[W]=$;return J}function r9(f,$){let J=df[f],{enableSpawnAgent:W,enableAgentTeams:H,...Q}=J;return E$({...Q,...$})}import{createTool as gY,zodToJsonSchema as vY}from"@cline/shared";import{z as JJ}from"zod";import{createAgentRuntime as wY}from"@cline/agents";import{createContributionRegistry as bY}from"@cline/shared";import{createGateway as nB,MODEL_COLLECTIONS_BY_PROVIDER_ID as aB}from"@cline/llms";function i6(f){let $=f.providerConfig;if($?.knownModels)return $.knownModels;if(f.knownModels)return f.knownModels;return aB[f.providerId]?.models??void 0}function l9(f,$){let J=f.providerConfig,W=J?.providerId===f.providerId?J:void 0,H={...W??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??W?.apiKey,baseUrl:f.baseUrl??W?.baseUrl,headers:f.headers??W?.headers,knownModels:i6(f),maxOutputTokens:f.maxTokensPerTurn,reasoningEffort:f.reasoningEffort,thinkingBudgetTokens:f.thinkingBudgetTokens,thinking:f.thinking,logger:$,extensionContext:f.extensionContext};return nB({providerConfigs:[{providerId:H.providerId,apiKey:H.apiKey,baseUrl:H.baseUrl,headers:H.headers,models:H.knownModels?Object.entries(H.knownModels).map(([Q,Z])=>({id:Q,name:Z.name??Q,description:Z.description,contextWindow:Z.contextWindow,maxOutputTokens:Z.maxTokens})):void 0}],logger:$}).createAgentModel({providerId:H.providerId,modelId:H.modelId},{maxTokens:H.maxOutputTokens})}import{normalizeUserInput as p9}from"@cline/shared";var tB=50000,sB=6000000,i9=8000,oB=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),eB=new Set(["read","read_files"]),e0="[outdated - see the latest file content]",n9="Tool execution was interrupted before a result was produced.",fY=(f)=>`
|
|
132
132
|
|
|
133
133
|
...[truncated ${f} chars]...
|
|
134
134
|
|
|
135
|
-
|
|
135
|
+
`,$Y=(f)=>`
|
|
136
136
|
|
|
137
137
|
...[truncated ${f} chars to fit provider request budget]...
|
|
138
138
|
|
|
139
|
-
`;class c6{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor(f=EY,$=kY,J=SY){this.maxToolResultChars=f;this.targetToolNames=$;this.maxTotalTextBytes=J}buildForApi(f){this.reindex(f);let J=this.addMissingToolResults(f).map((H)=>{if(!Array.isArray(H.content)){if(H.role==="user"&&typeof H.content==="string"){let Z=v9(H.content);if(Z!==H.content)return{...H,content:Z}}return H}let W=!1,Q=H.content.map((Z)=>{let j=this.transformBlock(Z,H.role);if(j!==Z)W=!0;return j});return W?{...H,content:Q}:H});return this.truncateToTotalTextBudget(J)}transformBlock(f,$){if($==="user"&&f.type==="text"&&typeof f.text==="string"){let W=v9(f.text);if(W!==f.text)return{...f,text:W};return f}if(f.type==="file"){let W=this.truncateMiddle(f.content);return W===f.content?f:{...f,content:W}}if(f.type!=="tool_result")return f;let J=this.toolNameByIdCache.get(f.tool_use_id),H=f.content;if(this.isReadTool(J)&&f.is_error!==!0){let W=this.getReadLocators(f);if(W.length>0){let Q=W.filter((Z)=>this.isOutdatedReadLocator(Z,f.tool_use_id));if(Q.length>0)H=this.replaceOutdatedReadContent(H,Q)}}if(this.shouldTruncateTool(J))H=this.truncateToolResultContent(H);return H===f.content?f:{...f,content:H}}reindex(f){let $=this.indexedMessageCount===0||f.length>=this.indexedMessageCount&&f[this.indexedMessageCount-1]===this.indexedTailRef;if(f.length<this.indexedMessageCount||!$)this.resetIndexes();for(let J=this.indexedMessageCount;J<f.length;J++){let H=f[J];if(!Array.isArray(H.content))continue;for(let W=0;W<H.content.length;W++){let Q=H.content[W];if(Q.type==="file")this.latestFullContentOwnerByPathCache.set(Q.path,`file:${J}:${W}`);else if(Q.type==="tool_use"){let Z=Q.name.toLowerCase();if(this.toolNameByIdCache.set(Q.id,Z),this.isReadTool(Z)){let j=this.extractLocatorsFromReadToolInput(Q.input);if(j.length>0)this.readLocatorsByToolUseIdCache.set(Q.id,j)}}else if(Q.type==="tool_result"){let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.isReadTool(Z)||Q.is_error===!0)continue;let j=this.getReadLocators(Q);for(let P of j)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(P),Q.tool_use_id),this.isFullFileRead(P))this.latestFullContentOwnerByPathCache.set(P.path,Q.tool_use_id)}}}this.indexedMessageCount=f.length,this.indexedTailRef=f.length>0?f[f.length-1]:void 0}addMissingToolResults(f){let $=this.collectToolResultIds(f),J=[],H=new Map,W=!1,Q=()=>{if(H.size===0)return;Z(this.createMissingToolResultMessage(H)),H.clear(),W=!0},Z=(j)=>{let P=J.at(-1);if(this.shouldMergeUserAfterToolResults(P,j)){J[J.length-1]={...P,content:[...P.content,...this.contentBlocksForUserMerge(j.content)]},W=!0;return}J.push(j)};for(let j of f){if(this.isToolResultOnlyMessage(j)){if(Z(this.appendMissingToolResults(j,H)),H.size>0)H.clear(),W=!0;continue}if(Array.isArray(j.content)){let P=j.content.filter((V)=>V.type==="tool_result"),X=j.content.filter((V)=>V.type!=="tool_result");if(P.length>0){let V=this.appendMissingToolResults({...j,role:"user",content:P},H);if(Z(V),H.size>0)H.clear();W=!0}if(X.length>0||P.length===0){if(P.length===0)Q();let V=P.length>0?{...j,content:X}:j;if(Z(V),V.role==="assistant")this.trackMissingToolCalls(V,$,H)}continue}Q(),Z(j)}return Q(),W?J:f}appendMissingToolResults(f,$){if($.size===0||!Array.isArray(f.content))return f;return{...f,role:"user",content:[...f.content,...this.createMissingToolResultBlocks($)]}}shouldMergeUserAfterToolResults(f,$){return f?.role==="user"&&$.role==="user"&&this.isToolResultOnlyMessage(f)&&this.contentBlocksForUserMerge($.content).length>0}contentBlocksForUserMerge(f){return typeof f==="string"?f.length>0?[{type:"text",text:f}]:[]:f}collectToolResultIds(f){let $=new Set;for(let J of f){if(!Array.isArray(J.content))continue;for(let H of J.content)if(H.type==="tool_result")$.add(H.tool_use_id)}return $}isToolResultOnlyMessage(f){return f.role==="user"&&Array.isArray(f.content)&&f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}trackMissingToolCalls(f,$,J){if(!Array.isArray(f.content))return;for(let H of f.content){if(H.type!=="tool_use"||$.has(H.id))continue;J.set(H.id,H.name)}}createMissingToolResultMessage(f){return{role:"user",content:this.createMissingToolResultBlocks(f)}}createMissingToolResultBlocks(f){return Array.from(f,([$,J])=>({type:"tool_result",tool_use_id:$,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText(f){return f?`${c9} Tool: ${f}.`:c9}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators(f){let $=f,J=this.readResultLocatorCache.get($);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent(f.content),this.readResultLocatorCache.set($,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get(f.tool_use_id)??[]}extractLocatorsFromReadToolInput(f){if(!f||typeof f!=="object")return[];let $=f,J=[],H=this.extractLocatorFromReadRequest($);if(H)J.push(H);if(Array.isArray($.files))for(let W of $.files){let Q=this.extractLocatorFromReadRequest(W);if(Q)J.push(Q)}if(Array.isArray($.file_paths)){for(let W of $.file_paths)if(typeof W==="string"&&W.length>0)J.push({path:W,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent(f){if(typeof f==="string")return this.tryParseReadLocators(f);for(let $ of f){if($.type!=="text")continue;let J=this.tryParseReadLocators($.text);if(J.length>0)return J}return[]}tryParseReadLocators(f){try{return this.extractLocatorsFromParsedReadResult(JSON.parse(f))}catch{return[]}}extractLocatorsFromParsedReadResult(f){if(Array.isArray(f)){let J=[];for(let H of f){let W=this.extractLocatorFromResultEntry(H);if(W)J.push(W)}return this.dedupeReadLocators(J)}let $=this.extractLocatorFromResultEntry(f);return $?[$]:[]}extractLocatorFromReadRequest(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(!J)return;return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)}}extractLocatorFromResultEntry(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(J)return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)};if(typeof $.query==="string"&&$.query.length>0)return this.parseReadQuery($.query);return}extractPath(f){let $=[f.path,f.file_path,f.filePath];for(let J of $)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber(f){return typeof f==="number"&&Number.isInteger(f)?f:null}parseReadQuery(f){let $=/^(.*):(\d+)-(EOF|\d+)$/.exec(f);if(!$)return{path:f,startLine:null,endLine:null};return{path:$[1],startLine:Number($[2]),endLine:$[3]==="EOF"?null:Number($[3])}}dedupeReadLocators(f){let $=new Map;for(let J of f)$.set(this.toReadLocatorKey(J),J);return Array.from($.values())}toReadLocatorKey(f){if(this.isFullFileRead(f))return f.path;return`${f.path}:${f.startLine??1}-${f.endLine??"EOF"}`}isFullFileRead(f){return f.startLine==null&&f.endLine==null}isOutdatedReadLocator(f,$){let J=this.latestFullContentOwnerByPathCache.get(f.path);if(J&&J!==$)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey(f))!==$}replaceOutdatedReadContent(f,$){let J=new Set($.map((Q)=>this.toReadLocatorKey(Q))),H=new Set($.map((Q)=>Q.path));if(typeof f==="string")return this.replaceOutdatedInString(f,J)??n0;let W=0;for(let Q of f)if(Q.type==="text")W+=this.countOutdatedImageEntries(Q.text,J);return f.map((Q)=>{if(Q.type==="file"){if(!H.has(Q.path))return Q;return{...Q,content:n0}}if(Q.type==="image"){if(W===0)return Q;return W-=1,{type:"text",text:n0}}if(Q.type!=="text")return Q;let Z=this.replaceOutdatedInString(Q.text,J);if(Z===null)return{...Q,text:n0};return Z===Q.text?Q:{...Q,text:Z}})}countOutdatedImageEntries(f,$){let J;try{J=JSON.parse(f)}catch{return 0}let H=Array.isArray(J)?J:[J],W=0;for(let Q of H){if(!Q||typeof Q!=="object")continue;let Z=Q,j=this.extractLocatorFromResultEntry(Z);if(!j)continue;if(!$.has(this.toReadLocatorKey(j)))continue;if(Z.result==="Successfully read image"||Z.content==="Successfully read image")W+=1}return W}replaceOutdatedInString(f,$){let J;try{J=JSON.parse(f)}catch{return null}let H=Array.isArray(J)?J.map((W)=>this.replaceOutdatedReadEntry(W,$)):this.replaceOutdatedReadEntry(J,$);return JSON.stringify(H)}replaceOutdatedReadEntry(f,$){if(!f||typeof f!=="object")return f;let J=this.extractLocatorFromResultEntry(f);if(!J||!$.has(this.toReadLocatorKey(J)))return f;let H={...f};if(typeof H.result==="string")H.result=n0;else if(typeof H.content==="string")H.content=n0;else H.result=n0;return H}isReadTool(f){return!!f&&mY.has(f)}shouldTruncateTool(f){return!!f&&this.targetToolNames.has(f)}truncateToolResultContent(f){if(typeof f==="string")return this.truncateMiddle(f);return f.map(($)=>{if($.type==="file"){let H=this.truncateMiddle($.content);return H===$.content?$:{...$,content:H}}if($.type!=="text")return $;let J=this.truncateMiddle($.text);return J===$.text?$:{...$,text:J}})}truncateMiddle(f){return u6(f,this.maxToolResultChars,IY)}truncateToTotalTextBudget(f){if(this.maxTotalTextBytes<=0)return f;let $=this.countMessageTextBytes(f);if($<=this.maxTotalTextBytes)return f;let J=f.map((W)=>{if(!Array.isArray(W.content))return W;return{...W,content:W.content.map((Q)=>vY(Q))}}),H=this.collectTruncationCandidates(J);for(let W of H){if($<=this.maxTotalTextBytes)break;let Q=W.byteLength;if(Q<=u9)continue;let Z=$-this.maxTotalTextBytes,j=Math.max(u9,Q-Z),P=gY(W.get(),j,xY);W.set(P),$-=Q-Ff(P)}return J}countMessageTextBytes(f){let $=0;for(let J of f){if(typeof J.content==="string"){$+=Ff(J.content);continue}for(let H of J.content)if(H.type==="text")$+=Ff(H.text);else if(H.type==="thinking")$+=Ff(H.thinking);else if(H.type==="file")$+=Ff(H.content);else if(H.type==="tool_result"){if(typeof H.content==="string")$+=Ff(H.content);else for(let W of H.content)if(W.type==="text")$+=Ff(W.text);else if(W.type==="file")$+=Ff(W.content)}}return $}collectTruncationCandidates(f){let $=[];for(let J of f){if(!Array.isArray(J.content))continue;for(let H of J.content){if(H.type!=="tool_result")continue;let W=this.toolNameByIdCache.get(H.tool_use_id);if(!this.shouldTruncateTool(W))continue;if(typeof H.content==="string"){$.push({byteLength:Ff(H.content),get:()=>H.content,set:(Q)=>{H.content=Q}});continue}for(let Q of H.content)if(Q.type==="text")$.push({byteLength:Ff(Q.text),get:()=>Q.text,set:(Z)=>{Q.text=Z}});else if(Q.type==="file")$.push({byteLength:Ff(Q.content),get:()=>Q.content,set:(Z)=>{Q.content=Z}})}}return $.sort((J,H)=>H.byteLength-J.byteLength)}}function Ff(f){return Buffer.byteLength(f,"utf8")}function u6(f,$,J){if(f.length<=$)return f;let H=J(f.length-$),W=Math.max(0,Math.floor(($-H.length)/2)),Q=Math.max(0,f.length-W*2),Z=J(Q),j=Math.max(0,Math.floor(($-Z.length)/2)),P=f.slice(0,j),X=j>0?f.slice(-j):"";return`${P}${Z}${X}`}function gY(f,$,J){if(Ff(f)<=$)return f;let H=0,W=f.length,Q=u6(f,0,J);while(H<=W){let Z=H+W>>>1,j=u6(f,Z,J);if(Ff(j)<=$)Q=j,H=Z+1;else W=Z-1}return Q}function vY(f){if(f.type!=="tool_result"||typeof f.content==="string")return{...f};return{...f,content:f.content.map(($)=>({...$}))}}function d6(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class r6{messages=[];conversationId=d6();sessionStarted=!1;constructor(f){if((f?.length??0)>0)this.restore(f??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage(f){this.messages.push(f)}appendMessages(f){if(f.length===0)return;this.messages.push(...f)}replaceMessages(f){this.messages=[...f]}resetForRun(){this.messages=[],this.conversationId=d6(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=d6(),this.sessionStarted=!1}restore(f){this.messages=[...f],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function uY(f){let $=dY(f.content),J=[],H=f.id??pY(),W=0,Q=[],Z=()=>{if(Q.length===0)return;let j=W===0?H:`${H}_part_${W}`;W+=1,J.push({id:j,role:f.role,content:Q.map(rY),createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:d9(f.metrics)}),Q=[]};if($.length===0)return J.push({id:H,role:f.role,content:[],createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:d9(f.metrics)}),J;for(let j of $){if(j.type!=="tool_result"){Q.push(j);continue}Z(),J.push({id:`${H}_tool_${j.tool_use_id}`,role:"tool",content:[p9(j)],createdAt:f.ts??Date.now(),metadata:f.metadata})}return Z(),J}function $8(f){return f.flatMap(uY)}function cY(f){let $=f.content.map(i9).filter((J)=>J!==void 0);return{id:f.id,role:f.role==="tool"?"user":f.role,content:$,ts:f.createdAt,metadata:f.metadata,modelInfo:f.modelInfo,metrics:lY(f.metrics)}}function b$(f){return f.map(cY)}function l9(f){let $=[];for(let J of f){let H=J.content.map(i9).filter((Z)=>Z!==void 0),W=J.role==="tool"?"user":J.role,Q=$[$.length-1];if(W==="user"&&H.length>0&&H.every((Z)=>Z.type==="tool_result")&&Q?.role==="user"&&Array.isArray(Q.content)&&Q.content.every((Z)=>Z.type==="tool_result")){Q.content.push(...H);continue}$.push({role:W,content:H})}return $}function dY(f){if(typeof f==="string")return f.length>0?[{type:"text",text:f}]:[];return[...f]}function rY(f){switch(f.type){case"text":return{type:"text",text:f.text};case"thinking":return{type:"reasoning",text:f.thinking,metadata:f.signature?{signature:f.signature,details:f.details}:f.details?{details:f.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:f.data}};case"image":return{type:"image",image:f.data,mediaType:f.mediaType};case"file":return{type:"file",path:f.path,content:f.content};case"tool_use":return{type:"tool-call",toolCallId:f.id,toolName:f.name,input:f.input,metadata:f.signature?{signature:f.signature}:void 0};case"tool_result":return p9(f)}}function p9(f){return{type:"tool-result",toolCallId:f.tool_use_id,toolName:"",output:f.content,isError:f.is_error}}function i9(f){switch(f.type){case"text":return{type:"text",text:f.text};case"reasoning":{if(f.redacted===!0)return{type:"redacted_thinking",data:f.metadata?.data??""};let $=f.metadata;return{type:"thinking",thinking:f.text,signature:$?.signature,details:$?.details}}case"image":return typeof f.image==="string"?{type:"image",data:f.image,mediaType:f.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:f.path,content:f.content};case"tool-call":return{type:"tool_use",id:f.toolCallId,name:f.toolName,input:f.input??{},signature:f.metadata?.signature};case"tool-result":{let $=f.output,J=typeof $==="string"?$:Array.isArray($)?$:JSON.stringify($);return{type:"tool_result",tool_use_id:f.toolCallId,content:J,is_error:f.isError}}}}function d9(f){if(!f)return;return{inputTokens:f.inputTokens??0,outputTokens:f.outputTokens??0,cacheReadTokens:f.cacheReadTokens??0,cacheWriteTokens:f.cacheWriteTokens??0,cost:f.cost}}function lY(f){if(!f)return;return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,cost:f.cost}}var r9=0;function pY(){return r9+=1,`msg_${Date.now().toString(36)}_${r9.toString(36)}`}function n9(f){let{agentConfig:$}=f,J=iY($),H=nY($),W=f.hooks,Q=aY($.maxParallelToolCalls);return{sessionId:f.sessionId??$.sessionId,agentId:f.agentId,conversationId:f.conversationId,parentAgentId:f.parentAgentId,agentRole:f.agentRole,systemPrompt:f.systemPrompt??$.systemPrompt,messageModelInfo:H,model:f.model,modelOptions:J,tools:f.tools,hooks:W,prepareTurn:f.prepareTurn,consumePendingUserMessage:$.consumePendingUserMessage,plugins:f.plugins,logger:f.logger??$.logger,telemetry:f.telemetry??tY($.telemetry),initialMessages:f.initialMessages,completionPolicy:$.completionPolicy,maxIterations:$.maxIterations,toolExecution:Q,toolPolicies:$.toolPolicies,toolContextMetadata:f.toolContextMetadata,requestToolApproval:$.requestToolApproval}}function iY(f){let $={};if(f.thinking!==void 0)$.thinking=f.thinking;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;if(f.maxTokensPerTurn!==void 0)$.maxTokensPerTurn=f.maxTokensPerTurn;if(f.apiTimeoutMs!==void 0)$.apiTimeoutMs=f.apiTimeoutMs;return Object.keys($).length>0?$:void 0}function nY(f){let $=f.providerConfig?.family;return{id:f.modelId,provider:f.providerId,family:$}}function aY(f){if(f===void 0)return;return f>=2?"parallel":"sequential"}function tY(f){if(!f)return;return{capture:($,J)=>{f.capture({event:$,properties:J})}}}function sY(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function oY(f){f.lastToolName="",f.lastToolSignature="",f.consecutiveIdenticalCount=0}function l6(f){if(f==null||typeof f!=="object")return f;if(Array.isArray(f))return f.map(l6);let $={};for(let J of Object.keys(f).sort())$[J]=l6(f[J]);return $}function eY(f){if(f==null)return"null";if(typeof f==="string")return f;if(typeof f!=="object")return String(f);try{return JSON.stringify(l6(f))}catch{return String(f)}}function fB(f,$,J,H){if($===f.lastToolName&&J===f.lastToolSignature)f.consecutiveIdenticalCount++;else f.consecutiveIdenticalCount=1;return f.lastToolName=$,f.lastToolSignature=J,{softWarning:f.consecutiveIdenticalCount===H.softThreshold,hardEscalation:f.consecutiveIdenticalCount>=H.hardThreshold}}var a9={softThreshold:3,hardThreshold:5};class p6{config;state=sY();constructor(f){this.config={softThreshold:f?.softThreshold??a9.softThreshold,hardThreshold:f?.hardThreshold??a9.hardThreshold}}inspect(f){let $=eY(f.input),J=fB(this.state,f.name,$,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){oY(this.state)}}class i6{consecutiveMistakes=0;options;constructor(f){this.options=f}async record(f){let $=this.options.maxConsecutiveMistakes,J=f.forceAtLimit&&$?$:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let H=f.details?.trim()||`consecutive mistake (${f.reason})`;if(this.options.emit({type:"error",error:Error(H),recoverable:!0,iteration:f.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:f.iteration,reason:f.reason,details:f.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!$||J<$)return{action:"continue"};let W=await JB({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details},this.options.onLimitReached);if(W.action==="continue"){let Q=W.guidance?.trim();if(Q)this.options.appendRecoveryNotice(Q,f.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:Q}}return{action:"stop",reason:W.reason?.trim()||void 0,message:$B({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details,stopReason:W.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function $B(f){let $=[`Stopped after ${f.consecutiveMistakes}/${f.maxConsecutiveMistakes} consecutive mistakes (${f.reason}) at iteration ${f.iteration}.`],J=f.details?.trim();if(J)$.push(`Error: ${J}`);let H=f.stopReason?.trim();if(H)$.push(`Decision: ${H}`);return $.push("Session state was preserved. Send a new prompt to resume from the latest state."),$.join(" ")}async function JB(f,$){if(!$)return{action:"stop",reason:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`};try{return await $(f)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`}}}function HB(f){let $=f.content.filter((J)=>J.type==="text");if($.length===0)return;return $.map((J)=>J.text).join("")}function WB(f){let $=f.content.filter((J)=>J.type==="reasoning");if($.length===0)return;return{reasoning:$.map((J)=>J.text).join(""),redacted:$.some((J)=>J.redacted===!0)}}function QB(f){return f.content.find(($)=>$.type==="tool-result")}function ZB(f){switch(f){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function jB(f){if(!f||f.isError!==!0)return;if(typeof f.output==="string")return f.output;if(f.output instanceof Error)return f.output.message;try{return JSON.stringify(f.output)}catch{return String(f.output)}}class n6{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate(f){switch(f.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:f.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:f.iteration,hadToolCalls:f.toolCallCount>0,toolCallCount:f.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:f.text,accumulated:f.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:f.text,redacted:f.redacted===!0}];case"assistant-message":return this.translateAssistantMessage(f.message);case"tool-started":return this.translateToolStarted(f);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,update:f.update}];case"tool-finished":return this.translateToolFinished(f);case"usage-updated":return this.translateUsage(f.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:f.message,reason:f.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:f.metadata}];case"run-finished":return this.translateRunFinished(f.result);case"run-failed":return[{type:"error",error:f.error,recoverable:!1,iteration:f.snapshot.iteration}];default:return f}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage(f){let $=[],J=HB(f);if(J!==void 0)$.push({type:"content_end",contentType:"text",text:J});let H=WB(f);if(H!==void 0)$.push({type:"content_end",contentType:"reasoning",reasoning:H.reasoning});return $}translateToolStarted(f){return this.toolStartedAt.set(f.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,input:f.toolCall.input}]}translateToolFinished(f){let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=$===void 0?void 0:Date.now()-$;this.toolStartedAt.delete(f.toolCall.toolCallId);let H=QB(f.message),W=H?.output,Q=jB(H);return[{type:"content_end",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,output:W,error:Q,durationMs:J}]}translateUsage(f){let $=f.inputTokens-this.lastUsage.inputTokens,J=f.outputTokens-this.lastUsage.outputTokens,H=f.cacheReadTokens-this.lastUsage.cacheReadTokens,W=f.cacheWriteTokens-this.lastUsage.cacheWriteTokens,Q=this.lastUsage.totalCost??0,j=(f.totalCost??0)-Q;return this.lastUsage={inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,totalCost:f.totalCost},[{type:"usage",inputTokens:Math.max(0,$),outputTokens:Math.max(0,J),cacheReadTokens:H===0?void 0:Math.max(0,H),cacheWriteTokens:W===0?void 0:Math.max(0,W),cost:j===0?void 0:j,totalInputTokens:f.inputTokens,totalOutputTokens:f.outputTokens,totalCacheReadTokens:f.cacheReadTokens===0?void 0:f.cacheReadTokens,totalCacheWriteTokens:f.cacheWriteTokens===0?void 0:f.cacheWriteTokens,totalCost:f.totalCost}]}translateRunFinished(f){let $={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens===0?void 0:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens===0?void 0:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost};return[{type:"done",reason:ZB(f.status),text:f.outputText,iterations:f.iterations,usage:$}]}}function FB(f){if(typeof f==="string")return f;if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}}async function yB(f){let J=(typeof f.content==="function"?await f.content():f.content).trim();return J.length>0?J:void 0}function KB(f,$){let J=f.trim(),H=$.map((W)=>W.trim()).filter(Boolean).join(`
|
|
139
|
+
`;class a6{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor(f=tB,$=oB,J=sB){this.maxToolResultChars=f;this.targetToolNames=$;this.maxTotalTextBytes=J}buildForApi(f){this.reindex(f);let J=this.addMissingToolResults(f).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let Z=p9(W.content);if(Z!==W.content)return{...W,content:Z}}return W}let H=!1,Q=W.content.map((Z)=>{let j=this.transformBlock(Z,W.role);if(j!==Z)H=!0;return j});return H?{...W,content:Q}:W});return this.truncateToTotalTextBudget(J)}transformBlock(f,$){if($==="user"&&f.type==="text"&&typeof f.text==="string"){let H=p9(f.text);if(H!==f.text)return{...f,text:H};return f}if(f.type==="file"){let H=this.truncateMiddle(f.content);return H===f.content?f:{...f,content:H}}if(f.type!=="tool_result")return f;let J=this.toolNameByIdCache.get(f.tool_use_id),W=f.content;if(this.isReadTool(J)&&f.is_error!==!0){let H=this.getReadLocators(f);if(H.length>0){let Q=H.filter((Z)=>this.isOutdatedReadLocator(Z,f.tool_use_id));if(Q.length>0)W=this.replaceOutdatedReadContent(W,Q)}}if(this.shouldTruncateTool(J))W=this.truncateToolResultContent(W);return W===f.content?f:{...f,content:W}}reindex(f){let $=this.indexedMessageCount===0||f.length>=this.indexedMessageCount&&f[this.indexedMessageCount-1]===this.indexedTailRef;if(f.length<this.indexedMessageCount||!$)this.resetIndexes();for(let J=this.indexedMessageCount;J<f.length;J++){let W=f[J];if(!Array.isArray(W.content))continue;for(let H=0;H<W.content.length;H++){let Q=W.content[H];if(Q.type==="file")this.latestFullContentOwnerByPathCache.set(Q.path,`file:${J}:${H}`);else if(Q.type==="tool_use"){let Z=Q.name.toLowerCase();if(this.toolNameByIdCache.set(Q.id,Z),this.isReadTool(Z)){let j=this.extractLocatorsFromReadToolInput(Q.input);if(j.length>0)this.readLocatorsByToolUseIdCache.set(Q.id,j)}}else if(Q.type==="tool_result"){let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.isReadTool(Z)||Q.is_error===!0)continue;let j=this.getReadLocators(Q);for(let X of j)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(X),Q.tool_use_id),this.isFullFileRead(X))this.latestFullContentOwnerByPathCache.set(X.path,Q.tool_use_id)}}}this.indexedMessageCount=f.length,this.indexedTailRef=f.length>0?f[f.length-1]:void 0}addMissingToolResults(f){let $=this.collectToolResultIds(f),J=[],W=new Map,H=!1,Q=()=>{if(W.size===0)return;Z(this.createMissingToolResultMessage(W)),W.clear(),H=!0},Z=(j)=>{let X=J.at(-1);if(this.shouldMergeUserAfterToolResults(X,j)){J[J.length-1]={...X,content:[...X.content,...this.contentBlocksForUserMerge(j.content)]},H=!0;return}J.push(j)};for(let j of f){if(this.isToolResultOnlyMessage(j)){if(Z(this.appendMissingToolResults(j,W)),W.size>0)W.clear(),H=!0;continue}if(Array.isArray(j.content)){let X=j.content.filter((P)=>P.type==="tool_result"),A=j.content.filter((P)=>P.type!=="tool_result");if(X.length>0){let P=this.appendMissingToolResults({...j,role:"user",content:X},W);if(Z(P),W.size>0)W.clear();H=!0}if(A.length>0||X.length===0){if(X.length===0)Q();let P=X.length>0?{...j,content:A}:j;if(Z(P),P.role==="assistant")this.trackMissingToolCalls(P,$,W)}continue}Q(),Z(j)}return Q(),H?J:f}appendMissingToolResults(f,$){if($.size===0||!Array.isArray(f.content))return f;return{...f,role:"user",content:[...f.content,...this.createMissingToolResultBlocks($)]}}shouldMergeUserAfterToolResults(f,$){return f?.role==="user"&&$.role==="user"&&this.isToolResultOnlyMessage(f)&&this.contentBlocksForUserMerge($.content).length>0}contentBlocksForUserMerge(f){return typeof f==="string"?f.length>0?[{type:"text",text:f}]:[]:f}collectToolResultIds(f){let $=new Set;for(let J of f){if(!Array.isArray(J.content))continue;for(let W of J.content)if(W.type==="tool_result")$.add(W.tool_use_id)}return $}isToolResultOnlyMessage(f){return f.role==="user"&&Array.isArray(f.content)&&f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}trackMissingToolCalls(f,$,J){if(!Array.isArray(f.content))return;for(let W of f.content){if(W.type!=="tool_use"||$.has(W.id))continue;J.set(W.id,W.name)}}createMissingToolResultMessage(f){return{role:"user",content:this.createMissingToolResultBlocks(f)}}createMissingToolResultBlocks(f){return Array.from(f,([$,J])=>({type:"tool_result",tool_use_id:$,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText(f){return f?`${n9} Tool: ${f}.`:n9}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators(f){let $=f,J=this.readResultLocatorCache.get($);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent(f.content),this.readResultLocatorCache.set($,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get(f.tool_use_id)??[]}extractLocatorsFromReadToolInput(f){if(!f||typeof f!=="object")return[];let $=f,J=[],W=this.extractLocatorFromReadRequest($);if(W)J.push(W);if(Array.isArray($.files))for(let H of $.files){let Q=this.extractLocatorFromReadRequest(H);if(Q)J.push(Q)}if(Array.isArray($.file_paths)){for(let H of $.file_paths)if(typeof H==="string"&&H.length>0)J.push({path:H,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent(f){if(typeof f==="string")return this.tryParseReadLocators(f);for(let $ of f){if($.type!=="text")continue;let J=this.tryParseReadLocators($.text);if(J.length>0)return J}return[]}tryParseReadLocators(f){try{return this.extractLocatorsFromParsedReadResult(JSON.parse(f))}catch{return[]}}extractLocatorsFromParsedReadResult(f){if(Array.isArray(f)){let J=[];for(let W of f){let H=this.extractLocatorFromResultEntry(W);if(H)J.push(H)}return this.dedupeReadLocators(J)}let $=this.extractLocatorFromResultEntry(f);return $?[$]:[]}extractLocatorFromReadRequest(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(!J)return;return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)}}extractLocatorFromResultEntry(f){if(!f||typeof f!=="object")return;let $=f,J=this.extractPath($);if(J)return{path:J,startLine:this.extractLineNumber($.start_line),endLine:this.extractLineNumber($.end_line)};if(typeof $.query==="string"&&$.query.length>0)return this.parseReadQuery($.query);return}extractPath(f){let $=[f.path,f.file_path,f.filePath];for(let J of $)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber(f){return typeof f==="number"&&Number.isInteger(f)?f:null}parseReadQuery(f){let $=/^(.*):(\d+)-(EOF|\d+)$/.exec(f);if(!$)return{path:f,startLine:null,endLine:null};return{path:$[1],startLine:Number($[2]),endLine:$[3]==="EOF"?null:Number($[3])}}dedupeReadLocators(f){let $=new Map;for(let J of f)$.set(this.toReadLocatorKey(J),J);return Array.from($.values())}toReadLocatorKey(f){if(this.isFullFileRead(f))return f.path;return`${f.path}:${f.startLine??1}-${f.endLine??"EOF"}`}isFullFileRead(f){return f.startLine==null&&f.endLine==null}isOutdatedReadLocator(f,$){let J=this.latestFullContentOwnerByPathCache.get(f.path);if(J&&J!==$)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey(f))!==$}replaceOutdatedReadContent(f,$){let J=new Set($.map((Q)=>this.toReadLocatorKey(Q))),W=new Set($.map((Q)=>Q.path));if(typeof f==="string")return this.replaceOutdatedInString(f,J)??e0;let H=0;for(let Q of f)if(Q.type==="text")H+=this.countOutdatedImageEntries(Q.text,J);return f.map((Q)=>{if(Q.type==="file"){if(!W.has(Q.path))return Q;return{...Q,content:e0}}if(Q.type==="image"){if(H===0)return Q;return H-=1,{type:"text",text:e0}}if(Q.type!=="text")return Q;let Z=this.replaceOutdatedInString(Q.text,J);if(Z===null)return{...Q,text:e0};return Z===Q.text?Q:{...Q,text:Z}})}countOutdatedImageEntries(f,$){let J;try{J=JSON.parse(f)}catch{return 0}let W=Array.isArray(J)?J:[J],H=0;for(let Q of W){if(!Q||typeof Q!=="object")continue;let Z=Q,j=this.extractLocatorFromResultEntry(Z);if(!j)continue;if(!$.has(this.toReadLocatorKey(j)))continue;if(Z.result==="Successfully read image"||Z.content==="Successfully read image")H+=1}return H}replaceOutdatedInString(f,$){let J;try{J=JSON.parse(f)}catch{return null}let W=Array.isArray(J)?J.map((H)=>this.replaceOutdatedReadEntry(H,$)):this.replaceOutdatedReadEntry(J,$);return JSON.stringify(W)}replaceOutdatedReadEntry(f,$){if(!f||typeof f!=="object")return f;let J=this.extractLocatorFromResultEntry(f);if(!J||!$.has(this.toReadLocatorKey(J)))return f;let W={...f};if(typeof W.result==="string")W.result=e0;else if(typeof W.content==="string")W.content=e0;else W.result=e0;return W}isReadTool(f){return!!f&&eB.has(f)}shouldTruncateTool(f){return!!f&&this.targetToolNames.has(f)}truncateToolResultContent(f){if(typeof f==="string")return this.truncateMiddle(f);return f.map(($)=>{if($.type==="file"){let W=this.truncateMiddle($.content);return W===$.content?$:{...$,content:W}}if($.type!=="text")return $;let J=this.truncateMiddle($.text);return J===$.text?$:{...$,text:J}})}truncateMiddle(f){return n6(f,this.maxToolResultChars,fY)}truncateToTotalTextBudget(f){if(this.maxTotalTextBytes<=0)return f;let $=this.countMessageTextBytes(f);if($<=this.maxTotalTextBytes)return f;let J=f.map((H)=>{if(!Array.isArray(H.content))return H;return{...H,content:H.content.map((Q)=>WY(Q))}}),W=this.collectTruncationCandidates(J);for(let H of W){if($<=this.maxTotalTextBytes)break;let Q=H.byteLength;if(Q<=i9)continue;let Z=$-this.maxTotalTextBytes,j=Math.max(i9,Q-Z),X=JY(H.get(),j,$Y);H.set(X),$-=Q-Tf(X)}return J}countMessageTextBytes(f){let $=0;for(let J of f){if(typeof J.content==="string"){$+=Tf(J.content);continue}for(let W of J.content)if(W.type==="text")$+=Tf(W.text);else if(W.type==="thinking")$+=Tf(W.thinking);else if(W.type==="file")$+=Tf(W.content);else if(W.type==="tool_result"){if(typeof W.content==="string")$+=Tf(W.content);else for(let H of W.content)if(H.type==="text")$+=Tf(H.text);else if(H.type==="file")$+=Tf(H.content)}}return $}collectTruncationCandidates(f){let $=[];for(let J of f){if(!Array.isArray(J.content))continue;for(let W of J.content){if(W.type!=="tool_result")continue;let H=this.toolNameByIdCache.get(W.tool_use_id);if(!this.shouldTruncateTool(H))continue;if(typeof W.content==="string"){$.push({byteLength:Tf(W.content),get:()=>W.content,set:(Q)=>{W.content=Q}});continue}for(let Q of W.content)if(Q.type==="text")$.push({byteLength:Tf(Q.text),get:()=>Q.text,set:(Z)=>{Q.text=Z}});else if(Q.type==="file")$.push({byteLength:Tf(Q.content),get:()=>Q.content,set:(Z)=>{Q.content=Z}})}}return $.sort((J,W)=>W.byteLength-J.byteLength)}}function Tf(f){return Buffer.byteLength(f,"utf8")}function n6(f,$,J){if(f.length<=$)return f;let W=J(f.length-$),H=Math.max(0,Math.floor(($-W.length)/2)),Q=Math.max(0,f.length-H*2),Z=J(Q),j=Math.max(0,Math.floor(($-Z.length)/2)),X=f.slice(0,j),A=j>0?f.slice(-j):"";return`${X}${Z}${A}`}function JY(f,$,J){if(Tf(f)<=$)return f;let W=0,H=f.length,Q=n6(f,0,J);while(W<=H){let Z=W+H>>>1,j=n6(f,Z,J);if(Tf(j)<=$)Q=j,W=Z+1;else H=Z-1}return Q}function WY(f){if(f.type!=="tool_result"||typeof f.content==="string")return{...f};return{...f,content:f.content.map(($)=>({...$}))}}function t6(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class s6{messages=[];conversationId=t6();sessionStarted=!1;constructor(f){if((f?.length??0)>0)this.restore(f??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage(f){this.messages.push(f)}appendMessages(f){if(f.length===0)return;this.messages.push(...f)}replaceMessages(f){this.messages=[...f]}resetForRun(){this.messages=[],this.conversationId=t6(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=t6(),this.sessionStarted=!1}restore(f){this.messages=[...f],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function HY(f){let $=ZY(f.content),J=[],W=f.id??AY(),H=0,Q=[],Z=()=>{if(Q.length===0)return;let j=H===0?W:`${W}_part_${H}`;H+=1,J.push({id:j,role:f.role,content:Q.map(jY),createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:a9(f.metrics)}),Q=[]};if($.length===0)return J.push({id:W,role:f.role,content:[],createdAt:f.ts??Date.now(),metadata:f.metadata,modelInfo:f.modelInfo,metrics:a9(f.metrics)}),J;for(let j of $){if(j.type!=="tool_result"){Q.push(j);continue}Z(),J.push({id:`${W}_tool_${j.tool_use_id}`,role:"tool",content:[o9(j)],createdAt:f.ts??Date.now(),metadata:f.metadata})}return Z(),J}function Q8(f){return f.flatMap(HY)}function QY(f){let $=f.content.map(e9).filter((J)=>J!==void 0);return{id:f.id,role:f.role==="tool"?"user":f.role,content:$,ts:f.createdAt,metadata:f.metadata,modelInfo:f.modelInfo,metrics:XY(f.metrics)}}function k$(f){return f.map(QY)}function s9(f){let $=[];for(let J of f){let W=J.content.map(e9).filter((Z)=>Z!==void 0),H=J.role==="tool"?"user":J.role,Q=$[$.length-1];if(H==="user"&&W.length>0&&W.every((Z)=>Z.type==="tool_result")&&Q?.role==="user"&&Array.isArray(Q.content)&&Q.content.every((Z)=>Z.type==="tool_result")){Q.content.push(...W);continue}$.push({role:H,content:W})}return $}function ZY(f){if(typeof f==="string")return f.length>0?[{type:"text",text:f}]:[];return[...f]}function jY(f){switch(f.type){case"text":return{type:"text",text:f.text};case"thinking":return{type:"reasoning",text:f.thinking,metadata:f.signature?{signature:f.signature,details:f.details}:f.details?{details:f.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:f.data}};case"image":return{type:"image",image:f.data,mediaType:f.mediaType};case"file":return{type:"file",path:f.path,content:f.content};case"tool_use":return{type:"tool-call",toolCallId:f.id,toolName:f.name,input:f.input,metadata:f.signature?{signature:f.signature}:void 0};case"tool_result":return o9(f)}}function o9(f){return{type:"tool-result",toolCallId:f.tool_use_id,toolName:"",output:f.content,isError:f.is_error}}function e9(f){switch(f.type){case"text":return{type:"text",text:f.text};case"reasoning":{if(f.redacted===!0)return{type:"redacted_thinking",data:f.metadata?.data??""};let $=f.metadata;return{type:"thinking",thinking:f.text,signature:$?.signature,details:$?.details}}case"image":return typeof f.image==="string"?{type:"image",data:f.image,mediaType:f.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:f.path,content:f.content};case"tool-call":return{type:"tool_use",id:f.toolCallId,name:f.toolName,input:f.input??{},signature:f.metadata?.signature};case"tool-result":{let $=f.output,J=typeof $==="string"?$:Array.isArray($)?$:JSON.stringify($);return{type:"tool_result",tool_use_id:f.toolCallId,content:J,is_error:f.isError}}}}function a9(f){if(!f)return;return{inputTokens:f.inputTokens??0,outputTokens:f.outputTokens??0,cacheReadTokens:f.cacheReadTokens??0,cacheWriteTokens:f.cacheWriteTokens??0,cost:f.cost}}function XY(f){if(!f)return;return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,cost:f.cost}}var t9=0;function AY(){return t9+=1,`msg_${Date.now().toString(36)}_${t9.toString(36)}`}function f3(f){let{agentConfig:$}=f,J=PY($),W=BY($),H=f.hooks,Q=YY($.maxParallelToolCalls);return{sessionId:f.sessionId??$.sessionId,agentId:f.agentId,conversationId:f.conversationId,parentAgentId:f.parentAgentId,agentRole:f.agentRole,systemPrompt:f.systemPrompt??$.systemPrompt,messageModelInfo:W,model:f.model,modelOptions:J,tools:f.tools,hooks:H,prepareTurn:f.prepareTurn,consumePendingUserMessage:$.consumePendingUserMessage,plugins:f.plugins,logger:f.logger??$.logger,telemetry:f.telemetry??VY($.telemetry),initialMessages:f.initialMessages,completionPolicy:$.completionPolicy,maxIterations:$.maxIterations,toolExecution:Q,toolPolicies:$.toolPolicies,toolContextMetadata:f.toolContextMetadata,requestToolApproval:$.requestToolApproval}}function PY(f){let $={};if(f.thinking!==void 0)$.thinking=f.thinking;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;if(f.maxTokensPerTurn!==void 0)$.maxTokensPerTurn=f.maxTokensPerTurn;if(f.apiTimeoutMs!==void 0)$.apiTimeoutMs=f.apiTimeoutMs;return Object.keys($).length>0?$:void 0}function BY(f){let $=f.providerConfig?.family;return{id:f.modelId,provider:f.providerId,family:$}}function YY(f){if(f===void 0)return;return f>=2?"parallel":"sequential"}function VY(f){if(!f)return;return{capture:($,J)=>{f.capture({event:$,properties:J})}}}function RY(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function FY(f){f.lastToolName="",f.lastToolSignature="",f.consecutiveIdenticalCount=0}function o6(f){if(f==null||typeof f!=="object")return f;if(Array.isArray(f))return f.map(o6);let $={};for(let J of Object.keys(f).sort())$[J]=o6(f[J]);return $}function KY(f){if(f==null)return"null";if(typeof f==="string")return f;if(typeof f!=="object")return String(f);try{return JSON.stringify(o6(f))}catch{return String(f)}}function yY(f,$,J,W){if($===f.lastToolName&&J===f.lastToolSignature)f.consecutiveIdenticalCount++;else f.consecutiveIdenticalCount=1;return f.lastToolName=$,f.lastToolSignature=J,{softWarning:f.consecutiveIdenticalCount===W.softThreshold,hardEscalation:f.consecutiveIdenticalCount>=W.hardThreshold}}var $3={softThreshold:3,hardThreshold:5};class e6{config;state=RY();constructor(f){this.config={softThreshold:f?.softThreshold??$3.softThreshold,hardThreshold:f?.hardThreshold??$3.hardThreshold}}inspect(f){let $=KY(f.input),J=yY(this.state,f.name,$,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${f.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){FY(this.state)}}class fJ{consecutiveMistakes=0;options;constructor(f){this.options=f}async record(f){let $=this.options.maxConsecutiveMistakes,J=f.forceAtLimit&&$?$:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let W=f.details?.trim()||`consecutive mistake (${f.reason})`;if(this.options.emit({type:"error",error:Error(W),recoverable:!0,iteration:f.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:f.iteration,reason:f.reason,details:f.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!$||J<$)return{action:"continue"};let H=await GY({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details},this.options.onLimitReached);if(H.action==="continue"){let Q=H.guidance?.trim();if(Q)this.options.appendRecoveryNotice(Q,f.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:Q}}return{action:"stop",reason:H.reason?.trim()||void 0,message:UY({iteration:f.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:$,reason:f.reason,details:f.details,stopReason:H.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function UY(f){let $=[`Stopped after ${f.consecutiveMistakes}/${f.maxConsecutiveMistakes} consecutive mistakes (${f.reason}) at iteration ${f.iteration}.`],J=f.details?.trim();if(J)$.push(`Error: ${J}`);let W=f.stopReason?.trim();if(W)$.push(`Decision: ${W}`);return $.push("Session state was preserved. Send a new prompt to resume from the latest state."),$.join(" ")}async function GY(f,$){if(!$)return{action:"stop",reason:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`};try{return await $(f)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${f.maxConsecutiveMistakes})`}}}function TY(f){let $=f.content.filter((J)=>J.type==="text");if($.length===0)return;return $.map((J)=>J.text).join("")}function DY(f){let $=f.content.filter((J)=>J.type==="reasoning");if($.length===0)return;return{reasoning:$.map((J)=>J.text).join(""),redacted:$.some((J)=>J.redacted===!0)}}function _Y(f){return f.content.find(($)=>$.type==="tool-result")}function MY(f){switch(f){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function LY(f){if(!f||f.isError!==!0)return;if(typeof f.output==="string")return f.output;if(f.output instanceof Error)return f.output.message;try{return JSON.stringify(f.output)}catch{return String(f.output)}}class $J{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate(f){switch(f.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:f.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:f.iteration,hadToolCalls:f.toolCallCount>0,toolCallCount:f.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:f.text,accumulated:f.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:f.text,redacted:f.redacted===!0}];case"assistant-message":return this.translateAssistantMessage(f.message);case"tool-started":return this.translateToolStarted(f);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,update:f.update}];case"tool-finished":return this.translateToolFinished(f);case"usage-updated":return this.translateUsage(f.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:f.message,reason:f.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:f.metadata}];case"run-finished":return this.translateRunFinished(f.result);case"run-failed":return[{type:"error",error:f.error,recoverable:!1,iteration:f.snapshot.iteration}];default:return f}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage(f){let $=[],J=TY(f);if(J!==void 0)$.push({type:"content_end",contentType:"text",text:J});let W=DY(f);if(W!==void 0)$.push({type:"content_end",contentType:"reasoning",reasoning:W.reasoning});return $}translateToolStarted(f){return this.toolStartedAt.set(f.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,input:f.toolCall.input}]}translateToolFinished(f){let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=$===void 0?void 0:Date.now()-$;this.toolStartedAt.delete(f.toolCall.toolCallId);let W=_Y(f.message),H=W?.output,Q=LY(W);return[{type:"content_end",contentType:"tool",toolName:f.toolCall.toolName,toolCallId:f.toolCall.toolCallId,output:H,error:Q,durationMs:J}]}translateUsage(f){let $=f.inputTokens-this.lastUsage.inputTokens,J=f.outputTokens-this.lastUsage.outputTokens,W=f.cacheReadTokens-this.lastUsage.cacheReadTokens,H=f.cacheWriteTokens-this.lastUsage.cacheWriteTokens,Q=this.lastUsage.totalCost??0,j=(f.totalCost??0)-Q;return this.lastUsage={inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheWriteTokens:f.cacheWriteTokens,totalCost:f.totalCost},[{type:"usage",inputTokens:Math.max(0,$),outputTokens:Math.max(0,J),cacheReadTokens:W===0?void 0:Math.max(0,W),cacheWriteTokens:H===0?void 0:Math.max(0,H),cost:j===0?void 0:j,totalInputTokens:f.inputTokens,totalOutputTokens:f.outputTokens,totalCacheReadTokens:f.cacheReadTokens===0?void 0:f.cacheReadTokens,totalCacheWriteTokens:f.cacheWriteTokens===0?void 0:f.cacheWriteTokens,totalCost:f.totalCost}]}translateRunFinished(f){let $={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens===0?void 0:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens===0?void 0:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost};return[{type:"done",reason:MY(f.status),text:f.outputText,iterations:f.iterations,usage:$}]}}function CY(f){if(typeof f==="string")return f;if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}}async function EY(f){let J=(typeof f.content==="function"?await f.content():f.content).trim();return J.length>0?J:void 0}function SY(f,$){let J=f.trim(),W=$.map((H)=>H.trim()).filter(Boolean).join(`
|
|
140
140
|
|
|
141
|
-
`);if(J&&
|
|
141
|
+
`);if(J&&W)return`${J}
|
|
142
142
|
|
|
143
|
-
${H}`;return J||H}function UB(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return{};return{beforeRun:async(J)=>{for(let H of $){let W=await H.beforeRun?.(J);if(W?.stop)return W}return},afterRun:async(J)=>{for(let H of $)await H.afterRun?.(J)},beforeModel:async(J)=>{let H=J.request,W;for(let Q of $){let Z=await Q.beforeModel?.({...J,request:H});if(!Z)continue;if(Z.stop)return Z;W={...W,...Z,options:{...W?.options??{},...Z.options??{}}},H={...H,...Z.messages?{messages:Z.messages}:{},...Z.tools?{tools:Z.tools}:{},...Z.options?{options:{...H.options??{},...Z.options}}:{}}}return W},afterModel:async(J)=>{for(let H of $){let W=await H.afterModel?.(J);if(W?.stop)return W}return},beforeTool:async(J)=>{let H=J.input,W;for(let Q of $){let Z=await Q.beforeTool?.({...J,input:H});if(!Z)continue;if(Z.stop||Z.skip)return Z;if(W={...W,...Z},Object.hasOwn(Z,"input"))H=Z.input}return W},afterTool:async(J)=>{let H=J.result,W;for(let Q of $){let Z=await Q.afterTool?.({...J,result:H});if(!Z)continue;if(Z.stop)return Z;if(W={...W,...Z},Z.result)H=Z.result}return W},onEvent:async(J)=>{for(let H of $)await H.onEvent?.(J)}}}class G0{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 n6;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor(f,$={}){this.config=f,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=f.parentAgentId,this.logger=$.logger??f.logger,this.telemetry=$.telemetry??f.telemetry,this.createAgentRuntimeImpl=$.createAgentRuntimeImpl??AB,this.conversation=new r6(f.initialMessages),this.messageBuilder=new c6,this.contributionRegistry=RB({extensions:f.extensions?[...f.extensions]:[],setupContext:{session:f.extensionContext?.session,client:f.extensionContext?.client,user:f.extensionContext?.user,workspaceInfo:f.extensionContext?.workspace,automation:f.extensionContext?.automation,logger:f.extensionContext?.logger??this.logger,telemetry:f.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=f.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new i6({maxConsecutiveMistakes:J,onLimitReached:f.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,Z,j)=>GB(this.logger,Q,Z,j),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(Q,Z)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q}]})}});let H=f.execution?.loopDetection;this.loopDetectionDisabled=H===!1;let W=H===!1||H===void 0?void 0:H;this.loopTracker=new p6(W)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools(f){if(f.length===0)return;let $=new Set(this.config.tools.map((H)=>H.name)),J=[...this.config.tools];for(let H of f)if(!$.has(H.name))J.push(H),$.add(H.name);this.config={...this.config,tools:J}}updateConnection(f){let $={...this.config};if(f.providerId!==void 0)$.providerId=f.providerId;if(f.modelId!==void 0)$.modelId=f.modelId;if(f.apiKey!==void 0)$.apiKey=f.apiKey;if(f.baseUrl!==void 0)$.baseUrl=f.baseUrl;if(f.headers!==void 0)$.headers=f.headers;if(f.providerConfig!==void 0)$.providerConfig=f.providerConfig;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinking!==void 0)$.thinking=f.thinking;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;this.config=$}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore(f){this.conversation.restore(f),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}abort(f){let $=typeof f==="string"?f:f instanceof Error?f.message:f===void 0?void 0:String(f);if(this.abortRequested=!0,this.abortReason=$,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort($)}async shutdown(f,$){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run(f,$,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!1})}continue(f,$,J){return this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let f=[];for(let $ of this.contributionRegistry.getRegisteredRules()){let J=await yB($);if(J)f.push(J)}return KB(this.config.systemPrompt,f)}executeRun(f){let $;return $=this.executeRunInternal(f).finally(()=>{if(this.activeRunPromise===$)this.activeRunPromise=null}),this.activeRunPromise=$,$}async executeRunInternal(f){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let $=new Date,J=f.userMessage;if(J!==void 0){let F=await TB(J,f.userImages,f.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let H=await this.composeSystemPrompt(),W=g9(this.config,this.logger),Q=this.contributionRegistry.getRegisteredTools(),Z=new Map;for(let F of Q)Z.set(F.name,F);for(let F of this.config.tools)Z.set(F.name,F);let j=this.conversation.getConversationId(),P=s9(this.config),X=Array.from(Z.values()),V=$8(this.conversation.getMessages()),Y=n9({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:j,parentAgentId:this.parentAgentId,model:W,logger:this.logger,tools:X,toolContextMetadata:{modelSupportsImages:P?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(P,X),initialMessages:V,systemPrompt:H}),B=this.createAgentRuntimeImpl(Y);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let A=B.subscribe((F)=>{this.handleRuntimeEvent(F)}),R,U;try{if(f.isContinue)R=await B.continue(void 0);else R=await B.run("")}catch(F){U=F instanceof Error?F:Error(String(F))}finally{A();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(R&&R.messages.length>0){let F=b$(R.messages);this.conversation.replaceMessages(F)}let y=new Date;try{return this.buildLegacyResult({runResult:R,thrownError:U,startedAt:$,endedAt:y})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch(f){if(this.config.hookErrorMode==="throw")throw f;this.emitLegacyEvent({type:"error",error:f instanceof Error?f:Error(String(f)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let f=UB([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map(($)=>$.hooks)]);return{...f,beforeModel:async($)=>{let J=await f.beforeModel?.($);if(J?.stop)return J;let H=J?.messages??$.request.messages,W=await this.prepareMessagesForModelRequest(H);return{...J,messages:W}}}}createRuntimePrepareTurn(f,$){let J=this.config.prepareTurn;if(!J)return;return async(H)=>{let W=b$(H.messages),Q=await this.prepareProviderMessagesForApi(W),Z=await J({agentId:H.agentId,conversationId:H.conversationId??this.conversation.getConversationId(),parentAgentId:H.parentAgentId??null,iteration:H.iteration,messages:W,apiMessages:Q,abortSignal:H.signal??new AbortController().signal,systemPrompt:H.systemPrompt??"",tools:$,model:{id:this.config.modelId,provider:this.config.providerId,info:f},emitStatusNotice:H.emitStatusNotice});if(!Z)return;return{...Z.messages?{messages:$8(Z.messages)}:{},...Z.systemPrompt!==void 0?{systemPrompt:Z.systemPrompt}:{}}}}async prepareMessagesForModelRequest(f){let $=await this.prepareProviderMessagesForApi(l9(f));return $8($)}async prepareProviderMessagesForApi(f){let $=f,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let H of J)$=await H.build($);return this.messageBuilder.buildForApi($)}handleRuntimeEvent(f){switch(f.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage(f.snapshot.messages,[f.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set(f.toolCall.toolCallId,new Date),this.toolInputs.set(f.toolCall.toolCallId,f.toolCall.input),this.inspectLoopForToolCall(f.toolCall.toolName,f.toolCall.input,f.iteration);break}case"tool-finished":{let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=new Date,H=this.toolInputs.get(f.toolCall.toolCallId);this.toolStartedAt.delete(f.toolCall.toolCallId),this.toolInputs.delete(f.toolCall.toolCallId);let W=f.message.content.find((P)=>P.type==="tool-result"),Q=W?.type==="tool-result"&&W.isError===!0,Z=Q?FB(W?.type==="tool-result"?W.output:void 0):void 0,j={id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:H,output:W?.type==="tool-result"?W.output:void 0,error:Z,durationMs:$===void 0?0:J.getTime()-$.getTime(),startedAt:$??J,endedAt:J};if(this.currentRunToolCalls.push(j),Q){if(this.currentTurnFailedTools+=1,Z)this.currentTurnFailureDetails.push(`[${f.toolCall.toolName}] ${Z}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let $=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if($>0&&J===0){let H=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:f.iteration,reason:"tool_execution_failed",details:`${$} tool call(s) failed${H?`: ${H}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost};break}default:break}for(let $ of this.eventAdapter.translate(f))this.emitLegacyEvent($)}syncConversationFromRuntimeMessage(f,$){if(f.length>0){this.conversation.replaceMessages(b$(f));return}if($.length===0)return;let J=new Set(this.conversation.getMessages().map((W)=>W.id).filter((W)=>typeof W==="string")),H=b$($).filter((W)=>!W.id||!J.has(W.id));if(H.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...H])}emitLegacyEvent(f){for(let $ of this.listeners)try{$(f)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall(f,$,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let H=this.loopTracker.inspect({name:f,input:$});if(H.kind==="ok")return;if(H.kind==="soft"){if(H.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:H.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:H.message??`Detected repeated tool calls to \`${f}\`; stopping to avoid a loop.`})}enqueueMistakeRecord(f){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let $=await this.mistakeTracker.record(f);if($.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:$.message}]}),this.activeRuntime?.abort($.reason??$.message)})}buildLegacyResult(f){let{runResult:$,thrownError:J,startedAt:H,endedAt:W}=f,Q=W.getTime()-H.getTime(),Z=J?"error":hB($),j=$?.outputText||($?.status==="failed"?$.error?.message:void 0)||"",P=$?{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost}:this.currentRunUsage,X=$?b$($.messages):this.conversation.getMessages(),V=s9(this.config);if(J)throw J;return{text:j,usage:P,messages:X,toolCalls:this.currentRunToolCalls,iterations:$?.iterations??0,finishReason:Z,model:{id:this.config.modelId,provider:this.config.providerId,info:V},startedAt:H,endedAt:W,durationMs:Q}}}function GB(f,$,J,H){if(!f)return;if($==="debug"){f.debug(J,H);return}if($==="error"&&f.error){f.error(J,H);return}let W=$==="warn"?"warn":$==="error"?"error":"info";f.log(J,{...H,severity:W})}function hB(f){if(!f)return"error";switch(f.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function TB(f,$,J,H){let{buildInitialUserContent:W}=await Promise.resolve().then(() => t9);return W(f,$,J,H)}function s9(f){if(f.knownModels?.[f.modelId])return f.knownModels[f.modelId];let $=v6(f);if($?.[f.modelId])return $[f.modelId];return}import{buildClineSystemPrompt as o9}from"@cline/shared";function e9(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return o9({ide:$.clineIdeName?.trim()||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,rules:`# Team Teammate Role
|
|
144
|
-
${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function f3(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return o9({ide:$.clineIdeName||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,overridePrompt:J,metadata:$.workspaceMetadata,platform:$.clinePlatform})}function J8(f){let $={...f};return{getRuntimeConfig:()=>$,getConnectionConfig:()=>({providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking}),updateConnectionDefaults:(J)=>{$={...$,...J}}}}function B1(f){let $=f.configProvider.getRuntimeConfig(),J=f.kind==="teammate"?e9(f.prompt,$):f3(f.prompt,$);return{...f.configProvider.getConnectionConfig(),systemPrompt:J,tools:f.tools,maxIterations:f.maxIterations??$.maxIterations,parentAgentId:f.parentAgentId,abortSignal:f.abortSignal,onEvent:f.onEvent,hooks:$.hooks,extensions:$.extensions,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval,logger:$.logger,role:f.role}}function H8(f){let $=B1(f),J=new G0($);if($.onEvent)J.subscribeEvents($.onEvent);return J}var _B=a6.object({systemPrompt:a6.string().describe("System prompt defining the sub-agent's behavior"),task:a6.string().describe("Task for the sub-agent to complete")});function w$(f){return DB({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:MB(_B),execute:async($,J)=>{let H=f.createSubAgentTools?await f.createSubAgentTools($,J):f.subAgentTools??[],W=H8({kind:"subagent",prompt:$.systemPrompt,configProvider:f.configProvider,tools:H,maxIterations:f.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:f.onSubAgentEvent,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval}),Q=W.getAgentId(),Z=W.getConversationId(),j=J.agentId;if(f.onSubAgentStart)try{await f.onSubAgentStart({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$})}catch{}try{let P=await W.run($.task),X={text:P.text,iterations:P.iterations,finishReason:P.finishReason,usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens}};if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$,result:X})}catch{}return X}catch(P){if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$,error:P instanceof Error?P:Error(String(P))})}catch{}throw P}},timeoutMs:300000,retryable:!1})}import{createTool as e,TEAM_AWAIT_TIMEOUT_MS as LB,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as zB,TEAM_RUN_TEXT_PREVIEW_LIMIT as OB,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as NB,TeamAttachOutcomeFragmentInputSchema as $3,TeamAwaitRunsInputSchema as J3,TeamBroadcastInputSchema as H3,TeamBroadcastToolResultSchema as qB,TeamCancelRunInputSchema as W3,TeamCancelRunToolResultSchema as bB,TeamCleanupInputSchema as Q3,TeamCleanupToolResultSchema as wB,TeamCreateOutcomeInputSchema as Z3,TeamCreateOutcomeToolResultSchema as CB,TeamFinalizeOutcomeInputSchema as j3,TeamFinalizeOutcomeToolResultSchema as EB,TeamListOutcomesInputSchema as P3,TeamListRunsInputSchema as X3,TeamMailboxMessageToolResultSchema as SB,TeamMissionLogInputSchema as V3,TeamMissionLogToolResultSchema as kB,TeamOutcomeFragmentToolResultSchema as Y3,TeamOutcomeToolResultSchema as mB,TeamReadMailboxInputSchema as B3,TeamReviewOutcomeFragmentInputSchema as A3,TeamRunTaskInputSchema as R3,TeamRunTaskToolResultSchema as t6,TeamRunToolSummarySchema as s6,TeamSendMessageInputSchema as F3,TeamSendMessageToolResultSchema as IB,TeamShutdownTeammateInputSchema as y3,TeamSimpleAgentStatusToolResultSchema as K3,TeamSpawnTeammateInputSchema as U3,TeamStatusInputSchema as G3,TeamStatusToolResultSchema as xB,TeamTaskInputSchema as h3,TeamTaskToolResultSchema as A1,validateWithZod as O,zodToJsonSchema as ff}from"@cline/shared";function T3(f,$){let J=f.replace(/\s+/g," ").trim();if(J.length<=$)return J;return`${J.slice(0,Math.max(0,$-3)).trimEnd()}...`}function a0(f,$){if(f===void 0)throw Error(`Missing required field: ${$}`);return f}function gB(f){let $=f.result;if(!$)return;return{textPreview:T3($.text,OB),iterations:$.iterations,finishReason:$.finishReason,durationMs:$.durationMs,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost}}}function W8(f){return f?.toISOString()}function o6(f){return{id:f.id,agentId:f.agentId,taskId:f.taskId,status:f.status,messagePreview:T3(f.message,zB),priority:f.priority,retryCount:f.retryCount,maxRetries:f.maxRetries,nextAttemptAt:W8(f.nextAttemptAt),continueConversation:f.continueConversation,startedAt:f.startedAt.toISOString(),endedAt:W8(f.endedAt),leaseOwner:f.leaseOwner,heartbeatAt:W8(f.heartbeatAt),lastProgressAt:W8(f.lastProgressAt),lastProgressMessage:f.lastProgressMessage,currentActivity:f.currentActivity,error:f.error,resultSummary:gB(f)}}function vB(f){if(f.status==="failed")throw Error(`Run "${f.id}" failed${f.error?`: ${f.error}`:""}`);if(f.status==="cancelled")throw Error(`Run "${f.id}" was cancelled${f.error?`: ${f.error}`:""}`);if(f.status==="interrupted")throw Error(`Run "${f.id}" was interrupted${f.error?`: ${f.error}`:""}`)}var Q8=["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 D3(f){let $=[];if(f.createBaseTools)$.push(...f.createBaseTools());$.push(...R1({runtime:f.runtime,requesterId:f.spec.agentId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!1})),f.runtime.spawnTeammate({agentId:f.spec.agentId,config:B1({kind:"teammate",prompt:f.spec.rolePrompt,role:f.spec.rolePrompt,configProvider:f.teammateConfigProvider,tools:$,maxIterations:f.spec.maxIterations,cwd:f.teammateConfigProvider.getRuntimeConfig().cwd})})}function Z8(f){let $=f.leadAgentId??"lead",J=f.restoredFromPersistence===!0,H=R1({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!0,includeSpawnTool:f.includeLeadSpawnTool,includeManagementTools:f.includeLeadManagementTools,onLeadToolsUnlocked:f.onLeadToolsUnlocked}),W=[];for(let Q of f.restoredTeammates??[]){if(f.runtime.isTeammateActive(Q.agentId))continue;D3({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:Q}),W.push(Q.agentId)}return{tools:H,restoredFromPersistence:J,restoredTeammates:W}}function R1(f){let $=f.allowSpawn??!0,J=f.includeSpawnTool??!0,H=f.includeManagementTools??!0,W=[];if(J)W.push(e({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:ff(U3),execute:async(Z)=>{let j=O(U3,Z);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!$)throw Error("Spawning teammates is disabled in this context.");let P={agentId:j.agentId,rolePrompt:j.rolePrompt};if(D3({runtime:f.runtime,requesterId:f.requesterId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:P}),!H)f.onLeadToolsUnlocked?.(R1({...f,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return O(K3,{agentId:j.agentId,status:"spawned"})}}));if(!H)return W;W.push(e({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:ff(y3),execute:async(Z)=>{let j=O(y3,Z);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return f.runtime.shutdownTeammate(j.agentId,j.reason),O(K3,{agentId:j.agentId,status:"stopped"})}})),W.push(e({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:ff(G3),execute:async(Z)=>{return O(G3,Z),O(xB,f.runtime.getSnapshot())}})),W.push(e({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:ff(h3),execute:async(Z)=>{let j=O(h3,Z);switch(j.action){case"create":{let P=new Set(NB.create??[]),X=Object.entries(Z).filter(([Y,B])=>P.has(Y)&&B!=null).map(([Y])=>Y),V=f.runtime.createTask({title:a0(j.title,"title"),description:a0(j.description,"description"),dependsOn:j.dependsOn,assignee:j.assignee,createdBy:f.requesterId});return O(A1,{action:"create",taskId:V.id,status:V.status,...X.length>0?{ignoredFields:X,note:`Ignored fields for action=create: ${X.join(", ")}`}:{}})}case"list":return O(A1,{action:"list",tasks:f.runtime.listTaskItems({status:j.status,assignee:j.assignee})});case"claim":{let P=f.runtime.claimTask(a0(j.taskId,"taskId"),f.requesterId);return O(A1,{action:"claim",taskId:P.id,status:P.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let P=f.runtime.completeTask(a0(j.taskId,"taskId"),f.requesterId,a0(j.summary,"summary"));return O(A1,{action:"complete",taskId:P.id,status:P.status})}case"block":{let P=f.runtime.blockTask(a0(j.taskId,"taskId"),f.requesterId,a0(j.reason,"reason"));return O(A1,{action:"block",taskId:P.id,status:P.status})}}}}));let Q=new Map;return W.push(e({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:ff(R3),execute:async(Z)=>{let j=O(R3,Z);if(j.runMode==="async"){let V=f.runtime.startTeammateRun(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:f.requesterId,continueConversation:j.continueConversation||void 0});return O(t6,{agentId:j.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${j.agentId} and queued as ${V.id}.`,runId:V.id})}let P=Q.get(j.agentId);if(P){let V=await P;return O(t6,{...V,status:"joined",deduped:!0,message:`Task for ${j.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let X=f.runtime.routeToTeammate(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:f.requesterId,continueConversation:j.continueConversation||void 0}).then((V)=>O(t6,{agentId:j.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${j.agentId} and completed in sync mode.`,text:V.text,iterations:V.iterations})).finally(()=>{Q.delete(j.agentId)});return Q.set(j.agentId,X),await X}})),W.push(e({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:ff(W3),execute:async(Z)=>{let j=O(W3,Z),P=f.runtime.cancelRun(j.runId,j.reason);return O(bB,{runId:P.id,status:P.status})}})),W.push(e({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:ff(X3),execute:async(Z)=>O(s6.array(),f.runtime.listRuns(O(X3,Z)).map(o6))})),W.push(e({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:ff(J3),timeoutMs:LB,execute:async(Z)=>{let j=O(J3,Z);if(j.runId){let V=await f.runtime.awaitRun(j.runId);return vB(V),O(s6,o6(V))}let P=await f.runtime.awaitAllRuns(),X=P.filter((V)=>["failed","cancelled","interrupted"].includes(V.status));if(X.length>0){let V=X.map((Y)=>`${Y.id}:${Y.status}${Y.error?`(${Y.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${V}`)}return O(s6.array(),P.map(o6))}})),W.push(e({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:ff(F3),execute:async(Z)=>{let j=O(F3,Z),P=f.runtime.sendMessage(f.requesterId,j.toAgentId,j.subject,j.body,j.taskId??void 0);return O(IB,{id:P.id,toAgentId:P.toAgentId})}})),W.push(e({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:ff(H3),execute:async(Z)=>{let j=O(H3,Z),P=f.runtime.broadcast(f.requesterId,j.subject,j.body,{taskId:j.taskId??void 0});return O(qB,{delivered:P.length})}})),W.push(e({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:ff(B3),execute:async(Z)=>{let j=O(B3,Z);return O(SB.array(),f.runtime.listMailbox(f.requesterId,{unreadOnly:j.unreadOnly,markRead:!0}))}})),W.push(e({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:ff(V3),execute:async(Z)=>{let j=O(V3,Z),P=f.runtime.appendMissionLog({agentId:f.requesterId,taskId:j.taskId||void 0,kind:j.kind,summary:j.summary,evidence:j.evidence?.length?j.evidence:void 0,nextAction:j.nextAction||void 0});return O(kB,{id:P.id})}})),W.push(e({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:ff(Q3),execute:async(Z)=>{if(O(Q3,Z),f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return f.runtime.cleanup(),O(wB,{status:"cleaned"})}})),W.push(e({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:ff(Z3),execute:async(Z)=>{let j=O(Z3,Z),P=f.runtime.createOutcome({title:j.title,requiredSections:j.requiredSections,createdBy:f.requesterId});return O(CB,{outcomeId:P.id,status:P.status,requiredSections:P.requiredSections})}})),W.push(e({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:ff($3),execute:async(Z)=>{let j=O($3,Z),P=f.runtime.attachOutcomeFragment({outcomeId:j.outcomeId,section:j.section,sourceAgentId:f.requesterId,sourceRunId:j.sourceRunId||void 0,content:j.content});return O(Y3,{fragmentId:P.id,status:P.status})}})),W.push(e({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:ff(A3),execute:async(Z)=>{let j=O(A3,Z),P=f.runtime.reviewOutcomeFragment({fragmentId:j.fragmentId,reviewedBy:f.requesterId,approved:j.approved});return O(Y3,{fragmentId:P.id,status:P.status})}})),W.push(e({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:ff(j3),execute:async(Z)=>{let j=O(j3,Z),P=f.runtime.finalizeOutcome(j.outcomeId);return O(EB,{outcomeId:P.id,status:P.status})}})),W.push(e({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:ff(P3),execute:async(Z)=>{return O(P3,Z),O(mB.array(),f.runtime.listOutcomes())}})),W}function M3(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}function _3(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var uB=[{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:w$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...Q8]}],cB={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function dB(f){return f==="plan"||f==="yolo"?f:"act"}function z3(f){let $=dB(f.mode),J=uf[U0({mode:$})],H=V1(f.providerId??"",f.modelId??"",$,X1);return{mode:$,flags:{...J,...H,...typeof f.enableSpawnAgent==="boolean"?{enableSpawnAgent:f.enableSpawnAgent}:{},...typeof f.enableAgentTeams==="boolean"?{enableAgentTeams:f.enableAgentTeams}:{}}}}function L3(f,$){if($.disabledToolIds?.has(f))return!1;let{flags:J}=z3($);if(f==="spawn_agent")return J.enableSpawnAgent===!0;if(f==="teams")return J.enableAgentTeams===!0;if(f==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let H=cB[f];return H?J[H]===!0:!1}function rB(f,$){if(f.id==="editor"){let{flags:J}=z3($),H=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...f,defaultEnabled:L3(f.id,$),headlessToolNames:[H?"apply_patch":"editor"]}}return{...f,defaultEnabled:L3(f.id,$)}}function F1(f={}){return uB.map(($)=>rB($,f))}function O3(f={}){return F1(f).filter(($)=>$.defaultEnabled).map(($)=>$.id)}function N3(f){if(!f.enabled)return new Set;let $=F1(f.availabilityContext),J=new Set($.map((H)=>H.id));if(!f.allowlist||f.allowlist.length===0)return new Set($.filter((H)=>H.defaultEnabled).map((H)=>H.id));for(let H of f.allowlist)if(!J.has(H))throw Error(`Unknown tool "${H}". Available tools: ${$.map((W)=>W.id).join(", ")}`);return new Set(f.allowlist)}function e6(f,$={}){return F1($).filter((J)=>f.has(J.id)).flatMap((J)=>J.headlessToolNames)}function q3(f,$={}){return e6(f,$)}function y1(f={}){let{executorOptions:$={},executors:J,...H}=f,W={...f8($),...J??{}};return N$({...H,executors:W})}function j8(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function lB(f){if(!f||f.length===0)return;let $=f.map(j8).filter((J)=>J.length>0);return $.length>0?new Set($):void 0}function pB(f,$,J){if(!J)return!0;let H=j8(f),W=j8($),Q=H.includes(":")?H.split(":").at(-1)??H:H,Z=W.includes(":")?W.split(":").at(-1)??W:W;return J.has(H)||J.has(W)||J.has(Q)||J.has(Z)}function K1(f,$){let J=lB($);return[...f.getSnapshot("skill").entries()].map(([W,Q])=>{let Z=Q.item;return{id:W,name:Z.name.trim(),description:Z.description?.trim(),disabled:Z.disabled===!0,skill:Z}}).filter((W)=>pB(W.id,W.name,J))}function iB(f,$){return K1(f,$).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,H)=>J.localeCompare(H))}function nB(f,$,J){let H=j8($);if(!H)return{error:"Missing skill name."};let W=K1(f,J),Q=W.find((V)=>V.id===H);if(Q){let{skill:V}=Q;if(V.disabled===!0)return{error:`Skill "${V.name}" is configured but disabled.`};return{id:Q.id,skill:V}}let Z=H.includes(":")?H.split(":").at(-1)??H:H,j=W.filter(({id:V})=>{if(V===Z)return!0;return V.endsWith(`:${Z}`)}),P=j.filter(({skill:V})=>V.disabled!==!0);if(P.length===1){let{id:V,skill:Y}=P[0];return{id:V,skill:Y}}if(P.length>1)return{error:`Skill "${$}" is ambiguous. Use one of: ${P.map(({id:V})=>V).join(", ")}`};if(j.length===1){let{skill:V}=j[0];return{error:`Skill "${V.name}" is configured but disabled.`}}if(j.length>1)return{error:`Skill "${$}" is ambiguous, and all matches are disabled: ${j.map(({id:V})=>V).join(", ")}`};let X=iB(f,J);return{error:X.length>0?`Skill "${$}" not found. Available skills: ${X.join(", ")}`:"No skills are currently available."}}function aB(f,$=Promise.resolve(),J){let H=new Set,W=async(Q,Z)=>{await $;let j=nB(f,Q,J);if("error"in j)return j.error;let{id:P,skill:X}=j;if(H.has(P))return`Skill "${X.name}" is already running.`;H.add(P);try{let V=Z?.trim(),Y=V?`
|
|
145
|
-
<command-args>${
|
|
143
|
+
${W}`;return J||W}function kY(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return{};return{beforeRun:async(J)=>{for(let W of $){let H=await W.beforeRun?.(J);if(H?.stop)return H}return},afterRun:async(J)=>{for(let W of $)await W.afterRun?.(J)},beforeModel:async(J)=>{let W=J.request,H;for(let Q of $){let Z=await Q.beforeModel?.({...J,request:W});if(!Z)continue;if(Z.stop)return Z;H={...H,...Z,options:{...H?.options??{},...Z.options??{}}},W={...W,...Z.messages?{messages:Z.messages}:{},...Z.tools?{tools:Z.tools}:{},...Z.options?{options:{...W.options??{},...Z.options}}:{}}}return H},afterModel:async(J)=>{for(let W of $){let H=await W.afterModel?.(J);if(H?.stop)return H}return},beforeTool:async(J)=>{let W=J.input,H;for(let Q of $){let Z=await Q.beforeTool?.({...J,input:W});if(!Z)continue;if(Z.stop||Z.skip)return Z;if(H={...H,...Z},Object.hasOwn(Z,"input"))W=Z.input}return H},afterTool:async(J)=>{let W=J.result,H;for(let Q of $){let Z=await Q.afterTool?.({...J,result:W});if(!Z)continue;if(Z.stop)return Z;if(H={...H,...Z},Z.result)W=Z.result}return H},onEvent:async(J)=>{for(let W of $)await W.onEvent?.(J)}}}class L0{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 $J;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor(f,$={}){this.config=f,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=f.parentAgentId,this.logger=$.logger??f.logger,this.telemetry=$.telemetry??f.telemetry,this.createAgentRuntimeImpl=$.createAgentRuntimeImpl??wY,this.conversation=new s6(f.initialMessages),this.messageBuilder=new a6,this.contributionRegistry=bY({extensions:f.extensions?[...f.extensions]:[],setupContext:{session:f.extensionContext?.session,client:f.extensionContext?.client,user:f.extensionContext?.user,workspaceInfo:f.extensionContext?.workspace,automation:f.extensionContext?.automation,logger:f.extensionContext?.logger??this.logger,telemetry:f.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=f.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new fJ({maxConsecutiveMistakes:J,onLimitReached:f.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,Z,j)=>IY(this.logger,Q,Z,j),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(Q,Z)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q}]})}});let W=f.execution?.loopDetection;this.loopDetectionDisabled=W===!1;let H=W===!1||W===void 0?void 0:W;this.loopTracker=new e6(H)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools(f){if(f.length===0)return;let $=new Set(this.config.tools.map((W)=>W.name)),J=[...this.config.tools];for(let W of f)if(!$.has(W.name))J.push(W),$.add(W.name);this.config={...this.config,tools:J}}updateConnection(f){let $={...this.config};if(f.providerId!==void 0)$.providerId=f.providerId;if(f.modelId!==void 0)$.modelId=f.modelId;if(f.apiKey!==void 0)$.apiKey=f.apiKey;if(f.baseUrl!==void 0)$.baseUrl=f.baseUrl;if(f.headers!==void 0)$.headers=f.headers;if(f.providerConfig!==void 0)$.providerConfig=f.providerConfig;if(f.reasoningEffort!==void 0)$.reasoningEffort=f.reasoningEffort;if(f.thinking!==void 0)$.thinking=f.thinking;if(f.thinkingBudgetTokens!==void 0)$.thinkingBudgetTokens=f.thinkingBudgetTokens;this.config=$}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore(f){this.conversation.restore(f),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}abort(f){let $=typeof f==="string"?f:f instanceof Error?f.message:f===void 0?void 0:String(f);if(this.abortRequested=!0,this.abortReason=$,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort($)}async shutdown(f,$){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run(f,$,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!1})}continue(f,$,J){return this.executeRun({userMessage:f,userImages:$,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let f=[];for(let $ of this.contributionRegistry.getRegisteredRules()){let J=await EY($);if(J)f.push(J)}return SY(this.config.systemPrompt,f)}executeRun(f){let $;return $=this.executeRunInternal(f).finally(()=>{if(this.activeRunPromise===$)this.activeRunPromise=null}),this.activeRunPromise=$,$}async executeRunInternal(f){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let $=new Date,J=f.userMessage;if(J!==void 0){let F=await xY(J,f.userImages,f.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let W=await this.composeSystemPrompt(),H=l9(this.config,this.logger),Q=this.contributionRegistry.getRegisteredTools(),Z=new Map;for(let F of Q)Z.set(F.name,F);for(let F of this.config.tools)Z.set(F.name,F);let j=this.conversation.getConversationId(),X=W3(this.config),A=Array.from(Z.values()),P=Q8(this.conversation.getMessages()),B=f3({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:j,parentAgentId:this.parentAgentId,model:H,logger:this.logger,tools:A,toolContextMetadata:{modelSupportsImages:X?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(X,A),initialMessages:P,systemPrompt:W}),Y=this.createAgentRuntimeImpl(B);if(this.activeRuntime=Y,this.abortRequested)Y.abort(this.abortReason);let V=Y.subscribe((F)=>{this.handleRuntimeEvent(F)}),R,U;try{if(f.isContinue)R=await Y.continue(void 0);else R=await Y.run("")}catch(F){U=F instanceof Error?F:Error(String(F))}finally{V();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(R&&R.messages.length>0){let F=k$(R.messages);this.conversation.replaceMessages(F)}let K=new Date;try{return this.buildLegacyResult({runResult:R,thrownError:U,startedAt:$,endedAt:K})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch(f){if(this.config.hookErrorMode==="throw")throw f;this.emitLegacyEvent({type:"error",error:f instanceof Error?f:Error(String(f)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let f=kY([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map(($)=>$.hooks)]);return{...f,beforeModel:async($)=>{let J=await f.beforeModel?.($);if(J?.stop)return J;let W=J?.messages??$.request.messages,H=await this.prepareMessagesForModelRequest(W);return{...J,messages:H}}}}createRuntimePrepareTurn(f,$){let J=this.config.prepareTurn;if(!J)return;return async(W)=>{let H=k$(W.messages),Q=await this.prepareProviderMessagesForApi(H),Z=await J({agentId:W.agentId,conversationId:W.conversationId??this.conversation.getConversationId(),parentAgentId:W.parentAgentId??null,iteration:W.iteration,messages:H,apiMessages:Q,abortSignal:W.signal??new AbortController().signal,systemPrompt:W.systemPrompt??"",tools:$,model:{id:this.config.modelId,provider:this.config.providerId,info:f},emitStatusNotice:W.emitStatusNotice});if(!Z)return;return{...Z.messages?{messages:Q8(Z.messages)}:{},...Z.systemPrompt!==void 0?{systemPrompt:Z.systemPrompt}:{}}}}async prepareMessagesForModelRequest(f){let $=await this.prepareProviderMessagesForApi(s9(f));return Q8($)}async prepareProviderMessagesForApi(f){let $=f,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let W of J)$=await W.build($);return this.messageBuilder.buildForApi($)}handleRuntimeEvent(f){switch(f.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage(f.snapshot.messages,[f.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set(f.toolCall.toolCallId,new Date),this.toolInputs.set(f.toolCall.toolCallId,f.toolCall.input),this.inspectLoopForToolCall(f.toolCall.toolName,f.toolCall.input,f.iteration);break}case"tool-finished":{let $=this.toolStartedAt.get(f.toolCall.toolCallId),J=new Date,W=this.toolInputs.get(f.toolCall.toolCallId);this.toolStartedAt.delete(f.toolCall.toolCallId),this.toolInputs.delete(f.toolCall.toolCallId);let H=f.message.content.find((X)=>X.type==="tool-result"),Q=H?.type==="tool-result"&&H.isError===!0,Z=Q?CY(H?.type==="tool-result"?H.output:void 0):void 0,j={id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:W,output:H?.type==="tool-result"?H.output:void 0,error:Z,durationMs:$===void 0?0:J.getTime()-$.getTime(),startedAt:$??J,endedAt:J};if(this.currentRunToolCalls.push(j),Q){if(this.currentTurnFailedTools+=1,Z)this.currentTurnFailureDetails.push(`[${f.toolCall.toolName}] ${Z}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let $=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if($>0&&J===0){let W=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:f.iteration,reason:"tool_execution_failed",details:`${$} tool call(s) failed${W?`: ${W}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost};break}default:break}for(let $ of this.eventAdapter.translate(f))this.emitLegacyEvent($)}syncConversationFromRuntimeMessage(f,$){if(f.length>0){this.conversation.replaceMessages(k$(f));return}if($.length===0)return;let J=new Set(this.conversation.getMessages().map((H)=>H.id).filter((H)=>typeof H==="string")),W=k$($).filter((H)=>!H.id||!J.has(H.id));if(W.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...W])}emitLegacyEvent(f){for(let $ of this.listeners)try{$(f)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall(f,$,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let W=this.loopTracker.inspect({name:f,input:$});if(W.kind==="ok")return;if(W.kind==="soft"){if(W.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:W.message??`Detected repeated tool calls to \`${f}\`; stopping to avoid a loop.`})}enqueueMistakeRecord(f){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let $=await this.mistakeTracker.record(f);if($.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:$.message}]}),this.activeRuntime?.abort($.reason??$.message)})}buildLegacyResult(f){let{runResult:$,thrownError:J,startedAt:W,endedAt:H}=f,Q=H.getTime()-W.getTime(),Z=J?"error":mY($),j=$?.outputText||($?.status==="failed"?$.error?.message:void 0)||"",X=$?{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost}:this.currentRunUsage,A=$?k$($.messages):this.conversation.getMessages(),P=W3(this.config);if(J)throw J;return{text:j,usage:X,messages:A,toolCalls:this.currentRunToolCalls,iterations:$?.iterations??0,finishReason:Z,model:{id:this.config.modelId,provider:this.config.providerId,info:P},startedAt:W,endedAt:H,durationMs:Q}}}function IY(f,$,J,W){if(!f)return;if($==="debug"){f.debug(J,W);return}if($==="error"&&f.error){f.error(J,W);return}let H=$==="warn"?"warn":$==="error"?"error":"info";f.log(J,{...W,severity:H})}function mY(f){if(!f)return"error";switch(f.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function xY(f,$,J,W){let{buildInitialUserContent:H}=await Promise.resolve().then(() => J3);return H(f,$,J,W)}function W3(f){if(f.knownModels?.[f.modelId])return f.knownModels[f.modelId];let $=i6(f);if($?.[f.modelId])return $[f.modelId];return}import{buildClineSystemPrompt as H3}from"@cline/shared";function Q3(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return H3({ide:$.clineIdeName?.trim()||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,rules:`# Team Teammate Role
|
|
144
|
+
${J}`,platform:$.clinePlatform,metadata:$.workspaceMetadata})}function Z3(f,$){let J=f.trim();if($.providerId.toLowerCase()!=="cline")return J;return H3({ide:$.clineIdeName||"Terminal",workspaceRoot:$.cwd?.trim()||"/",providerId:$.providerId,overridePrompt:J,metadata:$.workspaceMetadata,platform:$.clinePlatform})}function Z8(f){let $={...f};return{getRuntimeConfig:()=>$,getConnectionConfig:()=>({providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking}),updateConnectionDefaults:(J)=>{$={...$,...J}}}}function y1(f){let $=f.configProvider.getRuntimeConfig(),J=f.kind==="teammate"?Q3(f.prompt,$):Z3(f.prompt,$);return{...f.configProvider.getConnectionConfig(),systemPrompt:J,tools:f.tools,maxIterations:f.maxIterations??$.maxIterations,parentAgentId:f.parentAgentId,abortSignal:f.abortSignal,onEvent:f.onEvent,hooks:$.hooks,extensions:$.extensions,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval,logger:$.logger,role:f.role}}function j8(f){let $=y1(f),J=new L0($);if($.onEvent)J.subscribeEvents($.onEvent);return J}var uY=JJ.object({systemPrompt:JJ.string().describe("System prompt defining the sub-agent's behavior"),task:JJ.string().describe("Task for the sub-agent to complete")});function I$(f){return gY({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:vY(uY),execute:async($,J)=>{let W=f.createSubAgentTools?await f.createSubAgentTools($,J):f.subAgentTools??[],H=j8({kind:"subagent",prompt:$.systemPrompt,configProvider:f.configProvider,tools:W,maxIterations:f.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:f.onSubAgentEvent,hookErrorMode:f.hookErrorMode,toolPolicies:f.toolPolicies,requestToolApproval:f.requestToolApproval}),Q=H.getAgentId(),Z=H.getConversationId(),j=J.agentId;if(f.onSubAgentStart)try{await f.onSubAgentStart({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$})}catch{}try{let X=await H.run($.task),A={text:X.text,iterations:X.iterations,finishReason:X.finishReason,usage:{inputTokens:X.usage.inputTokens,outputTokens:X.usage.outputTokens}};if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$,result:A,agentResult:X})}catch{}return A}catch(X){if(f.onSubAgentEnd)try{await f.onSubAgentEnd({subAgentId:Q,conversationId:Z,parentAgentId:j,input:$,error:X instanceof Error?X:Error(String(X))})}catch{}throw X}},timeoutMs:300000,retryable:!1})}import{createTool as Jf,TEAM_AWAIT_TIMEOUT_MS as cY,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as dY,TEAM_RUN_TEXT_PREVIEW_LIMIT as rY,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as lY,TeamAttachOutcomeFragmentInputSchema as j3,TeamAwaitRunsInputSchema as X3,TeamBroadcastInputSchema as A3,TeamBroadcastToolResultSchema as pY,TeamCancelRunInputSchema as P3,TeamCancelRunToolResultSchema as iY,TeamCleanupInputSchema as B3,TeamCleanupToolResultSchema as nY,TeamCreateOutcomeInputSchema as Y3,TeamCreateOutcomeToolResultSchema as aY,TeamFinalizeOutcomeInputSchema as V3,TeamFinalizeOutcomeToolResultSchema as tY,TeamListOutcomesInputSchema as R3,TeamListRunsInputSchema as F3,TeamMailboxMessageToolResultSchema as sY,TeamMissionLogInputSchema as K3,TeamMissionLogToolResultSchema as oY,TeamOutcomeFragmentToolResultSchema as y3,TeamOutcomeToolResultSchema as eY,TeamReadMailboxInputSchema as U3,TeamReviewOutcomeFragmentInputSchema as G3,TeamRunTaskInputSchema as T3,TeamRunTaskToolResultSchema as WJ,TeamRunToolSummarySchema as HJ,TeamSendMessageInputSchema as D3,TeamSendMessageToolResultSchema as fV,TeamShutdownTeammateInputSchema as _3,TeamSimpleAgentStatusToolResultSchema as M3,TeamSpawnTeammateInputSchema as L3,TeamStatusInputSchema as h3,TeamStatusToolResultSchema as $V,TeamTaskInputSchema as O3,TeamTaskToolResultSchema as U1,validateWithZod as N,zodToJsonSchema as Wf}from"@cline/shared";function z3(f,$){let J=f.replace(/\s+/g," ").trim();if(J.length<=$)return J;return`${J.slice(0,Math.max(0,$-3)).trimEnd()}...`}function f$(f,$){if(f===void 0)throw Error(`Missing required field: ${$}`);return f}function JV(f){let $=f.result;if(!$)return;return{textPreview:z3($.text,rY),iterations:$.iterations,finishReason:$.finishReason,durationMs:$.durationMs,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost}}}function X8(f){return f?.toISOString()}function QJ(f){return{id:f.id,agentId:f.agentId,taskId:f.taskId,status:f.status,messagePreview:z3(f.message,dY),priority:f.priority,retryCount:f.retryCount,maxRetries:f.maxRetries,nextAttemptAt:X8(f.nextAttemptAt),continueConversation:f.continueConversation,startedAt:f.startedAt.toISOString(),endedAt:X8(f.endedAt),leaseOwner:f.leaseOwner,heartbeatAt:X8(f.heartbeatAt),lastProgressAt:X8(f.lastProgressAt),lastProgressMessage:f.lastProgressMessage,currentActivity:f.currentActivity,error:f.error,resultSummary:JV(f)}}function WV(f){if(f.status==="failed")throw Error(`Run "${f.id}" failed${f.error?`: ${f.error}`:""}`);if(f.status==="cancelled")throw Error(`Run "${f.id}" was cancelled${f.error?`: ${f.error}`:""}`);if(f.status==="interrupted")throw Error(`Run "${f.id}" was interrupted${f.error?`: ${f.error}`:""}`)}var A8=["team_spawn_teammate","team_shutdown_teammate","team_status","team_task","team_run_task","team_cancel_run","team_list_runs","team_await_runs","team_send_message","team_broadcast","team_read_mailbox","team_mission_log","team_cleanup","team_create_outcome","team_attach_outcome_fragment","team_review_outcome_fragment","team_finalize_outcome","team_list_outcomes"];function N3(f){let $=[];if(f.createBaseTools)$.push(...f.createBaseTools());$.push(...G1({runtime:f.runtime,requesterId:f.spec.agentId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!1})),f.runtime.spawnTeammate({agentId:f.spec.agentId,config:y1({kind:"teammate",prompt:f.spec.rolePrompt,role:f.spec.rolePrompt,configProvider:f.teammateConfigProvider,tools:$,maxIterations:f.spec.maxIterations,cwd:f.teammateConfigProvider.getRuntimeConfig().cwd})})}function P8(f){let $=f.leadAgentId??"lead",J=f.restoredFromPersistence===!0,W=G1({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,allowSpawn:!0,includeSpawnTool:f.includeLeadSpawnTool,includeManagementTools:f.includeLeadManagementTools,onLeadToolsUnlocked:f.onLeadToolsUnlocked}),H=[];for(let Q of f.restoredTeammates??[]){if(f.runtime.isTeammateActive(Q.agentId))continue;N3({runtime:f.runtime,requesterId:$,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:Q}),H.push(Q.agentId)}return{tools:W,restoredFromPersistence:J,restoredTeammates:H}}function G1(f){let $=f.allowSpawn??!0,J=f.includeSpawnTool??!0,W=f.includeManagementTools??!0,H=[];if(J)H.push(Jf({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:Wf(L3),execute:async(Z)=>{let j=N(L3,Z);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!$)throw Error("Spawning teammates is disabled in this context.");let X={agentId:j.agentId,rolePrompt:j.rolePrompt};if(N3({runtime:f.runtime,requesterId:f.requesterId,teammateConfigProvider:f.teammateConfigProvider,createBaseTools:f.createBaseTools,spec:X}),!W)f.onLeadToolsUnlocked?.(G1({...f,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return N(M3,{agentId:j.agentId,status:"spawned"})}}));if(!W)return H;H.push(Jf({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:Wf(_3),execute:async(Z)=>{let j=N(_3,Z);if(f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return f.runtime.shutdownTeammate(j.agentId,j.reason),N(M3,{agentId:j.agentId,status:"stopped"})}})),H.push(Jf({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:Wf(h3),execute:async(Z)=>{return N(h3,Z),N($V,f.runtime.getSnapshot())}})),H.push(Jf({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:Wf(O3),execute:async(Z)=>{let j=N(O3,Z);switch(j.action){case"create":{let X=new Set(lY.create??[]),A=Object.entries(Z).filter(([B,Y])=>X.has(B)&&Y!=null).map(([B])=>B),P=f.runtime.createTask({title:f$(j.title,"title"),description:f$(j.description,"description"),dependsOn:j.dependsOn,assignee:j.assignee,createdBy:f.requesterId});return N(U1,{action:"create",taskId:P.id,status:P.status,...A.length>0?{ignoredFields:A,note:`Ignored fields for action=create: ${A.join(", ")}`}:{}})}case"list":return N(U1,{action:"list",tasks:f.runtime.listTaskItems({status:j.status,assignee:j.assignee})});case"claim":{let X=f.runtime.claimTask(f$(j.taskId,"taskId"),f.requesterId);return N(U1,{action:"claim",taskId:X.id,status:X.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let X=f.runtime.completeTask(f$(j.taskId,"taskId"),f.requesterId,f$(j.summary,"summary"));return N(U1,{action:"complete",taskId:X.id,status:X.status})}case"block":{let X=f.runtime.blockTask(f$(j.taskId,"taskId"),f.requesterId,f$(j.reason,"reason"));return N(U1,{action:"block",taskId:X.id,status:X.status})}}}}));let Q=new Map;return H.push(Jf({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:Wf(T3),execute:async(Z)=>{let j=N(T3,Z);if(j.runMode==="async"){let P=f.runtime.startTeammateRun(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:f.requesterId,continueConversation:j.continueConversation||void 0});return N(WJ,{agentId:j.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${j.agentId} and queued as ${P.id}.`,runId:P.id})}let X=Q.get(j.agentId);if(X){let P=await X;return N(WJ,{...P,status:"joined",deduped:!0,message:`Task for ${j.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let A=f.runtime.routeToTeammate(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:f.requesterId,continueConversation:j.continueConversation||void 0}).then((P)=>N(WJ,{agentId:j.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${j.agentId} and completed in sync mode.`,text:P.text,iterations:P.iterations})).finally(()=>{Q.delete(j.agentId)});return Q.set(j.agentId,A),await A}})),H.push(Jf({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:Wf(P3),execute:async(Z)=>{let j=N(P3,Z),X=f.runtime.cancelRun(j.runId,j.reason);return N(iY,{runId:X.id,status:X.status})}})),H.push(Jf({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:Wf(F3),execute:async(Z)=>N(HJ.array(),f.runtime.listRuns(N(F3,Z)).map(QJ))})),H.push(Jf({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:Wf(X3),timeoutMs:cY,execute:async(Z)=>{let j=N(X3,Z);if(j.runId){let P=await f.runtime.awaitRun(j.runId);return WV(P),N(HJ,QJ(P))}let X=await f.runtime.awaitAllRuns(),A=X.filter((P)=>["failed","cancelled","interrupted"].includes(P.status));if(A.length>0){let P=A.map((B)=>`${B.id}:${B.status}${B.error?`(${B.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${P}`)}return N(HJ.array(),X.map(QJ))}})),H.push(Jf({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:Wf(D3),execute:async(Z)=>{let j=N(D3,Z),X=f.runtime.sendMessage(f.requesterId,j.toAgentId,j.subject,j.body,j.taskId??void 0);return N(fV,{id:X.id,toAgentId:X.toAgentId})}})),H.push(Jf({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:Wf(A3),execute:async(Z)=>{let j=N(A3,Z),X=f.runtime.broadcast(f.requesterId,j.subject,j.body,{taskId:j.taskId??void 0});return N(pY,{delivered:X.length})}})),H.push(Jf({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:Wf(U3),execute:async(Z)=>{let j=N(U3,Z);return N(sY.array(),f.runtime.listMailbox(f.requesterId,{unreadOnly:j.unreadOnly,markRead:!0}))}})),H.push(Jf({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:Wf(K3),execute:async(Z)=>{let j=N(K3,Z),X=f.runtime.appendMissionLog({agentId:f.requesterId,taskId:j.taskId||void 0,kind:j.kind,summary:j.summary,evidence:j.evidence?.length?j.evidence:void 0,nextAction:j.nextAction||void 0});return N(oY,{id:X.id})}})),H.push(Jf({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:Wf(B3),execute:async(Z)=>{if(N(B3,Z),f.runtime.getMemberRole(f.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return f.runtime.cleanup(),N(nY,{status:"cleaned"})}})),H.push(Jf({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:Wf(Y3),execute:async(Z)=>{let j=N(Y3,Z),X=f.runtime.createOutcome({title:j.title,requiredSections:j.requiredSections,createdBy:f.requesterId});return N(aY,{outcomeId:X.id,status:X.status,requiredSections:X.requiredSections})}})),H.push(Jf({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:Wf(j3),execute:async(Z)=>{let j=N(j3,Z),X=f.runtime.attachOutcomeFragment({outcomeId:j.outcomeId,section:j.section,sourceAgentId:f.requesterId,sourceRunId:j.sourceRunId||void 0,content:j.content});return N(y3,{fragmentId:X.id,status:X.status})}})),H.push(Jf({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:Wf(G3),execute:async(Z)=>{let j=N(G3,Z),X=f.runtime.reviewOutcomeFragment({fragmentId:j.fragmentId,reviewedBy:f.requesterId,approved:j.approved});return N(y3,{fragmentId:X.id,status:X.status})}})),H.push(Jf({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:Wf(V3),execute:async(Z)=>{let j=N(V3,Z),X=f.runtime.finalizeOutcome(j.outcomeId);return N(tY,{outcomeId:X.id,status:X.status})}})),H.push(Jf({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:Wf(R3),execute:async(Z)=>{return N(R3,Z),N(eY.array(),f.runtime.listOutcomes())}})),H}function q3(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}var HV=[{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:I$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...A8]}],QV={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function ZV(f){return f==="plan"||f==="yolo"?f:"act"}function b3(f){let $=ZV(f.mode),J=df[M0({mode:$})],W=F1(f.providerId??"",f.modelId??"",$,R1);return{mode:$,flags:{...J,...W,...typeof f.enableSpawnAgent==="boolean"?{enableSpawnAgent:f.enableSpawnAgent}:{},...typeof f.enableAgentTeams==="boolean"?{enableAgentTeams:f.enableAgentTeams}:{}}}}function w3(f,$){if($.disabledToolIds?.has(f))return!1;let{flags:J}=b3($);if(f==="spawn_agent")return J.enableSpawnAgent===!0;if(f==="teams")return J.enableAgentTeams===!0;if(f==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let W=QV[f];return W?J[W]===!0:!1}function jV(f,$){if(f.id==="editor"){let{flags:J}=b3($),W=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...f,defaultEnabled:w3(f.id,$),headlessToolNames:[W?"apply_patch":"editor"]}}return{...f,defaultEnabled:w3(f.id,$)}}function T1(f={}){return HV.map(($)=>jV($,f))}function C3(f={}){return T1(f).filter(($)=>$.defaultEnabled).map(($)=>$.id)}function E3(f){if(!f.enabled)return new Set;let $=T1(f.availabilityContext),J=new Set($.map((W)=>W.id));if(!f.allowlist||f.allowlist.length===0)return new Set($.filter((W)=>W.defaultEnabled).map((W)=>W.id));for(let W of f.allowlist)if(!J.has(W))throw Error(`Unknown tool "${W}". Available tools: ${$.map((H)=>H.id).join(", ")}`);return new Set(f.allowlist)}function ZJ(f,$={}){return T1($).filter((J)=>f.has(J.id)).flatMap((J)=>J.headlessToolNames)}function S3(f,$={}){return ZJ(f,$)}function D1(f={}){let{executorOptions:$={},executors:J,...W}=f,H={...H8($),...J??{}};return E$({...W,executors:H})}function B8(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function XV(f){if(!f||f.length===0)return;let $=f.map(B8).filter((J)=>J.length>0);return $.length>0?new Set($):void 0}function AV(f,$,J){if(!J)return!0;let W=B8(f),H=B8($),Q=W.includes(":")?W.split(":").at(-1)??W:W,Z=H.includes(":")?H.split(":").at(-1)??H:H;return J.has(W)||J.has(H)||J.has(Q)||J.has(Z)}function _1(f,$){let J=XV($);return[...f.getSnapshot("skill").entries()].map(([H,Q])=>{let Z=Q.item;return{id:H,name:Z.name.trim(),description:Z.description?.trim(),disabled:Z.disabled===!0,skill:Z}}).filter((H)=>AV(H.id,H.name,J))}function PV(f,$){return _1(f,$).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,W)=>J.localeCompare(W))}function BV(f,$,J){let W=B8($);if(!W)return{error:"Missing skill name."};let H=_1(f,J),Q=H.find((P)=>P.id===W);if(Q){let{skill:P}=Q;if(P.disabled===!0)return{error:`Skill "${P.name}" is configured but disabled.`};return{id:Q.id,skill:P}}let Z=W.includes(":")?W.split(":").at(-1)??W:W,j=H.filter(({id:P})=>{if(P===Z)return!0;return P.endsWith(`:${Z}`)}),X=j.filter(({skill:P})=>P.disabled!==!0);if(X.length===1){let{id:P,skill:B}=X[0];return{id:P,skill:B}}if(X.length>1)return{error:`Skill "${$}" is ambiguous. Use one of: ${X.map(({id:P})=>P).join(", ")}`};if(j.length===1){let{skill:P}=j[0];return{error:`Skill "${P.name}" is configured but disabled.`}}if(j.length>1)return{error:`Skill "${$}" is ambiguous, and all matches are disabled: ${j.map(({id:P})=>P).join(", ")}`};let A=PV(f,J);return{error:A.length>0?`Skill "${$}" not found. Available skills: ${A.join(", ")}`:"No skills are currently available."}}function YV(f,$=Promise.resolve(),J){let W=new Set,H=async(Q,Z)=>{await $;let j=BV(f,Q,J);if("error"in j)return j.error;let{id:X,skill:A}=j;if(W.has(X))return`Skill "${A.name}" is already running.`;W.add(X);try{let P=Z?.trim(),B=P?`
|
|
145
|
+
<command-args>${P}</command-args>`:"",Y=A.description?.trim()?`Description: ${A.description.trim()}
|
|
146
146
|
|
|
147
|
-
`:"";return`<command-name>${
|
|
147
|
+
`:"";return`<command-name>${A.name}</command-name>${B}
|
|
148
148
|
<command-instructions>
|
|
149
|
-
${
|
|
150
|
-
</command-instructions>`}finally{
|
|
149
|
+
${Y}${A.instructions}
|
|
150
|
+
</command-instructions>`}finally{W.delete(X)}};return Object.defineProperty(H,"configuredSkills",{get:()=>_1(f,J).map(({skill:Q,...Z})=>Z),enumerable:!0,configurable:!1}),H}function k3(f){let $=f.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[f.includeRules?"rules":void 0,f.registerSkillsTool?"tools":void 0,f.includeSkills||f.includeWorkflows?"commands":void 0].filter((W)=>Boolean(W))},async setup(W){if(await $,f.includeRules)W.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>j9(f.watcher)});if(f.registerSkillsTool)W.registerTool(C$(YV(f.watcher,$,f.allowedSkillNames)));for(let H of B1(f.watcher).filter((Q)=>Q.kind==="skill"&&f.includeSkills||Q.kind==="workflow"&&f.includeWorkflows))W.registerCommand({name:H.name,description:H.description,handler:(Q)=>{let Z=Q.trim();return Z?`${H.instructions}
|
|
151
151
|
|
|
152
|
-
${Z}`:
|
|
153
|
-
${
|
|
152
|
+
${Z}`:H.instructions}})}}}class I3{watcher;ready;stopped=!1;constructor(f){this.watcher=J9(f)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType(f){await this.start(),await this.watcher.refreshType(f)}listRecords(f){return[...this.watcher.getSnapshot(f).entries()].map(([$,J])=>({type:f,id:$,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return B1(this.watcher)}resolveRuntimeSlashCommand(f){return Q9(f,this.watcher)}hasConfiguredSkills(f){return _1(this.watcher,f).length>0}createExtension(f){return k3({...f,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function m$(f){return new I3(f)}import{readFile as VV,writeFile as RV}from"node:fs/promises";import x3 from"yaml";function FV(f){let $=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=f.match($);if(!J)return{data:{},body:f,hadFrontmatter:!1};let[,W,H]=J,Q=x3.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:H,hadFrontmatter:!0}}function m3(f,$){return`---
|
|
153
|
+
${x3.stringify(f).trimEnd()}
|
|
154
154
|
---
|
|
155
|
-
${$}`}function eB(f,$){let{data:J,body:H,hadFrontmatter:W}=oB(f);if(!W&&$)return f;if($){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return H;return C3(J,H)}return J.disabled=!0,C3(J,H)}async function S3({filePath:f,enabled:$}){let J=await tB(f,"utf8"),H=eB(J,$);return await sB(f,H),{filePath:f,enabled:$,disabled:!$}}ef();ef();import{existsSync as uA}from"node:fs";import{discoverPluginModulePaths as cA,resolveConfiguredPluginModulePaths as dA,resolvePluginConfigSearchPaths as rA}from"@cline/shared/storage";import{resolve as GA}from"node:path";import{normalizePluginManifest as hA}from"@cline/shared";import{existsSync as h0,readFileSync as ZJ}from"node:fs";import{builtinModules as PA,createRequire as v3}from"node:module";import{dirname as Y8,extname as u3,isAbsolute as XA,resolve as Xf}from"node:path";import{fileURLToPath as c3}from"node:url";import{PLUGIN_FILE_EXTENSIONS as VA}from"@cline/shared";var YA=Y8(c3(import.meta.url)),d3=v3(import.meta.url),BA=Xf(YA,"..","..","..","..",".."),WJ=AA(BA),jJ=new Set(PA.flatMap((f)=>[f,f.replace(/^node:/,"")])),V8=new Set(VA);function AA(f){let $={},J={"@cline/agents":Xf(f,"packages/agents/src/index.ts"),"@cline/core":Xf(f,"packages/core/src/index.ts"),"@cline/llms":Xf(f,"packages/llms/src/index.ts"),"@cline/shared":Xf(f,"packages/shared/src/index.ts"),"@cline/shared/storage":Xf(f,"packages/shared/src/storage/index.ts"),"@cline/shared/db":Xf(f,"packages/shared/src/db/index.ts")};for(let[H,W]of Object.entries(J))if(h0(W))$[H]=W;return $}function r3(f){return!(f.startsWith(".")||f.startsWith("/")||f.startsWith("file:")||f.startsWith("data:")||f.startsWith("http:")||f.startsWith("https:"))}function QJ(f){if(f.startsWith("@")){let[$,J]=f.split("/",3);return J?`${$}/${J}`:f}return f.split("/",1)[0]??f}function l3(f,$){let J=QJ($),H=Y8(f);while(!0){let W=Xf(H,"node_modules",J);if(h0(W)||h0(Xf(W,"package.json")))return!0;let Q=Xf(H,"..");if(Q===H)return!1;H=Q}}function RA(f){try{return d3.resolve(f),!0}catch{return!1}}function FA(f){try{return d3.resolve(f)}catch{return null}}function yA(f){let J=Y8(f);for(let H=0;H<4;H++){let W=Xf(J,"package.json");if(h0(W))try{let Z=JSON.parse(ZJ(W,"utf8"));return Z!=null&&typeof Z==="object"&&"cline"in Z}catch{return!1}let Q=Xf(J,"..");if(Q===J)return!1;J=Q}return!1}function KA(f,$){let J=$.startsWith("file:")?c3($):XA($)?$:Xf(Y8(f),$);if(h0(J)&&V8.has(u3(J)))return J;for(let H of V8){let W=`${J}${H}`;if(h0(W))return W}for(let H of V8){let W=Xf(J,`index${H}`);if(h0(W))return W}return null}function p3(f){let $=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let H of J)for(let W of f.matchAll(H)){let Q=W[1];if(Q)$.add(Q)}return[...$]}function i3(f,$,J=new Set){if(J.has(f)||!h0(f))return;if(J.add(f),!V8.has(u3(f)))return;let H=ZJ(f,"utf8");for(let W of p3(H)){if(W.startsWith("node:")||jJ.has(W))continue;if(r3(W)){if(Object.hasOwn(WJ,W)||Object.hasOwn(WJ,QJ(W))||l3(f,W)||$&&RA(W))continue;throw Error(`Cannot find module '${QJ(W)}'`)}let Q=KA(f,W);if(Q)i3(Q,$,J)}}function UA(f,$){let J=v3(f),H={};for(let[W,Q]of Object.entries(WJ)){try{J.resolve(W);continue}catch{}H[W]=Q}if($){let W=ZJ(f,"utf8");for(let Q of p3(W)){if(!r3(Q)||Q.startsWith("node:")||jJ.has(Q)||Object.hasOwn(H,Q)||l3(f,Q))continue;let Z=FA(Q);if(Z)H[Q]=Z}}return H}async function n3(f,$={}){let J=!yA(f);i3(f,J);let H=UA(f,J),W=await import("jiti"),Q=typeof W==="function"?W:typeof W.default==="function"?W.default:void 0;if(!Q)throw Error("Unable to load jiti");return await Q(f,{alias:H,cache:$.useCache,requireCache:$.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...jJ],transformModules:Object.keys(H)}).import(f,{})}function a3(f,$){if(!f)return!0;if(f.providerIds?.length){if(!$?.providerId||!f.providerIds.includes($.providerId))return!1}if(f.modelIds?.length){if(!$?.modelId||!f.modelIds.includes($.modelId))return!1}return!0}function t3(f){return typeof f==="object"&&f!==null}function PJ(f){return Array.isArray(f)&&f.every(($)=>typeof $==="string")}function TA(f,$){if(!t3(f.manifest))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);if(!PJ(f.manifest.capabilities))throw Error(`Invalid plugin module at ${$}: manifest.capabilities must be a string array`);if(f.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${$}: manifest.capabilities cannot be empty`);if(Object.hasOwn(f.manifest,"providerIds")&&!PJ(f.manifest.providerIds))throw Error(`Invalid plugin module at ${$}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn(f.manifest,"modelIds")&&!PJ(f.manifest.modelIds))throw Error(`Invalid plugin module at ${$}: manifest.modelIds must be a string array when provided`)}function DA(f,$){if(!t3(f))throw Error(`Invalid plugin module at ${$}: expected object export`);if(typeof f.name!=="string"||f.name.length===0)throw Error(`Invalid plugin module at ${$}: expected non-empty "name"`);if(!Object.hasOwn(f,"manifest"))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);TA(f,$)}async function XJ(f,$={}){let J=GA($.cwd??process.cwd(),f),H=await n3(J,{useCache:$.useCache}),W=$.exportName??"plugin",Q=H.default??H[W];DA(Q,J);let Z=Q,j=Z.setup,P=j?(X,V)=>{let Y={...$.session,...V.session},B={...V,session:Object.keys(Y).length>0?Y:void 0,client:$.client??V.client,user:$.user??V.user,workspaceInfo:$.workspaceInfo??V.workspaceInfo,automation:$.automation??V.automation,logger:$.logger??V.logger,telemetry:$.telemetry??V.telemetry};return j(X,B)}:void 0;return{...Z,manifest:hA(Z.manifest),setup:P}}async function s3(f,$={}){return(await t0(f,$)).plugins}async function t0(f,$={}){let J=[],H=[],W=new Map,Q=0;for(let Z of f)try{let j=await XJ(Z,$);if(!a3(j.manifest,$))continue;let P=W.get(j.name);if(P)H.push({type:"duplicate_plugin_override",pluginName:j.name,pluginPath:Z,overriddenPluginPath:P.pluginPath,message:`Plugin "${j.name}" from ${Z} overrides ${P.pluginPath}`});W.set(j.name,{plugin:j,pluginPath:Z,order:Q++})}catch(j){let P=j instanceof Error?j.message:String(j);J.push({pluginPath:Z,phase:"load",message:P,stack:j instanceof Error?j.stack:void 0})}return{plugins:[...W.values()].sort((Z,j)=>Z.order-j.order).map((Z)=>Z.plugin),failures:J,warnings:H}}import{existsSync as qA}from"node:fs";import{createRequire as bA}from"node:module";import{dirname as wA,join as A8}from"node:path";import{fileURLToPath as CA}from"node:url";import{spawn as MA}from"node:child_process";import{basename as _A}from"node:path";import{augmentNodeCommandForDebug as LA,withResolvedClineBuildEnv as zA}from"@cline/shared";function o3(f){if(f instanceof Error)return f;return Error(String(f))}var OA="CLINE_JS_RUNTIME_PATH";function e3(f){let $=f?.trim();if(!$)return!1;let J=_A($).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function f7(f={}){let $=f.env??process.env,J=f.runtimeExecutable?.trim()||$[OA]?.trim();if(J)return J;let H=f.execPath?.trim()||process.execPath;if(e3(H))return H;for(let W of[$.BUN_EXEC_PATH,$.npm_node_execpath,$.NODE]){let Q=W?.trim();if(Q&&e3(Q))return Q}return"node"}function NA(f,$={}){let J=f7({env:$.env,execPath:$.execPath,runtimeExecutable:$.runtimeExecutable});return LA([J,...f],{env:$.env,execArgv:$.execArgv,debugRole:$.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class B8{options;process=null;requestCounter=0;pending=new Map;constructor(f){this.options=f}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest(f){let $=this.pending.get(f);if(!$)return;if(this.pending.delete(f),$.timeout)clearTimeout($.timeout);return $}start(){if(this.process&&this.process.exitCode===null)return;let f=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],$=NA(f,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=MA($[0]??f7(this.options),$.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:zA(process.env)});this.process=J;let H="",W=(Q)=>{let Z=H+Q;H=Z.length>4000?Z.slice(-4000):Z};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(Q)=>{W(Q)}),J.on("message",(Q)=>{this.onMessage(Q)}),J.on("error",(Q)=>{this.failPending(Error(`${this.processLabel} process error: ${o3(Q).message}`))}),J.on("exit",(Q,Z)=>{this.process=null;let j=H.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Q)}, signal=${String(Z)})${j?`: ${j}`:""}`))})}async call(f,$,J={}){this.start();let H=this.process;if(!H||H.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let W=`req_${++this.requestCounter}`,Q={type:"call",id:W,method:f,args:$};return await new Promise((Z,j)=>{let P={resolve:(X)=>Z(X),reject:j};if((J.timeoutMs??0)>0)P.timeout=setTimeout(()=>{this.clearPendingRequest(W),this.shutdown().catch(()=>{}),j(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${f}`))},J.timeoutMs);this.pending.set(W,P),H.send(Q,(X)=>{if(!X)return;let V=this.clearPendingRequest(W);if(!V)return;V.reject(Error(`${this.processLabel} failed to send call "${f}": ${o3(X).message}`))})})}async shutdown(){let f=this.process;if(this.process=null,!f||f.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise(($)=>{let J=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}$()},300);f.once("exit",()=>{clearTimeout(J),$()});try{f.kill("SIGTERM")}catch{clearTimeout(J),$()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage(f){if(!f)return;if(f.type==="event"){if(typeof f.name==="string"&&f.name.length>0)this.options.onEvent?.({name:f.name,payload:f.payload});return}if(f.type!=="response"||!f.id)return;let $=this.clearPendingRequest(f.id);if(!$)return;if(f.ok){$.resolve(f.result);return}$.reject(Error(f.error?.message||`${this.processLabel} call failed`))}failPending(f){for(let[$,J]of this.pending.entries()){if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);J.reject(f)}}}function EA(f){return{...f,contributions:{tools:f.contributions?.tools??[],commands:f.contributions?.commands??[],messageBuilders:f.contributions?.messageBuilders??[],providers:f.contributions?.providers??[],automationEventTypes:f.contributions?.automationEventTypes??[],shortcuts:f.contributions?.shortcuts??[],flags:f.contributions?.flags??[]}}}function R8(f){return(f instanceof Error?f.message:String(f)).includes("Unknown sandbox plugin id:")}function SA(){let f=wA(CA(import.meta.url)),$=bA(import.meta.url),J=[A8(f,"plugin-sandbox-bootstrap.js"),A8(f,"extensions","plugin-sandbox-bootstrap.js"),A8(f,"agents","plugin-sandbox-bootstrap.js")];for(let Q of J)if(qA(Q))return{file:Q};let H=A8(f,"plugin-sandbox-bootstrap.ts"),W="jiti";try{W=$.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(W)});`,`const jiti = createJiti(${JSON.stringify(H)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(H)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
|
|
156
|
-
`)}}var VJ=SA();function YJ(f,$){return typeof f==="number"&&f>0?f:$}async function J7(f){let $=new B8({name:"plugin-sandbox",..."file"in VJ?{bootstrapFile:VJ.file}:{bootstrapScript:VJ.script},onEvent:f.onEvent}),J=YJ(f.importTimeoutMs,4000),H=YJ(f.hookTimeoutMs,3000),W=YJ(f.contributionTimeoutMs,60000),Q={pluginPaths:f.pluginPaths,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,loggerEnabled:Boolean(f.logger)},Z,j=()=>{return Z??=$.call("initialize",Q,{timeoutMs:J}).finally(()=>{Z=void 0}),Z},P;try{P=await $.call("initialize",Q,{timeoutMs:J})}catch(Y){throw await $.shutdown().catch(()=>{}),Y}return{extensions:P.plugins.map(EA).map((Y)=>{let B={name:Y.name,manifest:Y.manifest,setup:(A)=>{kA(A,$,Y,W,j),mA(A,$,Y,W,j),xA(A,$,Y,W,j),IA(A,Y)}};return B.hooks=vA($,Y,H,j),B}),failures:P.failures,shutdown:async()=>{await $.shutdown()},warnings:P.warnings}}function kA(f,$,J,H,W){for(let Q of J.contributions?.tools??[]){let Z={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema??{type:"object",properties:{}},timeoutMs:Q.timeoutMs,retryable:Q.retryable,execute:async(j,P)=>{try{return await $.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:j,context:P},{timeoutMs:H})}catch(X){if(!R8(X))throw X;return await W(),await $.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:j,context:P},{timeoutMs:H})}}};f.registerTool(Z)}}function mA(f,$,J,H,W){for(let Q of J.contributions?.commands??[])f.registerCommand({name:Q.name,description:Q.description,handler:async(Z)=>{try{return await $.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:Z},{timeoutMs:H})}catch(j){if(!R8(j))throw j;return await W(),await $.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:Z},{timeoutMs:H})}}})}function IA(f,$){for(let J of $.contributions?.providers??[])f.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of $.contributions?.automationEventTypes??[])f.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function xA(f,$,J,H,W){for(let Q of J.contributions?.messageBuilders??[])f.registerMessageBuilder({name:Q.name,async build(Z){try{let j=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:Z},{timeoutMs:H});return $7(j)?j:Z}catch(j){if(!R8(j))throw j;await W();let P=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:Z},{timeoutMs:H});return $7(P)?P:Z}}})}function $7(f){return Array.isArray(f)&&f.every(($)=>typeof $==="object"&&$!==null&&("role"in $)&&("content"in $))}function gA(f,$,J,H,W){return async(Q)=>{try{return await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:H})}catch(Z){if(!R8(Z))throw Z;return await W(),await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:H})}}}function vA(f,$,J,H){let W={};for(let Q of $.hooks??[])W[Q]=gA(f,$.pluginId,Q,J,H);return Object.keys(W).length>0?W:void 0}function BJ(f){return rA(f)}function AJ(f){return cA(f)}function G1(f={}){let $=f.cwd??process.cwd(),J=BJ(f.workspacePath).flatMap((Z)=>AJ(Z)).filter((Z)=>uA(Z)),H=dA(f.pluginPaths??[],$),W=[],Q=new Set;for(let Z of[...H,...J]){if(Q.has(Z))continue;Q.add(Z),W.push(Z)}return JJ(W)}async function F8(f={}){let $=G1(f);if($.length===0)return{extensions:[],failures:[],warnings:[]};if(f.mode==="in_process"){let H=await t0($,{cwd:f.cwd,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,automation:f.automation,logger:f.logger,telemetry:f.telemetry});return{extensions:H.plugins,failures:H.failures,warnings:H.warnings}}let J=await J7({pluginPaths:$,exportName:f.exportName,importTimeoutMs:f.importTimeoutMs,hookTimeoutMs:f.hookTimeoutMs,contributionTimeoutMs:f.contributionTimeoutMs,onEvent:f.onEvent,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,logger:f.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,warnings:J.warnings}}ef();function lA(f,$){if(!f.setup)return[];let J=[],H={registerTool:(W)=>J.push(W),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return f.setup(H,{workspaceInfo:$}),J}async function RJ(f){let $=G1({workspacePath:f.workspacePath,cwd:f.cwd}),J=cf(f.disabledToolNames),H=[];for(let W of $){let Q=await t0([W],{cwd:f.cwd,providerId:f.providerId,modelId:f.modelId});for(let Z of Q.plugins)for(let j of lA(Z,{rootPath:f.workspacePath}))H.push({name:j.name,pluginName:Z.name,path:W,source:W.startsWith(f.workspacePath)?"workspace-plugin":"global-plugin",enabled:!J.has(j.name),description:j.description?.trim()||void 0})}return H.sort((W,Q)=>{let Z=W.name.localeCompare(Q.name);if(Z!==0)return Z;return W.path.localeCompare(Q.path)})}function yJ(f,$){if(!$)return"global";let J=iA($,f);return!J.startsWith("..")&&!pA(J)?"workspace":"global"}function y8(f){return[...f].sort(($,J)=>{let H=(W)=>{switch(W){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if($.source!==J.source)return H($.source)-H(J.source);return $.name.localeCompare(J.name)})}function Q7(f){return f.workspaceRoot?.trim()||f.cwd?.trim()||""}async function W7(f,$){if(f.userInstructionService)return await $(f.userInstructionService);let J=Q7(f);if(!J)return await $(void 0);let H=C$({skills:{workspacePath:J},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await H.start(),await $(H)}finally{H.stop()}}function nA(f,$){if(!f)return;let J=f.listRecords("skill");if($.id){let H=J.find((W)=>W.id===$.id);if(H)return H}for(let H of J)if(H.filePath===$.path||H.item.name===$.name||H.id===$.name)return H;return}class k${async list(f={}){return await W7(f,async($)=>{let J=Q7(f),H=[],W=[],Q=[],Z=[];if($){for(let j of $.listRecords("workflow")){let P=j.item;H.push({id:j.id,name:P.name,path:j.filePath,enabled:P.disabled!==!0,kind:"workflow",source:yJ(j.filePath,J),description:P.instructions,toggleable:!1})}for(let j of $.listRecords("rule")){let P=j.item;W.push({id:j.id,name:P.name,path:j.filePath,enabled:P.disabled!==!0,kind:"rule",source:yJ(j.filePath,J),description:P.instructions,toggleable:!1})}for(let j of $.listRecords("skill")){let P=j.item;Q.push({id:j.id,name:P.name,path:j.filePath,enabled:P.disabled!==!0,kind:"skill",source:yJ(j.filePath,J),description:P.description,toggleable:!0})}}if(J)try{for(let j of await RJ({workspacePath:J,cwd:f.cwd,providerId:f.availabilityContext?.providerId,modelId:f.availabilityContext?.modelId}))Z.push({id:`${j.pluginName}:${j.name}:${j.path}`,name:j.name,path:j.path,enabled:j.enabled,kind:"tool",source:j.source,description:j.description,toggleable:!0})}catch{}return{workflows:y8(H.filter((j)=>FJ(j.path))),rules:y8(W.filter((j)=>FJ(j.path))),skills:y8(Q.filter((j)=>FJ(j.path))),tools:y8(Z)}})}async toggle(f){if(f.type==="skills")return await W7(f,async($)=>{let J=nA($,f),H=J?.filePath;if(!H)throw Error(`Unable to resolve skill setting '${f.id??f.name??H7(f.path??"")}'.`);let W=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,Q=f.enabled??(W!==void 0?!W:void 0);if(Q===void 0)throw Error(`Cannot determine toggle state for skill '${f.id??f.name??H7(f.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await S3({filePath:H,enabled:Q}),await $?.refreshType("skill"),{snapshot:await this.list({...f,userInstructionService:$}),changedTypes:["skills"]}});if(f.type==="tools"){if(!f.name?.trim())throw Error("Tool settings toggle requires a tool name.");if(f.enabled===void 0)$J(f.name);else g3(f.name,!f.enabled);return{snapshot:await this.list(f),changedTypes:["tools"]}}throw Error(`Settings type '${f.type}' does not support toggles.`)}}function h1(){return new k$}function Z7(f){return{async list($){let J=f;if(J.listSettings)return await J.listSettings($);return await h1().list($)},async toggle($){let J=f;if(J.toggleSetting)return await J.toggleSetting($);return await h1().toggle($)}}}function j7(f){function $(){let J=f.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return $().list(J)},update(J){return $().update(J)},delete(J){return $().delete(J)}}}function Vf(...f){let $,J;for(let W of f){if(!W)continue;if(W.toolExecutors)$={...$??{},...W.toolExecutors};if(W.requestToolApproval)J=W.requestToolApproval}let H=$&&Object.keys($).length>0;if(!H&&!J)return;return{...H?{toolExecutors:$}:{},...J?{requestToolApproval:J}:{}}}function KJ(f){let{hooks:$,logger:J,telemetry:H,extensionContext:W,extraTools:Q,extensions:Z,onTeamEvent:j,onConsecutiveMistakeLimitReached:P,checkpoint:X,compaction:V,...Y}=f,B={};if($)B.hooks=$;if(J)B.logger=J;if(H)B.telemetry=H;if(W)B.extensionContext=W;if(Q)B.extraTools=Q;if(Z)B.extensions=Z;if(j)B.onTeamEvent=j;if(P)B.onConsecutiveMistakeLimitReached=P;if(X?.createCheckpoint)B.checkpoint=X;if(V?.compact)B.compaction=V;let A=Object.keys(B).length>0?B:void 0;return{config:{...Y,...X?{checkpoint:{enabled:X.enabled}}:{},...V?{compaction:{enabled:V.enabled,strategy:V.strategy,thresholdRatio:V.thresholdRatio,reserveTokens:V.reserveTokens,preserveRecentTokens:V.preserveRecentTokens,contextWindowTokens:V.contextWindowTokens,summarizer:V.summarizer}}:{}},...A?{localRuntime:A}:{}}}function P7(f){let $=f.config;return"providerId"in $?{...f,config:{...$,...aA(f.localRuntime)},localRuntime:f.localRuntime}:f}function UJ(f,$={}){let J=KJ(f.config),H=Vf($.defaultCapabilities,f.capabilities),W=tA(J.localRuntime,f.localRuntime),Q=$.withExtensionContext?.(W?.extensionContext);if(Q)W={...W??{},extensionContext:Q};return{...f,...J,...W?{localRuntime:W}:{},...H?{capabilities:H}:{}}}function aA(f){if(!f)return{};let{modelCatalogDefaults:$,userInstructionService:J,configExtensions:H,onTeamRestored:W,...Q}=f;return Q}function tA(...f){let $={};for(let J of f)if(J)Object.assign($,J);return Object.keys($).length>0?$:void 0}Af();function X7(f){let $=f.input.config.telemetry??f.telemetry;if(!$)return;$.capture({event:I.SESSION.STARTED,properties:{sessionId:f.sessionId,source:f.input.source??Pf.CORE,providerId:f.input.config.providerId,modelId:f.input.config.modelId,enableTools:f.input.config.enableTools,enableSpawnAgent:f.input.config.enableSpawnAgent,enableAgentTeams:f.input.config.enableAgentTeams,clientName:f.clientName,runtimeAddress:f.runtimeAddress}})}function T1(f){return!!f&&typeof f==="object"&&!Array.isArray(f)}function GJ(f){let $=f?.trim();return $?$:void 0}function sA(f,$){let J=f?.trim();if(!J)return $;let H=Date.parse(J);if(!Number.isFinite(H))return $;return new Date(H).toISOString()}function V7(f,$){return new Date(new Date(f).getTime()+Math.max(0,Math.floor($))*1000).toISOString()}function Y7(f,$){return new Date(new Date(f).getTime()-Math.max(0,Math.floor($))*1000).toISOString()}function oA(f,$){if(!f)return $;return new Date(f).getTime()>=new Date($).getTime()?f:$}function eA(f,$){let J=f.eventId.trim(),H=f.eventType.trim(),W=f.source.trim(),Q=GJ(f.subject),Z=GJ(f.dedupeKey)??`${H}:${W}:${Q??J}`;return{eventId:J,eventType:H,source:W,subject:Q,occurredAt:sA(f.occurredAt,$),workspaceRoot:GJ(f.workspaceRoot),payload:T1(f.payload)?f.payload:void 0,attributes:T1(f.attributes)?f.attributes:void 0,dedupeKey:Z}}function hJ(f,$){if(!$)return;let J=$.split("."),H=f;for(let W of J){if(!T1(H))return;H=H[W]}return H}function fR(f,$){if(f.attributes&&Object.hasOwn(f.attributes,$))return f.attributes[$];if(f.payload&&Object.hasOwn(f.payload,$))return f.payload[$];let J={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload},H=hJ(J,$);if(H!==void 0)return H;if(f.attributes){let W=hJ(f.attributes,$);if(W!==void 0)return W}if(f.payload)return hJ(f.payload,$);return}function K8(f,$){if(Array.isArray($))return $.some((J)=>K8(f,J));if(Array.isArray(f))return f.some((J)=>K8(J,$));if(T1($)){if(!T1(f))return!1;return Object.entries($).every(([J,H])=>K8(f[J],H))}return Object.is(f,$)}function $R(f,$){if(!$||Object.keys($).length===0)return!0;return Object.entries($).every(([J,H])=>K8(fR(f,J),H))}class TJ{store;nowFn;logger;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now()),this.logger=f.logger}ingestEvent(f){let $=new Date(this.nowFn()).toISOString(),J=eA(f,$),H=this.store.insertEventLog(J,{receivedAtIso:$});if(!H.created)return this.logger?.debug("cron.event.duplicate",{eventId:H.record.eventId,eventType:H.record.eventType,source:H.record.source}),{event:H.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:H.record.dedupeKey}]};try{let W=this.store.listEventSpecsForType(J.eventType),Q=[],Z=[],j=[];for(let V of W){if(!$R(J,V.filters)){Q.push({specId:V.specId,externalId:V.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}Z.push(V);let Y=this.materializeForSpec(V,J,H.record.receivedAt);if(Y.run)j.push(Y.run);else Q.push({specId:V.specId,externalId:V.externalId,reason:Y.reason,dedupeKey:J.dedupeKey})}let P=Z.length===0?"unmatched":j.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(H.record.eventId,{status:P,matchedSpecCount:Z.length,queuedRunCount:j.length,suppressedCount:Q.filter((V)=>V.reason!=="filter_mismatch").length});let X=this.store.getEventLog(H.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:H.record.eventId,eventType:H.record.eventType,status:P,matchedSpecCount:Z.length,queuedRunCount:j.length}),{event:X??H.record,duplicate:!1,matchedSpecs:Z,queuedRuns:j,suppressions:Q}}catch(W){if(this.store.updateEventLogProcessing(H.record.eventId,{status:"failed",error:W instanceof Error?W.message:String(W)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:H.record.eventId,eventType:H.record.eventType,error:W});throw W}}materializeForSpec(f,$,J){let H=$.dedupeKey??$.eventId,W=f.debounceSeconds??0;if(W>0){let P=this.store.findQueuedEventRunForDedupe({specId:f.specId,dedupeKey:H});if(P){let X=oA(P.scheduledFor,V7(J,W)),V=this.store.updateQueuedEventRunForDebounce({runId:P.runId,triggerEventId:$.eventId,scheduledFor:X});if(V)return{run:V,reason:"dedupe_window"}}}let Q=f.dedupeWindowSeconds??0;if(Q>0&&this.store.hasRecentEventRunForDedupe({specId:f.specId,dedupeKey:H,sinceIso:Y7(J,Q)}))return{reason:"dedupe_window"};let Z=f.cooldownSeconds??0;if(Z>0&&this.store.hasRecentEventRunForSpec({specId:f.specId,sinceIso:Y7(J,Z)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"event",triggerEventId:$.eventId,scheduledFor:W>0?V7(J,W):J}),reason:"dedupe_window"}}}class D1{store;nowFn;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now())}materializeAll(){let f={oneOffQueued:0,scheduleQueued:0},$=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let H of $)if(this.materializeOneOff(H))f.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let H of J)try{if(this.materializeSchedule(H))f.scheduleQueued+=1}catch{}return f}materializeOneOff(f){if(f.triggerKind!=="one_off")return!1;if(!f.enabled||f.removed)return!1;if(this.store.hasOneOffRunForRevision(f.specId,f.revision))return!1;return this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule(f){if(f.triggerKind!=="schedule")return!1;if(!f.enabled||f.removed)return!1;if(!f.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:f.specId,nowMs:this.nowFn()}).queued}}import{basename as YR}from"node:path";import{buildClineSystemPrompt as BR}from"@cline/shared";import{nowIso as F7}from"@cline/shared/db";import{basename as JR,resolve as HR}from"node:path";import{performance as B7}from"node:perf_hooks";import{processWorkspaceInfo as A7}from"@cline/shared";import WR from"simple-git";function s0(f){return HR(f)}async function G8(f){return(await DJ(f)).info}function U8(f){if(f instanceof Error)return{errorType:f.name?.trim()||f.constructor.name||"Error",message:f.message};return{errorType:"Error",message:String(f)}}async function DJ(f){let $=s0(f),J={rootPath:$,hint:JR($)},H;try{let W=WR({baseDir:$});if(!await W.checkIsRepo())return{info:J,vcsType:"none"};try{let Z=await W.getRemotes(!0);if(Z.length>0){let j=Z.map((P)=>{let X=P.refs.fetch||P.refs.push;return`${P.name}: ${X}`});J.associatedRemoteUrls=j}}catch(Z){H??=U8(Z)}try{let Z=(await W.revparse(["HEAD"])).trim();if(Z.length>0)J.latestGitCommitHash=Z}catch(Z){H??=U8(Z)}try{let Z=(await W.branch()).current.trim();if(Z.length>0)J.latestGitBranchName=Z}catch(Z){H??=U8(Z)}return{info:J,vcsType:"git",error:H}}catch(W){return{info:J,vcsType:"none",error:U8(W)}}}async function MJ(f){let $=await G8(f);return A7($)}async function R7(f){let $=B7.now(),J=await DJ(f),H=B7.now()-$,W=J.info;return{workspaceInfo:W,workspaceMetadata:A7(W),durationMs:H,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as QR,writeFileSync as ZR}from"node:fs";import{join as jR}from"node:path";import{resolveCronReportsDir as PR}from"@cline/shared/storage";function T0(f){if(/[:#\n]/.test(f)||f.includes('"'))return JSON.stringify(f);return f}function o0(f,$){if($===void 0||$===null)return;return`${f}: ${T0($)}`}function XR(f,$,J){let H=[`runId: ${T0(f.runId)}`,`specId: ${T0($.specId)}`,`externalId: ${T0($.externalId)}`,`title: ${T0($.title)}`,`triggerKind: ${T0(f.triggerKind)}`,`status: ${T0(f.status)}`,`sourcePath: ${T0($.sourcePath)}`],W=[o0("sessionId",f.sessionId),o0("startedAt",f.startedAt),o0("completedAt",f.completedAt),o0("triggerEventId",f.triggerEventId),o0("triggerEventType",J?.eventType),o0("triggerEventSource",J?.source),o0("triggerEventSubject",J?.subject)];for(let Q of W)if(Q)H.push(Q);return`---
|
|
157
|
-
${
|
|
155
|
+
${$}`}function KV(f,$){let{data:J,body:W,hadFrontmatter:H}=FV(f);if(!H&&$)return f;if($){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return W;return m3(J,W)}return J.disabled=!0,m3(J,W)}async function g3({filePath:f,enabled:$}){let J=await VV(f,"utf8"),W=KV(J,$);return await RV(f,W),{filePath:f,enabled:$,disabled:!$}}W0();W0();import{existsSync as XR}from"node:fs";import{discoverPluginModulePaths as AR,resolveConfiguredPluginModulePaths as PR,resolvePluginConfigSearchPaths as BR}from"@cline/shared/storage";import{resolve as vV}from"node:path";import{normalizePluginManifest as uV}from"@cline/shared";import{existsSync as Bf,readFileSync as u$}from"node:fs";import{builtinModules as hV,createRequire as p3}from"node:module";import{dirname as h1,extname as RJ,isAbsolute as OV,resolve as v}from"node:path";import{fileURLToPath as i3}from"node:url";import{PLUGIN_FILE_EXTENSIONS as zV}from"@cline/shared";var n3=h1(i3(import.meta.url)),NV=p3(import.meta.url),qV=v(n3,"..","..","..","..",".."),BJ=CV(qV),wV=["@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"],FJ=new Set(hV.flatMap((f)=>[f,f.replace(/^node:/,"")])),L1=new Set(zV),bV=["development","node","import","require","default"];function CV(f){let $={},J={"@cline/agents":v(f,"packages/agents/src/index.ts"),"@cline/core":v(f,"packages/core/src/index.ts"),"@cline/llms":v(f,"packages/llms/src/index.ts"),"@cline/shared":v(f,"packages/shared/src/index.ts"),"@cline/shared/storage":v(f,"packages/shared/src/storage/index.ts"),"@cline/shared/db":v(f,"packages/shared/src/db/index.ts")};for(let[W,H]of Object.entries(J))if(Bf(H))$[W]=H;for(let W of["agents","core","llms","shared"]){let H=v(f,"packages",W),Q=v(H,"package.json");if(!Bf(Q))continue;try{let Z=JSON.parse(u$(Q,"utf8"));if(typeof Z.name!=="string"||!Z.exports)continue;if(typeof Z.exports==="string"){let j=v(H,Z.exports);if(Bf(j))$[Z.name]=j;continue}if(typeof Z.exports!=="object")continue;for(let[j,X]of Object.entries(Z.exports)){let A=EV(H,X);if(!A)continue;let P=j==="."?Z.name:`${Z.name}/${j.replace(/^\.\//,"")}`;$[P]=A}}catch{}}return $}function EV(f,$){let J=KJ($);if(!J)return null;let W=a3(f,J);for(let H of W)if(Bf(H))return H;return null}function KJ(f,$=new Set){if(typeof f==="string")return f;if(!f||typeof f!=="object")return null;if($.has(f))return null;$.add(f);let J=f;for(let W of bV){let H=KJ(J[W],$);if(H)return H}return null}function a3(f,$){let J=$.replace(/^\.\//,""),W=[v(f,$)];if(J.startsWith("dist/")){let H=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[v(f,`${H}.ts`),v(f,`${H}.tsx`),v(f,`${H}.mts`),v(f,`${H}.cts`),...W]}return W}function SV(f){return Object.fromEntries(Object.entries(f).sort(([$],[J])=>J.length-$.length))}function R8(f){return!(f.startsWith(".")||f.startsWith("/")||f.startsWith("file:")||f.startsWith("data:")||f.startsWith("http:")||f.startsWith("https:"))}function v$(f){if(f.startsWith("@")){let[$,J]=f.split("/",3);return J?`${$}/${J}`:f}return f.split("/",1)[0]??f}function kV(f){let $=v$(f);if(f===$)return".";return`.${f.slice($.length)}`}function t3(f){return v$(f).startsWith("@cline/")}function YJ(f,$){let J=v$($),W=h1(f);while(!0){let H=v(W,"node_modules",J);if(Bf(H)||Bf(v(H,"package.json")))return!0;let Q=v(W,"..");if(Q===W)return!1;W=Q}}function l3(f){return VJ(f)!==null}function VJ(f){try{return NV.resolve(f)}catch{}return IV(f)}function IV(f){let $=v$(f),J=mV($);if(!J)return null;let W=v(J,"package.json");try{let H=JSON.parse(u$(W,"utf8")),Q=kV(f),Z=Q==="."&&typeof H.exports==="string"?H.exports:H.exports&&typeof H.exports==="object"&&Object.hasOwn(H.exports,Q)?H.exports[Q]:void 0,j=KJ(Z)??(Q==="."&&typeof H.main==="string"?H.main:null);if(!j)return null;let X=v(J,j),A=[X,...a3(J,j).filter((P)=>P!==X)];for(let P of A)if(Bf(P))return P;return null}catch{return null}}function mV(f){let $=n3;while(!0){let J=v($,"package.json");if(Bf(J))try{if(JSON.parse(u$(J,"utf8")).name===f)return $}catch{}let W=v($,"node_modules",f,"package.json");if(Bf(W))return h1(W);let H=v($,"..");if(H===$)return null;$=H}}function xV(f){let J=h1(f);for(let W=0;W<4;W++){let H=v(J,"package.json");if(Bf(H))try{let Z=JSON.parse(u$(H,"utf8"));return Z!=null&&typeof Z==="object"&&"cline"in Z}catch{return!1}let Q=v(J,"..");if(Q===J)return!1;J=Q}return!1}function s3(f,$){let J=$.startsWith("file:")?i3($):OV($)?$:v(h1(f),$);if(Bf(J)&&L1.has(RJ(J)))return J;for(let W of L1){let H=`${J}${W}`;if(Bf(H))return H}for(let W of L1){let H=v(J,`index${W}`);if(Bf(H))return H}return null}function o3(f){let $=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let W of J)for(let H of f.matchAll(W)){let Q=H[1];if(Q)$.add(Q)}return[...$]}function e3(f,$,J=new Set){if(J.has(f)||!Bf(f))return;if(J.add(f),!L1.has(RJ(f)))return;let W=u$(f,"utf8");for(let H of o3(W)){if(H.startsWith("node:")||FJ.has(H))continue;if(R8(H)){if(Object.hasOwn(BJ,H)||Object.hasOwn(BJ,v$(H))||YJ(f,H)||t3(H)&&l3(H)||$&&l3(H))continue;throw Error(`Cannot find module '${v$(H)}'`)}let Q=s3(f,H);if(Q)e3(Q,$,J)}}function fQ(f,$=new Set,J=new Set){if($.has(f)||!Bf(f))return J;if($.add(f),!L1.has(RJ(f)))return J;let W=u$(f,"utf8");for(let H of o3(W)){if(J.add(H),R8(H))continue;let Q=s3(f,H);if(Q)fQ(Q,$,J)}return J}function gV(f,$){let J=p3(f),W={},H=fQ(f),Q=new Set(wV);for(let[Z,j]of Object.entries(BJ)){try{J.resolve(Z);continue}catch{}W[Z]=j}for(let Z of H)if(R8(Z)&&(t3(Z)||$))Q.add(Z);for(let Z of Q){if(Object.hasOwn(W,Z)||YJ(f,Z))continue;let j=VJ(Z);if(j)W[Z]=j}if(!$)return W;for(let Z of H){if(!R8(Z)||Object.hasOwn(W,Z)||YJ(f,Z)||Z.startsWith("node:")||FJ.has(Z))continue;let j=VJ(Z);if(j)W[Z]=j}return W}async function $Q(f,$={}){let J=!xV(f);e3(f,J);let W=gV(f,J),H=SV(W),Q=await import("jiti"),Z=typeof Q==="function"?Q:typeof Q.default==="function"?Q.default:void 0;if(!Z)throw Error("Unable to load jiti");return await Z(f,{alias:H,cache:$.useCache,requireCache:$.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...FJ],transformModules:Object.keys(H)}).import(f,{})}function JQ(f,$){if(!f)return!0;if(f.providerIds?.length){if(!$?.providerId||!f.providerIds.includes($.providerId))return!1}if(f.modelIds?.length){if(!$?.modelId||!f.modelIds.includes($.modelId))return!1}return!0}function WQ(f){return typeof f==="object"&&f!==null}function yJ(f){return Array.isArray(f)&&f.every(($)=>typeof $==="string")}function cV(f,$){if(!WQ(f.manifest))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);if(!yJ(f.manifest.capabilities))throw Error(`Invalid plugin module at ${$}: manifest.capabilities must be a string array`);if(f.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${$}: manifest.capabilities cannot be empty`);if(Object.hasOwn(f.manifest,"providerIds")&&!yJ(f.manifest.providerIds))throw Error(`Invalid plugin module at ${$}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn(f.manifest,"modelIds")&&!yJ(f.manifest.modelIds))throw Error(`Invalid plugin module at ${$}: manifest.modelIds must be a string array when provided`)}function dV(f,$){if(!WQ(f))throw Error(`Invalid plugin module at ${$}: expected object export`);if(typeof f.name!=="string"||f.name.length===0)throw Error(`Invalid plugin module at ${$}: expected non-empty "name"`);if(!Object.hasOwn(f,"manifest"))throw Error(`Invalid plugin module at ${$}: missing required "manifest"`);cV(f,$)}async function UJ(f,$={}){let J=vV($.cwd??process.cwd(),f),W=await $Q(J,{useCache:$.useCache}),H=$.exportName??"plugin",Q=W.default??W[H];dV(Q,J);let Z=Q,j=Z.setup,X=j?(A,P)=>{let B={...$.session,...P.session},Y={...P,session:Object.keys(B).length>0?B:void 0,client:$.client??P.client,user:$.user??P.user,workspaceInfo:$.workspaceInfo??P.workspaceInfo,automation:$.automation??P.automation,logger:$.logger??P.logger,telemetry:$.telemetry??P.telemetry};return j(A,Y)}:void 0;return{...Z,manifest:uV(Z.manifest),setup:X}}async function HQ(f,$={}){return(await $$(f,$)).plugins}async function $$(f,$={}){let J=[],W=[],H=new Map,Q=0;for(let Z of f)try{let j=await UJ(Z,$);if(!JQ(j.manifest,$))continue;let X=H.get(j.name);if(X)W.push({type:"duplicate_plugin_override",pluginName:j.name,pluginPath:Z,overriddenPluginPath:X.pluginPath,message:`Plugin "${j.name}" from ${Z} overrides ${X.pluginPath}`});H.set(j.name,{plugin:j,pluginPath:Z,order:Q++})}catch(j){let X=j instanceof Error?j.message:String(j);J.push({pluginPath:Z,phase:"load",message:X,stack:j instanceof Error?j.stack:void 0})}return{plugins:[...H.values()].sort((Z,j)=>Z.order-j.order).map((Z)=>Z.plugin),failures:J,warnings:W}}import{existsSync as tV}from"node:fs";import{createRequire as sV}from"node:module";import{dirname as oV,join as K8}from"node:path";import{fileURLToPath as eV}from"node:url";import{spawn as rV}from"node:child_process";import{basename as lV}from"node:path";import{augmentNodeCommandForDebug as pV,withResolvedClineBuildEnv as iV}from"@cline/shared";function QQ(f){if(f instanceof Error)return f;return Error(String(f))}var nV="CLINE_JS_RUNTIME_PATH";function ZQ(f){let $=f?.trim();if(!$)return!1;let J=lV($).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function jQ(f={}){let $=f.env??process.env,J=f.runtimeExecutable?.trim()||$[nV]?.trim();if(J)return J;let W=f.execPath?.trim()||process.execPath;if(ZQ(W))return W;for(let H of[$.BUN_EXEC_PATH,$.npm_node_execpath,$.NODE]){let Q=H?.trim();if(Q&&ZQ(Q))return Q}return"node"}function aV(f,$={}){let J=jQ({env:$.env,execPath:$.execPath,runtimeExecutable:$.runtimeExecutable});return pV([J,...f],{env:$.env,execArgv:$.execArgv,debugRole:$.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class F8{options;process=null;requestCounter=0;pending=new Map;constructor(f){this.options=f}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest(f){let $=this.pending.get(f);if(!$)return;if(this.pending.delete(f),$.timeout)clearTimeout($.timeout);return $}start(){if(this.process&&this.process.exitCode===null)return;let f=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],$=aV(f,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=rV($[0]??jQ(this.options),$.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:iV(process.env)});this.process=J;let W="",H=(Q)=>{let Z=W+Q;W=Z.length>4000?Z.slice(-4000):Z};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(Q)=>{H(Q)}),J.on("message",(Q)=>{this.onMessage(Q)}),J.on("error",(Q)=>{this.failPending(Error(`${this.processLabel} process error: ${QQ(Q).message}`))}),J.on("exit",(Q,Z)=>{this.process=null;let j=W.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Q)}, signal=${String(Z)})${j?`: ${j}`:""}`))})}async call(f,$,J={}){this.start();let W=this.process;if(!W||W.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let H=`req_${++this.requestCounter}`,Q={type:"call",id:H,method:f,args:$};return await new Promise((Z,j)=>{let X={resolve:(A)=>Z(A),reject:j};if((J.timeoutMs??0)>0)X.timeout=setTimeout(()=>{this.clearPendingRequest(H),this.shutdown().catch(()=>{}),j(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${f}`))},J.timeoutMs);this.pending.set(H,X),W.send(Q,(A)=>{if(!A)return;let P=this.clearPendingRequest(H);if(!P)return;P.reject(Error(`${this.processLabel} failed to send call "${f}": ${QQ(A).message}`))})})}async shutdown(){let f=this.process;if(this.process=null,!f||f.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise(($)=>{let J=setTimeout(()=>{try{f.kill("SIGKILL")}catch{}$()},300);f.once("exit",()=>{clearTimeout(J),$()});try{f.kill("SIGTERM")}catch{clearTimeout(J),$()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage(f){if(!f)return;if(f.type==="event"){if(typeof f.name==="string"&&f.name.length>0)this.options.onEvent?.({name:f.name,payload:f.payload});return}if(f.type!=="response"||!f.id)return;let $=this.clearPendingRequest(f.id);if(!$)return;if(f.ok){$.resolve(f.result);return}$.reject(Error(f.error?.message||`${this.processLabel} call failed`))}failPending(f){for(let[$,J]of this.pending.entries()){if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);J.reject(f)}}}function fR(f){return{...f,contributions:{tools:f.contributions?.tools??[],commands:f.contributions?.commands??[],messageBuilders:f.contributions?.messageBuilders??[],providers:f.contributions?.providers??[],automationEventTypes:f.contributions?.automationEventTypes??[],shortcuts:f.contributions?.shortcuts??[],flags:f.contributions?.flags??[]}}}function y8(f){return(f instanceof Error?f.message:String(f)).includes("Unknown sandbox plugin id:")}function $R(){let f=oV(eV(import.meta.url)),$=sV(import.meta.url),J=[K8(f,"plugin-sandbox-bootstrap.js"),K8(f,"extensions","plugin-sandbox-bootstrap.js"),K8(f,"agents","plugin-sandbox-bootstrap.js")];for(let Q of J)if(tV(Q))return{file:Q};let W=K8(f,"plugin-sandbox-bootstrap.ts"),H="jiti";try{H=$.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(H)});`,`const jiti = createJiti(${JSON.stringify(W)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(W)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
|
|
156
|
+
`)}}var GJ=$R();function TJ(f,$){return typeof f==="number"&&f>0?f:$}async function AQ(f){let $=new F8({name:"plugin-sandbox",..."file"in GJ?{bootstrapFile:GJ.file}:{bootstrapScript:GJ.script},onEvent:f.onEvent}),J=TJ(f.importTimeoutMs,4000),W=TJ(f.hookTimeoutMs,3000),H=TJ(f.contributionTimeoutMs,60000),Q={pluginPaths:f.pluginPaths,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,loggerEnabled:Boolean(f.logger)},Z,j=()=>{return Z??=$.call("initialize",Q,{timeoutMs:J}).finally(()=>{Z=void 0}),Z},X;try{X=await $.call("initialize",Q,{timeoutMs:J})}catch(B){throw await $.shutdown().catch(()=>{}),B}return{extensions:X.plugins.map(fR).map((B)=>{let Y={name:B.name,manifest:B.manifest,setup:(V)=>{JR(V,$,B,H,j),WR(V,$,B,H,j),QR(V,$,B,H,j),HR(V,B)}};return Y.hooks=jR($,B,W,j),Y}),failures:X.failures,shutdown:async()=>{await $.shutdown()},warnings:X.warnings}}function JR(f,$,J,W,H){for(let Q of J.contributions?.tools??[]){let Z={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema??{type:"object",properties:{}},timeoutMs:Q.timeoutMs,retryable:Q.retryable,execute:async(j,X)=>{try{return await $.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:j,context:X},{timeoutMs:W})}catch(A){if(!y8(A))throw A;return await H(),await $.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:j,context:X},{timeoutMs:W})}}};f.registerTool(Z)}}function WR(f,$,J,W,H){for(let Q of J.contributions?.commands??[])f.registerCommand({name:Q.name,description:Q.description,handler:async(Z)=>{try{return await $.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:Z},{timeoutMs:W})}catch(j){if(!y8(j))throw j;return await H(),await $.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:Z},{timeoutMs:W})}}})}function HR(f,$){for(let J of $.contributions?.providers??[])f.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of $.contributions?.automationEventTypes??[])f.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function QR(f,$,J,W,H){for(let Q of J.contributions?.messageBuilders??[])f.registerMessageBuilder({name:Q.name,async build(Z){try{let j=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:Z},{timeoutMs:W});return XQ(j)?j:Z}catch(j){if(!y8(j))throw j;await H();let X=await $.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:Z},{timeoutMs:W});return XQ(X)?X:Z}}})}function XQ(f){return Array.isArray(f)&&f.every(($)=>typeof $==="object"&&$!==null&&("role"in $)&&("content"in $))}function ZR(f,$,J,W,H){return async(Q)=>{try{return await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:W})}catch(Z){if(!y8(Z))throw Z;return await H(),await f.call("invokeHook",{pluginId:$,hookName:J,payload:Q},{timeoutMs:W})}}}function jR(f,$,J,W){let H={};for(let Q of $.hooks??[])H[Q]=ZR(f,$.pluginId,Q,J,W);return Object.keys(H).length>0?H:void 0}function DJ(f){return BR(f)}function _J(f){return AR(f)}function O1(f={}){let $=f.cwd??process.cwd(),J=DJ(f.workspacePath).flatMap((Z)=>_J(Z)).filter((Z)=>XR(Z)),W=PR(f.pluginPaths??[],$),H=[],Q=new Set;for(let Z of[...W,...J]){if(Q.has(Z))continue;Q.add(Z),H.push(Z)}return AJ(H)}async function U8(f={}){let $=O1(f);if($.length===0)return{extensions:[],failures:[],warnings:[]};if(f.mode==="in_process"){let W=await $$($,{cwd:f.cwd,exportName:f.exportName,providerId:f.providerId,modelId:f.modelId,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,automation:f.automation,logger:f.logger,telemetry:f.telemetry});return{extensions:W.plugins,failures:W.failures,warnings:W.warnings}}let J=await AQ({pluginPaths:$,exportName:f.exportName,importTimeoutMs:f.importTimeoutMs,hookTimeoutMs:f.hookTimeoutMs,contributionTimeoutMs:f.contributionTimeoutMs,onEvent:f.onEvent,providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,session:f.session,client:f.client,user:f.user,workspaceInfo:f.workspaceInfo,logger:f.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,warnings:J.warnings}}W0();function YR(f,$){if(!f.setup)return[];let J=[],W={registerTool:(H)=>J.push(H),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return f.setup(W,{workspaceInfo:$}),J}async function MJ(f){let $=O1({workspacePath:f.workspacePath,cwd:f.cwd}),J=rf(f.disabledToolNames),W=[];for(let H of $){let Q=await $$([H],{cwd:f.cwd,providerId:f.providerId,modelId:f.modelId});for(let Z of Q.plugins)for(let j of YR(Z,{rootPath:f.workspacePath}))W.push({name:j.name,pluginName:Z.name,path:H,source:H.startsWith(f.workspacePath)?"workspace-plugin":"global-plugin",enabled:!J.has(j.name),description:j.description?.trim()||void 0})}return W.sort((H,Q)=>{let Z=H.name.localeCompare(Q.name);if(Z!==0)return Z;return H.path.localeCompare(Q.path)})}function hJ(f,$){if(!$)return"global";let J=RR($,f);return!J.startsWith("..")&&!VR(J)?"workspace":"global"}function G8(f){return[...f].sort(($,J)=>{let W=(H)=>{switch(H){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if($.source!==J.source)return W($.source)-W(J.source);return $.name.localeCompare(J.name)})}function YQ(f){return f.workspaceRoot?.trim()||f.cwd?.trim()||""}async function BQ(f,$){if(f.userInstructionService)return await $(f.userInstructionService);let J=YQ(f);if(!J)return await $(void 0);let W=m$({skills:{workspacePath:J},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await W.start(),await $(W)}finally{W.stop()}}function FR(f,$){if(!f)return;let J=f.listRecords("skill");if($.id){let W=J.find((H)=>H.id===$.id);if(W)return W}for(let W of J)if(W.filePath===$.path||W.item.name===$.name||W.id===$.name)return W;return}class c${async list(f={}){return await BQ(f,async($)=>{let J=YQ(f),W=[],H=[],Q=[],Z=[];if($){for(let j of $.listRecords("workflow")){let X=j.item;W.push({id:j.id,name:X.name,path:j.filePath,enabled:X.disabled!==!0,kind:"workflow",source:hJ(j.filePath,J),description:X.instructions,toggleable:!1})}for(let j of $.listRecords("rule")){let X=j.item;H.push({id:j.id,name:X.name,path:j.filePath,enabled:X.disabled!==!0,kind:"rule",source:hJ(j.filePath,J),description:X.instructions,toggleable:!1})}for(let j of $.listRecords("skill")){let X=j.item;Q.push({id:j.id,name:X.name,path:j.filePath,enabled:X.disabled!==!0,kind:"skill",source:hJ(j.filePath,J),description:X.description,toggleable:!0})}}if(J)try{for(let j of await MJ({workspacePath:J,cwd:f.cwd,providerId:f.availabilityContext?.providerId,modelId:f.availabilityContext?.modelId}))Z.push({id:`${j.pluginName}:${j.name}:${j.path}`,name:j.name,path:j.path,enabled:j.enabled,kind:"tool",source:j.source,description:j.description,toggleable:!0})}catch{}return{workflows:G8(W.filter((j)=>LJ(j.path))),rules:G8(H.filter((j)=>LJ(j.path))),skills:G8(Q.filter((j)=>LJ(j.path))),tools:G8(Z)}})}async toggle(f){if(f.type==="skills")return await BQ(f,async($)=>{let J=FR($,f),W=J?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${f.id??f.name??PQ(f.path??"")}'.`);let H=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,Q=f.enabled??(H!==void 0?!H:void 0);if(Q===void 0)throw Error(`Cannot determine toggle state for skill '${f.id??f.name??PQ(f.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await g3({filePath:W,enabled:Q}),await $?.refreshType("skill"),{snapshot:await this.list({...f,userInstructionService:$}),changedTypes:["skills"]}});if(f.type==="tools"){if(!f.name?.trim())throw Error("Tool settings toggle requires a tool name.");if(f.enabled===void 0)XJ(f.name);else r3(f.name,!f.enabled);return{snapshot:await this.list(f),changedTypes:["tools"]}}throw Error(`Settings type '${f.type}' does not support toggles.`)}}function z1(){return new c$}function VQ(f){return{async list($){let J=f;if(J.listSettings)return await J.listSettings($);return await z1().list($)},async toggle($){let J=f;if(J.toggleSetting)return await J.toggleSetting($);return await z1().toggle($)}}}function RQ(f){function $(){let J=f.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return $().list(J)},update(J){return $().update(J)},delete(J){return $().delete(J)}}}function Ff(...f){let $,J;for(let H of f){if(!H)continue;if(H.toolExecutors)$={...$??{},...H.toolExecutors};if(H.requestToolApproval)J=H.requestToolApproval}let W=$&&Object.keys($).length>0;if(!W&&!J)return;return{...W?{toolExecutors:$}:{},...J?{requestToolApproval:J}:{}}}function OJ(f){let{hooks:$,logger:J,telemetry:W,extensionContext:H,extraTools:Q,extensions:Z,onTeamEvent:j,onConsecutiveMistakeLimitReached:X,checkpoint:A,compaction:P,...B}=f,Y={};if($)Y.hooks=$;if(J)Y.logger=J;if(W)Y.telemetry=W;if(H)Y.extensionContext=H;if(Q)Y.extraTools=Q;if(Z)Y.extensions=Z;if(j)Y.onTeamEvent=j;if(X)Y.onConsecutiveMistakeLimitReached=X;if(A?.createCheckpoint)Y.checkpoint=A;if(P?.compact)Y.compaction=P;let V=Object.keys(Y).length>0?Y:void 0;return{config:{...B,...A?{checkpoint:{enabled:A.enabled}}:{},...P?{compaction:{enabled:P.enabled,strategy:P.strategy,thresholdRatio:P.thresholdRatio,reserveTokens:P.reserveTokens,preserveRecentTokens:P.preserveRecentTokens,contextWindowTokens:P.contextWindowTokens,summarizer:P.summarizer}}:{}},...V?{localRuntime:V}:{}}}function FQ(f){let $=f.config;return"providerId"in $?{...f,config:{...$,...KR(f.localRuntime)},localRuntime:f.localRuntime}:f}function zJ(f,$={}){let J=OJ(f.config),W=Ff($.defaultCapabilities,f.capabilities),H=yR(J.localRuntime,f.localRuntime),Q=$.withExtensionContext?.(H?.extensionContext);if(Q)H={...H??{},extensionContext:Q};return{...f,...J,...H?{localRuntime:H}:{},...W?{capabilities:W}:{}}}function KR(f){if(!f)return{};let{modelCatalogDefaults:$,userInstructionService:J,configExtensions:W,onTeamRestored:H,...Q}=f;return Q}function yR(...f){let $={};for(let J of f)if(J)Object.assign($,J);return Object.keys($).length>0?$:void 0}Uf();function KQ(f){let $=f.input.config.telemetry??f.telemetry;if(!$)return;$.capture({event:x.SESSION.STARTED,properties:{sessionId:f.sessionId,source:f.input.source??Rf.CORE,providerId:f.input.config.providerId,modelId:f.input.config.modelId,enableTools:f.input.config.enableTools,enableSpawnAgent:f.input.config.enableSpawnAgent,enableAgentTeams:f.input.config.enableAgentTeams,clientName:f.clientName,runtimeAddress:f.runtimeAddress}})}function N1(f){return!!f&&typeof f==="object"&&!Array.isArray(f)}function NJ(f){let $=f?.trim();return $?$:void 0}function UR(f,$){let J=f?.trim();if(!J)return $;let W=Date.parse(J);if(!Number.isFinite(W))return $;return new Date(W).toISOString()}function yQ(f,$){return new Date(new Date(f).getTime()+Math.max(0,Math.floor($))*1000).toISOString()}function UQ(f,$){return new Date(new Date(f).getTime()-Math.max(0,Math.floor($))*1000).toISOString()}function GR(f,$){if(!f)return $;return new Date(f).getTime()>=new Date($).getTime()?f:$}function TR(f,$){let J=f.eventId.trim(),W=f.eventType.trim(),H=f.source.trim(),Q=NJ(f.subject),Z=NJ(f.dedupeKey)??`${W}:${H}:${Q??J}`;return{eventId:J,eventType:W,source:H,subject:Q,occurredAt:UR(f.occurredAt,$),workspaceRoot:NJ(f.workspaceRoot),payload:N1(f.payload)?f.payload:void 0,attributes:N1(f.attributes)?f.attributes:void 0,dedupeKey:Z}}function qJ(f,$){if(!$)return;let J=$.split("."),W=f;for(let H of J){if(!N1(W))return;W=W[H]}return W}function DR(f,$){if(f.attributes&&Object.hasOwn(f.attributes,$))return f.attributes[$];if(f.payload&&Object.hasOwn(f.payload,$))return f.payload[$];let J={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload},W=qJ(J,$);if(W!==void 0)return W;if(f.attributes){let H=qJ(f.attributes,$);if(H!==void 0)return H}if(f.payload)return qJ(f.payload,$);return}function T8(f,$){if(Array.isArray($))return $.some((J)=>T8(f,J));if(Array.isArray(f))return f.some((J)=>T8(J,$));if(N1($)){if(!N1(f))return!1;return Object.entries($).every(([J,W])=>T8(f[J],W))}return Object.is(f,$)}function _R(f,$){if(!$||Object.keys($).length===0)return!0;return Object.entries($).every(([J,W])=>T8(DR(f,J),W))}class wJ{store;nowFn;logger;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now()),this.logger=f.logger}ingestEvent(f){let $=new Date(this.nowFn()).toISOString(),J=TR(f,$),W=this.store.insertEventLog(J,{receivedAtIso:$});if(!W.created)return this.logger?.debug("cron.event.duplicate",{eventId:W.record.eventId,eventType:W.record.eventType,source:W.record.source}),{event:W.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:W.record.dedupeKey}]};try{let H=this.store.listEventSpecsForType(J.eventType),Q=[],Z=[],j=[];for(let P of H){if(!_R(J,P.filters)){Q.push({specId:P.specId,externalId:P.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}Z.push(P);let B=this.materializeForSpec(P,J,W.record.receivedAt);if(B.run)j.push(B.run);else Q.push({specId:P.specId,externalId:P.externalId,reason:B.reason,dedupeKey:J.dedupeKey})}let X=Z.length===0?"unmatched":j.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(W.record.eventId,{status:X,matchedSpecCount:Z.length,queuedRunCount:j.length,suppressedCount:Q.filter((P)=>P.reason!=="filter_mismatch").length});let A=this.store.getEventLog(W.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:W.record.eventId,eventType:W.record.eventType,status:X,matchedSpecCount:Z.length,queuedRunCount:j.length}),{event:A??W.record,duplicate:!1,matchedSpecs:Z,queuedRuns:j,suppressions:Q}}catch(H){if(this.store.updateEventLogProcessing(W.record.eventId,{status:"failed",error:H instanceof Error?H.message:String(H)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:W.record.eventId,eventType:W.record.eventType,error:H});throw H}}materializeForSpec(f,$,J){let W=$.dedupeKey??$.eventId,H=f.debounceSeconds??0;if(H>0){let X=this.store.findQueuedEventRunForDedupe({specId:f.specId,dedupeKey:W});if(X){let A=GR(X.scheduledFor,yQ(J,H)),P=this.store.updateQueuedEventRunForDebounce({runId:X.runId,triggerEventId:$.eventId,scheduledFor:A});if(P)return{run:P,reason:"dedupe_window"}}}let Q=f.dedupeWindowSeconds??0;if(Q>0&&this.store.hasRecentEventRunForDedupe({specId:f.specId,dedupeKey:W,sinceIso:UQ(J,Q)}))return{reason:"dedupe_window"};let Z=f.cooldownSeconds??0;if(Z>0&&this.store.hasRecentEventRunForSpec({specId:f.specId,sinceIso:UQ(J,Z)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"event",triggerEventId:$.eventId,scheduledFor:H>0?yQ(J,H):J}),reason:"dedupe_window"}}}class q1{store;nowFn;constructor(f){this.store=f.store,this.nowFn=f.now??(()=>Date.now())}materializeAll(){let f={oneOffQueued:0,scheduleQueued:0},$=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let W of $)if(this.materializeOneOff(W))f.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of J)try{if(this.materializeSchedule(W))f.scheduleQueued+=1}catch{}return f}materializeOneOff(f){if(f.triggerKind!=="one_off")return!1;if(!f.enabled||f.removed)return!1;if(this.store.hasOneOffRunForRevision(f.specId,f.revision))return!1;return this.store.enqueueRun({specId:f.specId,specRevision:f.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule(f){if(f.triggerKind!=="schedule")return!1;if(!f.enabled||f.removed)return!1;if(!f.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:f.specId,nowMs:this.nowFn()}).queued}}import{basename as CR}from"node:path";import{buildClineSystemPrompt as ER}from"@cline/shared";import{nowIso as _Q}from"@cline/shared/db";import{basename as MR,resolve as LR}from"node:path";import{performance as GQ}from"node:perf_hooks";import{processWorkspaceInfo as TQ}from"@cline/shared";import hR from"simple-git";function J$(f){return LR(f)}async function _8(f){return(await bJ(f)).info}function D8(f){if(f instanceof Error)return{errorType:f.name?.trim()||f.constructor.name||"Error",message:f.message};return{errorType:"Error",message:String(f)}}async function bJ(f){let $=J$(f),J={rootPath:$,hint:MR($)},W;try{let H=hR({baseDir:$});if(!await H.checkIsRepo())return{info:J,vcsType:"none"};try{let Z=await H.getRemotes(!0);if(Z.length>0){let j=Z.map((X)=>{let A=X.refs.fetch||X.refs.push;return`${X.name}: ${A}`});J.associatedRemoteUrls=j}}catch(Z){W??=D8(Z)}try{let Z=(await H.revparse(["HEAD"])).trim();if(Z.length>0)J.latestGitCommitHash=Z}catch(Z){W??=D8(Z)}try{let Z=(await H.branch()).current.trim();if(Z.length>0)J.latestGitBranchName=Z}catch(Z){W??=D8(Z)}return{info:J,vcsType:"git",error:W}}catch(H){return{info:J,vcsType:"none",error:D8(H)}}}async function CJ(f){let $=await _8(f);return TQ($)}async function DQ(f){let $=GQ.now(),J=await bJ(f),W=GQ.now()-$,H=J.info;return{workspaceInfo:H,workspaceMetadata:TQ(H),durationMs:W,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as OR,writeFileSync as zR}from"node:fs";import{join as NR}from"node:path";import{resolveCronReportsDir as qR}from"@cline/shared/storage";function h0(f){if(/[:#\n]/.test(f)||f.includes('"'))return JSON.stringify(f);return f}function W$(f,$){if($===void 0||$===null)return;return`${f}: ${h0($)}`}function wR(f,$,J){let W=[`runId: ${h0(f.runId)}`,`specId: ${h0($.specId)}`,`externalId: ${h0($.externalId)}`,`title: ${h0($.title)}`,`triggerKind: ${h0(f.triggerKind)}`,`status: ${h0(f.status)}`,`sourcePath: ${h0($.sourcePath)}`],H=[W$("sessionId",f.sessionId),W$("startedAt",f.startedAt),W$("completedAt",f.completedAt),W$("triggerEventId",f.triggerEventId),W$("triggerEventType",J?.eventType),W$("triggerEventSource",J?.source),W$("triggerEventSubject",J?.subject)];for(let Q of H)if(Q)W.push(Q);return`---
|
|
157
|
+
${W.join(`
|
|
158
158
|
`)}
|
|
159
159
|
---
|
|
160
|
-
`}function
|
|
160
|
+
`}function bR(f){let $=[];if(f.triggerEvent){let J=f.triggerEvent,W=[`- eventId: ${J.eventId}`,`- eventType: ${J.eventType}`,`- source: ${J.source}`,J.subject?`- subject: ${J.subject}`:"",`- occurredAt: ${J.occurredAt}`,J.dedupeKey?`- dedupeKey: ${J.dedupeKey}`:"",J.attributes?`- attributes: ${JSON.stringify(J.attributes)}`:""].filter((H)=>H.length>0);$.push(`## Trigger Event
|
|
161
161
|
|
|
162
|
-
${
|
|
162
|
+
${W.join(`
|
|
163
163
|
`)}
|
|
164
164
|
`)}if(f.error)$.push(`## Error
|
|
165
165
|
|
|
@@ -167,26 +167,26 @@ ${f.error}
|
|
|
167
167
|
`);if(f.finalText&&f.finalText.trim().length>0)$.push(`## Summary
|
|
168
168
|
|
|
169
169
|
${f.finalText.trim()}
|
|
170
|
-
`);if(f.usage){let J=f.usage,
|
|
170
|
+
`);if(f.usage){let J=f.usage,W=[J.inputTokens!==void 0?`- inputTokens: ${J.inputTokens}`:"",J.outputTokens!==void 0?`- outputTokens: ${J.outputTokens}`:"",J.cacheReadTokens!==void 0?`- cacheReadTokens: ${J.cacheReadTokens}`:"",J.cacheWriteTokens!==void 0?`- cacheWriteTokens: ${J.cacheWriteTokens}`:"",J.totalCost!==void 0?`- totalCostUsd: ${J.totalCost}`:"",f.durationMs!==void 0?`- durationMs: ${f.durationMs}`:""].filter((H)=>H.length>0);if(W.length>0)$.push(`## Usage
|
|
171
171
|
|
|
172
|
-
${
|
|
172
|
+
${W.join(`
|
|
173
173
|
`)}
|
|
174
|
-
`)}if(f.toolCalls&&f.toolCalls.length>0){let J=f.toolCalls.map((
|
|
174
|
+
`)}if(f.toolCalls&&f.toolCalls.length>0){let J=f.toolCalls.map((W)=>{let H=[`- ${W.name}`];if(W.durationMs!==void 0)H.push(`(${W.durationMs}ms)`);if(W.error)H.push(`error: ${W.error}`);return H.join(" ")});$.push(`## Tool Calls
|
|
175
175
|
|
|
176
176
|
${J.join(`
|
|
177
177
|
`)}
|
|
178
178
|
`)}return $.join(`
|
|
179
|
-
`)}function
|
|
180
|
-
${
|
|
181
|
-
`)}class
|
|
179
|
+
`)}function EJ(f){let $=qR(f.specs);OR($,{recursive:!0});let J=NR($,`${f.run.runId}.md`),W=`${wR(f.run,f.spec,f.data.triggerEvent)}
|
|
180
|
+
${bR(f.data)}`;return zR(J,W,"utf8"),J}class SJ{globalMaxConcurrency;activeExecutions=new Map;constructor(f){this.globalMaxConcurrency=Math.max(1,Math.floor(f))}acquire(f,$,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let W=Math.max(1,Math.floor(J)),H=this.activeExecutions.get(f)??new Set;if(H.size>=W)return!1;return H.add($),this.activeExecutions.set(f,H),!0}release(f,$){let J=this.activeExecutions.get(f);if(!J)return;if(J.delete($),J.size===0)this.activeExecutions.delete(f)}getGlobalActiveCount(){let f=0;for(let $ of this.activeExecutions.values())f+=$.size;return f}}var SR=15000,kR=90,MQ=["rules","skills","plugins"];function IR(f,$){return new Set(f.extensions??MQ).has($)}function mR(f,$){if(f.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let W of f.tools)J[W]={enabled:!0,autoApprove:!0};if($==="yolo")J[Hf.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function xR(f){let $=f?.trim();if(!$)return;return["# Notes Directory",`Use ${$} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
|
|
181
|
+
`)}class kJ extends Error{constructor(f){super(f);this.name="TimeoutError"}}async function gR(f,$){if($<=0)return f;let J,W=new Promise((H,Q)=>{J=setTimeout(()=>{Q(new kJ("cron run timed out"))},$)});try{return await Promise.race([f,W])}finally{if(J)clearTimeout(J)}}class w1{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor(f){this.store=f.store,this.materializer=f.materializer,this.options=f,this.limiter=new SJ(f.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,(f.claimLeaseSeconds??kR)*1000)}async start(){if(this.disposed)throw Error("CronRunner disposed");if(this.started)return;this.stopping=!1,this.started=!0;let f=Math.max(2000,this.options.pollIntervalMs??SR);await this.tick(),this.timer=setInterval(()=>void this.tick(),f)}async stop(){let f=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!f)return;let $=[...this.activeRuns.entries()];await Promise.all($.map(async([J,W])=>{if(W.sessionId)try{await this.options.runtimeHandlers.abortSession(W.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:W.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let f=this.store.claimDueRuns({nowIso:_Q(),leaseMs:this.claimLeaseMs});await Promise.allSettled(f.map(($)=>this.executeClaim($)))}catch(f){let $=this.options.logger;if($)if($.error)$.error("cron.runner.tick.failed",{error:f});else $.log("cron.runner.tick.failed",{error:f})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([f,$])=>{let J=this.store.getRun(f);return J?[{...J,...$}]:[]})}async executeClaim(f){let $=f.run,J=this.store.getSpec($.specId);if(!J){this.store.completeRun($.runId,{status:"failed",error:"spec not found",claimToken:f.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun($.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:f.claimToken});return}let W=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,$.runId,W)){this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,$.runId),this.store.requeueRun({runId:$.runId,claimToken:f.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set($.runId,{claimToken:f.claimToken});let Q=$.triggerEventId?this.store.getEventLog($.triggerEventId):void 0,Z,j,X=Date.now(),A;if(J.timeoutSeconds&&J.timeoutSeconds>0)A=X+J.timeoutSeconds*1000;try{j=this.startClaimLeaseHeartbeat(f);let P=await this.buildStartRequest(J);if(Z=(await this.options.runtimeHandlers.startSession(P)).sessionId.trim(),!Z)throw Error("runtime returned empty sessionId");this.activeRuns.set($.runId,{claimToken:f.claimToken,sessionId:Z}),this.store.attachSessionIdToRun($.runId,Z);let Y={config:P,prompt:this.buildPrompt(J,Q)},V=this.options.runtimeHandlers.sendSession(Z,Y),R=A?Math.max(1,A-Date.now()):0,K=(await gR(V,R)).result,F=Date.now(),y=EJ({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:Z,status:"done"},spec:J,data:{finalText:K.text,usage:K.usage,toolCalls:K.toolCalls,durationMs:F-X,triggerEvent:Q}});this.store.completeRun($.runId,{status:"done",sessionId:Z,reportPath:y,claimToken:f.claimToken}),this.store.updateSpecLastRunAt(J.specId,_Q())}catch(P){let B=P instanceof kJ;if(Z&&B)try{await this.options.runtimeHandlers.abortSession(Z)}catch{}let Y=P instanceof Error?P.message:String(P),V=Date.now(),R=EJ({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...$,sessionId:Z,status:"failed"},spec:J,data:{error:Y,durationMs:V-X,triggerEvent:Q}});this.store.completeRun($.runId,{status:"failed",sessionId:Z,reportPath:R,error:Y,claimToken:f.claimToken})}finally{if(j?.(),Z)try{await this.options.runtimeHandlers.stopSession(Z)}catch{}this.activeRuns.delete($.runId),this.limiter.release(J.specId,$.runId)}}buildPrompt(f,$){let J=f.prompt??"";if(!$)return J;let W={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload};return`${J}
|
|
182
182
|
|
|
183
183
|
Trigger event:
|
|
184
|
-
${JSON.stringify(
|
|
184
|
+
${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let W=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim(f.run.runId,f.claimToken,W))clearInterval(J)},$);return()=>clearInterval(J)}async buildSystemPrompt(f,$,J,W){let H=xR(f.notesDirectory),Q=g2(void 0,H),Z=await CJ($),j=ER({ide:"Cline Cron",workspaceRoot:$,workspaceName:CR($),metadata:Z,rules:f.systemPrompt?void 0:Q,mode:J,providerId:W,overridePrompt:f.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return f.systemPrompt?g2(j,Q)??j:j}async buildStartRequest(f){let $=(f.workspaceRoot??"").trim(),J=(f.providerId??"").trim(),W=(f.modelId??"").trim(),H=f.metadata?.__hubRuntimeOptions&&typeof f.metadata.__hubRuntimeOptions==="object"&&!Array.isArray(f.metadata.__hubRuntimeOptions)?f.metadata.__hubRuntimeOptions:void 0,Q=typeof f.metadata?.__hubScheduleCwd==="string"&&f.metadata.__hubScheduleCwd.trim()?f.metadata.__hubScheduleCwd.trim():$;if(!$)throw Error("cron spec requires workspaceRoot");let Z=f.mode==="plan"?"plan":f.mode==="act"?"act":"yolo";return{workspaceRoot:$,cwd:Q,provider:J,model:W,mode:Z,source:f.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt(f,$,Z,J),maxIterations:f.maxIterations,enableTools:H?.enableTools??!0,enableSpawn:H?.enableSpawn??!0,enableTeams:H?.enableTeams??!0,autoApproveTools:H?.autoApproveTools??!0,toolPolicies:mR(f,Z),configExtensions:MQ.filter((j)=>IR(f,j))}}}import{existsSync as XF,readdirSync as AF,readFileSync as PF,statSync as BF}from"node:fs";import{relative as YF}from"node:path";import{resolveCronSpecsDir as VF}from"@cline/shared/storage";function b1(f,$,J,W){let H=new Set;function Q(Z){let j=Z.toLowerCase();if(W){let A=W.indexOf(j);if(A!==-1)return A+$}let X=Number(Z);if(!Number.isInteger(X)||X<$||X>J)throw Error(`Invalid cron value "${Z}" for range [${$}-${J}]`);return X}for(let Z of f.split(",")){if(Z==="*"){for(let A=$;A<=J;A+=1)H.add(A);continue}let j=Z.indexOf("/");if(j!==-1){let A=Z.slice(0,j),P=Number(Z.slice(j+1));if(!Number.isInteger(P)||P<1)throw Error(`Invalid step "${Z.slice(j+1)}"`);let B=$,Y=J;if(A!=="*"){let V=A.indexOf("-");if(V!==-1)B=Q(A.slice(0,V)),Y=Q(A.slice(V+1));else B=Q(A)}if(B>Y)throw Error(`Invalid cron range "${A}"`);for(let V=B;V<=Y;V+=P)H.add(V);continue}let X=Z.indexOf("-");if(X!==-1){let A=Q(Z.slice(0,X)),P=Q(Z.slice(X+1));if(A>P)throw Error(`Invalid cron range "${Z}"`);for(let B=A;B<=P;B+=1)H.add(B);continue}H.add(Q(Z))}return[...H].sort((Z,j)=>Z-j)}var vR=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],hQ=["sun","mon","tue","wed","thu","fri","sat"];function C1(f,$,J){let W=f[$];if(typeof W!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${$+1}`);return W}function IJ(f,$){let J=f[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${$}`);return J}function mJ(f){let $=f.trim().split(/\s+/);if($.length!==5)throw Error(`Invalid cron pattern "${f}": expected 5 fields, got ${$.length}`);return{minutes:b1(C1($,0,f),0,59),hours:b1(C1($,1,f),0,23),daysOfMonth:b1(C1($,2,f),1,31),months:b1(C1($,3,f),1,12,vR),daysOfWeek:b1(C1($,4,f),0,6,hQ)}}function xJ(f){mJ(f)}function OQ(f,$,J=Date.now()){H$(f,J,$)}var LQ=new Map,uR=new Map(hQ.map((f,$)=>[f,$]));function zQ(f){let $=f?.trim();return $?$:void 0}function NQ(f){let $=LQ.get(f);if($)return $;let J=new Intl.DateTimeFormat("en-US",{timeZone:f,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return LQ.set(f,J),J}function cR(f){let $=zQ(f);if(!$)return;NQ($).format(new Date)}function dR(f,$){let J=NQ($).formatToParts(new Date(f)),W=new Map(J.map((Z)=>[Z.type,Z.value])),H=W.get("weekday")?.toLowerCase().slice(0,3)??"",Q=uR.get(H);if(Q===void 0)throw Error(`Unable to resolve weekday for timezone "${$}"`);return{month:Number(W.get("month")),dayOfMonth:Number(W.get("day")),dayOfWeek:Q,hour:Number(W.get("hour")),minute:Number(W.get("minute"))}}function rR(f){let $=new Date(f);return{month:$.getMonth()+1,dayOfMonth:$.getDate(),dayOfWeek:$.getDay(),hour:$.getHours(),minute:$.getMinutes()}}function lR(f,$){return f.months.includes($.month)&&f.daysOfMonth.includes($.dayOfMonth)&&f.daysOfWeek.includes($.dayOfWeek)&&f.hours.includes($.hour)&&f.minutes.includes($.minute)}function pR(f,$,J){let W=mJ(f),H=new Date($);H.setSeconds(0,0);let Q=H.getTime()+60000,Z=new Date($);Z.setFullYear(Z.getFullYear()+4);let j=Z.getTime();while(Q<=j){if(lR(W,dR(Q,J)))return Q;Q+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${f}" in timezone "${J}"`)}function H$(f,$,J){let W=zQ(J);if(W)return cR(W),pR(f,$,W);let H=mJ(f),Q=new Date($);Q.setSeconds(0,0),Q=new Date(Q.getTime()+60000);let Z=new Date($);Z.setFullYear(Z.getFullYear()+4);while(Q<=Z){let{month:j,dayOfMonth:X,dayOfWeek:A,hour:P,minute:B}=rR(Q.getTime());if(!H.months.includes(j)){let Y=H.months.find((R)=>R>j)??IJ(H.months,"months"),V=Y<=j?1:0;Q=new Date(Q.getFullYear()+V,Y-1,1,0,0,0,0);continue}if(!H.daysOfMonth.includes(X)||!H.daysOfWeek.includes(A)){Q=new Date(Q.getFullYear(),Q.getMonth(),X+1,0,0,0,0);continue}if(!H.hours.includes(P)){let Y=H.hours.find((R)=>R>P)??IJ(H.hours,"hours"),V=Y<=P?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()+V,Y,0,0,0);continue}if(!H.minutes.includes(B)){let Y=H.minutes.find((R)=>R>B)??IJ(H.minutes,"minutes"),V=Y<=B?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate(),Q.getHours()+V,Y,0,0);continue}return Q.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${f}"`)}import{createHash as iR}from"node:crypto";import nR from"yaml";function aR(f){let $=f.replace(/\\/g,"/");if($.startsWith("events/")&&$.endsWith(".event.md"))return"event";if($.endsWith(".cron.md"))return"schedule";return"one_off"}function tR(f){let $=f.replace(/\r\n/g,`
|
|
185
185
|
`);if(!$.startsWith(`---
|
|
186
|
-
`))return{frontmatter:void 0,body:f};let J=$.slice(4),
|
|
187
|
-
---`);if(
|
|
188
|
-
`))Q=Q.slice(1);return{frontmatter:
|
|
189
|
-
`),J.update($),J.digest("hex")}function
|
|
186
|
+
`))return{frontmatter:void 0,body:f};let J=$.slice(4),W=J.indexOf(`
|
|
187
|
+
---`);if(W===-1)return{frontmatter:void 0,body:f};let H=J.slice(0,W),Q=J.slice(W+4);if(Q.startsWith(`
|
|
188
|
+
`))Q=Q.slice(1);return{frontmatter:H,body:Q}}function qf(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function sR(f){if(!Array.isArray(f))return;let $=f.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return $.length>0?$:void 0}function uJ(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return f}function oR(f){let $=uJ(f);if(!$)return;let J=qf($.providerId),W=qf($.modelId);if(J===void 0&&W===void 0)return;return{providerId:J,modelId:W}}function eR(f){if(typeof f!=="string")return;let $=f.trim().toLowerCase();if($==="act"||$==="plan"||$==="yolo")return $;return}function wQ(f,$={}){let J=Array.isArray(f)?f:typeof f==="string"?f.split(","):void 0;if(!J)return;let W=[...new Set(J.map((H)=>typeof H==="string"?H.trim():"").filter((H)=>H.length>0))];if(Array.isArray(f)&&$.preserveEmptyArray)return W;return W.length>0?W:void 0}var fF=new Set(b$);function $F(f){let $=wQ(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((W)=>!fF.has(W));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return $}var JF=new Set(["rules","skills","plugins"]);function WF(f){let $=wQ(f,{preserveEmptyArray:!0});if(!$)return;let J=$.filter((W)=>!JF.has(W));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return $}function gJ(f){if(typeof f!=="number"||!Number.isFinite(f)||f<=0)return;return Math.floor(f)}function vJ(f){if(typeof f!=="number"||!Number.isFinite(f)||f<0)return;return Math.floor(f)}function cJ(f){if(f===null||typeof f!=="object")return JSON.stringify(f??null);if(Array.isArray(f))return`[${f.map((J)=>cJ(J)).join(",")}]`;let $=Object.entries(f).filter(([,J])=>J!==void 0);return $.sort(([J],[W])=>J<W?-1:J>W?1:0),`{${$.map(([J,W])=>`${JSON.stringify(J)}:${cJ(W)}`).join(",")}}`}function bQ(f,$){let J=iR("sha256");return J.update(cJ(f)),J.update(`
|
|
189
|
+
`),J.update($),J.digest("hex")}function HF(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var QF=["schedule","timezone"],ZF=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],jF=["cwd"];function qQ(f,$,J,W,H){return{externalId:f,relativePath:f,triggerKind:$,body:J,contentHash:bQ(W,J),error:H}}function lf(f,$,J,W,H,Q){return{externalId:f,relativePath:$,triggerKind:J,body:W,contentHash:H,error:Q}}function CQ(f){let $=f.relativePath.replace(/\\/g,"/"),J=aR($),{frontmatter:W,body:H}=tR(f.raw),Q={};if(W!==void 0&&W.trim().length>0)try{let y=nR.parse(W);if(y&&typeof y==="object"&&!Array.isArray(y))Q=y;else if(y!==null&&y!==void 0)return qQ($,J,H,{},"frontmatter must be a YAML mapping")}catch(y){return qQ($,J,H,{},y instanceof Error?`failed to parse frontmatter: ${y.message}`:"failed to parse frontmatter")}let Z=bQ(Q,H),j=qf(Q.id),X=j??$;if(J!=="schedule"){for(let y of QF)if(Q[y]!==void 0)return lf(X,$,J,H,Z,`field "${y}" is only allowed on *.cron.md specs`)}for(let y of jF)if(Q[y]!==void 0)return lf(X,$,J,H,Z,`field "${y}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let y of ZF)if(Q[y]!==void 0)return lf(X,$,J,H,Z,`field "${y}" is only allowed on .event.md specs`)}let A=qf(Q.prompt),P=H.trim(),B=A??(P.length>0?P:void 0);if(!B)return lf(X,$,J,H,Z,"prompt is required (frontmatter `prompt` or markdown body)");let Y=qf(Q.workspaceRoot);if(!Y)return lf(X,$,J,H,Z,"workspaceRoot is required");let V,R;try{V=$F(Q.tools),R=WF(Q.extensions)}catch(y){return lf(X,$,J,H,Z,y instanceof Error?y.message:String(y))}let U=eR(Q.mode);if(Q.mode!==void 0&&U===void 0)return lf(X,$,J,H,Z,"mode must be one of: act, plan, yolo");let K={id:j,title:qf(Q.title)??j??HF($),prompt:B,workspaceRoot:Y,mode:U??"yolo",systemPrompt:qf(Q.systemPrompt),modelSelection:oR(Q.modelSelection),maxIterations:gJ(Q.maxIterations),timeoutSeconds:gJ(Q.timeoutSeconds),tools:V,notesDirectory:qf(Q.notesDirectory),extensions:R,source:qf(Q.source)??"user",tags:sR(Q.tags),enabled:typeof Q.enabled==="boolean"?Q.enabled:!0,metadata:uJ(Q.metadata)},F;if(J==="schedule"){let y=qf(Q.schedule);if(!y)return lf(X,$,J,H,Z,"schedule is required for *.cron.md specs");let D=qf(Q.timezone);try{OQ(y,D)}catch(T){return lf(X,$,J,H,Z,T instanceof Error?T.message:String(T))}F={...K,triggerKind:"schedule",schedule:y,timezone:D}}else if(J==="event"){let y=qf(Q.event);if(!y)return lf(X,$,J,H,Z,"event is required for .event.md specs");F={...K,triggerKind:"event",event:y,filters:uJ(Q.filters),debounceSeconds:vJ(Q.debounceSeconds),dedupeWindowSeconds:vJ(Q.dedupeWindowSeconds),cooldownSeconds:vJ(Q.cooldownSeconds),maxParallel:gJ(Q.maxParallel)}}else F={...K,triggerKind:"one_off"};return{externalId:X,relativePath:$,triggerKind:J,body:H,contentHash:Z,spec:F}}function RF(f,$){return YF(f,$).replace(/\\/g,"/")}function FF(f){if(!XF(f))return[];let $=[],J=[f];while(J.length>0){let W=J.pop();if(!W)continue;let H;try{H=AF(W,{withFileTypes:!0})}catch{continue}for(let Q of H){let Z=`${W}/${Q.name}`;if(Q.isDirectory()){if(Q.name==="reports")continue;J.push(Z);continue}if(!Q.isFile())continue;if(!Q.name.endsWith(".md"))continue;$.push(Z)}}return $}class dJ{store;cronDir;constructor(f){this.store=f.store,this.cronDir=VF(f.specs??(f.workspaceRoot?{scope:"workspace",workspaceRoot:f.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let f={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},$=FF(this.cronDir),J=new Set;for(let H of $){let Q=RF(this.cronDir,H);J.add(Q),f.scanned+=1;let Z=await this.reconcileFile(Q,H);if(Z){if(f.changes.push(Z),f.upserted+=1,Z.parse.error)f.invalidParses+=1}}let W=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let H of W)if(!J.has(H.sourcePath))this.handleFileDeleted(H),f.removed+=1;return this.refreshScheduleNextRunAt(),f}async reconcileFile(f,$){let J=this.store.getSpecBySourcePath(f),W,H;try{W=PF($,"utf8"),H=BF($).mtimeMs}catch{return}let Z=CQ({relativePath:f,raw:W}),j=this.store.upsertSpec({externalId:Z.externalId,sourcePath:f,triggerKind:Z.triggerKind,sourceMtimeMs:H,sourceHash:Z.contentHash,parseStatus:Z.error?"invalid":"valid",parseError:Z.error,spec:Z.spec});if(!Z.error&&Z.triggerKind==="schedule"&&j.record.enabled)this.applyScheduleNextRunAt(j.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==j.record.scheduleExpr||J.timezone!==j.record.timezone});return{relativePath:f,result:j,parse:Z}}handleFileDeleted(f){this.store.markSpecRemoved(f.specId),this.store.cancelQueuedRunsForSpec(f.specId)}refreshScheduleNextRunAt(){let f=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let $ of f)this.applyScheduleNextRunAt($,{forceReset:!1})}applyScheduleNextRunAt(f,$){if(!f.scheduleExpr)return;if(!$.forceReset&&f.nextRunAt)return;try{let J=Date.now(),W=f.lastRunAt?Math.max(J,new Date(f.lastRunAt).getTime()):J,H=H$(f.scheduleExpr,W,f.timezone),Q=new Date(H).toISOString();if(f.nextRunAt!==Q)this.store.updateSpecNextRunAt(f.specId,Q)}catch{}}}import{existsSync as KF,mkdirSync as yF,watch as UF}from"node:fs";import{relative as GF,resolve as TF}from"node:path";var DF=250;class rJ{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor(f){this.reconciler=f.reconciler,this.debounceMs=Math.max(0,f.debounceMs??DF),this.onError=f.onError??(()=>{}),this.onReconciled=f.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let f=this.reconciler.getCronDir();try{yF(f,{recursive:!0}),this.watcher=UF(f,{recursive:!0},($,J)=>{if(!J)return;let W=String(J).replace(/\\/g,"/");if(!W.endsWith(".md"))return;if(W.startsWith("reports/"))return;this.scheduleReconcile(W)}),this.watcher.on("error",this.onError)}catch($){this.onError($)}}stop(){for(let f of this.pending.values())clearTimeout(f);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile(f){let $=this.pending.get(f);if($)clearTimeout($);let J=setTimeout(()=>{this.pending.delete(f),this.reconcileNow(f)},this.debounceMs);this.pending.set(f,J)}async reconcileNow(f){try{let $=TF(this.reconciler.getCronDir(),f);if(!KF($)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=GF(this.reconciler.getCronDir(),$).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,$),await this.onReconciled()}catch($){this.onError($)}}}import{randomUUID as E1}from"node:crypto";import{asOptionalString as C,asString as p,loadSqliteDb as MF,nowIso as jf}from"@cline/shared/db";import{resolveCronDbPath as LF}from"@cline/shared/storage";var _F=[`CREATE TABLE IF NOT EXISTS cron_specs (
|
|
190
190
|
spec_id TEXT PRIMARY KEY,
|
|
191
191
|
external_id TEXT NOT NULL,
|
|
192
192
|
source_path TEXT NOT NULL UNIQUE,
|
|
@@ -277,17 +277,17 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
277
277
|
ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
|
|
278
278
|
ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
|
|
279
279
|
ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
|
|
280
|
-
ON cron_specs(source_path);`];function
|
|
280
|
+
ON cron_specs(source_path);`];function EQ(f){f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec("PRAGMA foreign_keys = ON;");for(let $ of _F)f.exec($)}function M8(f){if(!f)return;try{let $=JSON.parse(f);if($&&typeof $==="object"&&!Array.isArray($))return $}catch{}return}function lJ(f,$={}){if(!f)return;try{let J=JSON.parse(f);if(!Array.isArray(J))return;let W=J.map((H)=>typeof H==="string"?H.trim():"").filter((H)=>H.length>0);if($.preserveEmpty)return W;return W.length>0?W:void 0}catch{return}}function Q$(f){if(typeof f==="number"&&Number.isFinite(f))return f;if(typeof f==="bigint")return Number(f);return}function O0(f){return{specId:p(f.spec_id),externalId:p(f.external_id),sourcePath:p(f.source_path),triggerKind:p(f.trigger_kind),sourceMtimeMs:Q$(f.source_mtime_ms),sourceHash:C(f.source_hash),parseStatus:p(f.parse_status)==="invalid"?"invalid":"valid",parseError:C(f.parse_error),enabled:Number(f.enabled??0)===1,removed:Number(f.removed??0)===1,title:p(f.title),prompt:C(f.prompt),workspaceRoot:C(f.workspace_root),scheduleExpr:C(f.schedule_expr),timezone:C(f.timezone),eventType:C(f.event_type),filters:M8(C(f.filters_json)),debounceSeconds:Q$(f.debounce_seconds),dedupeWindowSeconds:Q$(f.dedupe_window_seconds),cooldownSeconds:Q$(f.cooldown_seconds),mode:C(f.mode),systemPrompt:C(f.system_prompt),providerId:C(f.provider_id),modelId:C(f.model_id),maxIterations:Q$(f.max_iterations),timeoutSeconds:Q$(f.timeout_seconds),maxParallel:Q$(f.max_parallel),tools:lJ(C(f.tools_json),{preserveEmpty:!0}),notesDirectory:C(f.notes_directory),extensions:lJ(C(f.extensions_json),{preserveEmpty:!0}),source:C(f.source),tags:lJ(C(f.tags_json)),metadata:M8(C(f.metadata_json)),revision:Number(f.revision??1),lastMaterializedRunId:C(f.last_materialized_run_id),lastRunAt:C(f.last_run_at),nextRunAt:C(f.next_run_at),createdAt:p(f.created_at),updatedAt:p(f.updated_at)}}function pJ(f){return{runId:p(f.run_id),specId:p(f.spec_id),specRevision:Number(f.spec_revision??1),triggerKind:p(f.trigger_kind),status:p(f.status),claimToken:C(f.claim_token),claimStartedAt:C(f.claim_started_at),claimUntilAt:C(f.claim_until_at),scheduledFor:C(f.scheduled_for),triggerEventId:C(f.trigger_event_id),startedAt:C(f.started_at),completedAt:C(f.completed_at),sessionId:C(f.session_id),reportPath:C(f.report_path),error:C(f.error),attemptCount:Number(f.attempt_count??0),createdAt:p(f.created_at),updatedAt:p(f.updated_at)}}function SQ(f){return{eventId:p(f.event_id),eventType:p(f.event_type),source:p(f.source),subject:C(f.subject),occurredAt:p(f.occurred_at),receivedAt:p(f.received_at),workspaceRoot:C(f.workspace_root),dedupeKey:C(f.dedupe_key),payload:M8(C(f.payload_json)),attributes:M8(C(f.attributes_json)),processingStatus:p(f.processing_status),matchedSpecCount:Number(f.matched_spec_count??0),queuedRunCount:Number(f.queued_run_count??0),suppressedCount:Number(f.suppressed_count??0),error:C(f.error),createdAt:p(f.created_at),updatedAt:p(f.updated_at)}}function kQ(f){return f?JSON.stringify(f):null}var hF=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function IQ(f){if(f===void 0)return null;if(f&&typeof f==="object")return JSON.stringify(f);return f}function OF(f,$,J,W){for(let H of hF){let Q=f[H],Z=$[H];if(IQ(Q)!==IQ(Z))return!0}if(J===!1&&W===!0)return!0;return!1}function zF(f){return(f.split("/").pop()??f).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function NF(f){return`hub/schedules/${f}.cron.md`}function qF(f){let $={...f.metadata??{},...f.createdBy?{__hubScheduleCreatedBy:f.createdBy}:{},...f.cwd?{__hubScheduleCwd:f.cwd}:{},...f.runtimeOptions?{__hubRuntimeOptions:f.runtimeOptions}:{}};return Object.keys($).length>0?$:void 0}function iJ(f){return{triggerKind:"schedule",title:f.name.trim(),prompt:f.prompt,workspaceRoot:f.workspaceRoot.trim(),schedule:f.cronPattern.trim(),mode:f.mode??"act",systemPrompt:f.systemPrompt,modelSelection:f.modelSelection?JSON.parse(JSON.stringify(f.modelSelection)):void 0,maxIterations:typeof f.maxIterations==="number"?Math.floor(f.maxIterations):void 0,timeoutSeconds:typeof f.timeoutSeconds==="number"?Math.floor(f.timeoutSeconds):void 0,maxParallel:typeof f.maxParallel==="number"?Math.max(1,Math.floor(f.maxParallel)):1,source:"hub-schedule",tags:f.tags?.filter(($)=>$.trim().length>0),enabled:f.enabled!==!1,metadata:qF(f)}}function mQ(f){return JSON.stringify(iJ(f))}function wF(f,$){let J=f.metadata?{...f.metadata}:{},W=$.createdBy===null?void 0:$.createdBy!==void 0?$.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,H=$.cwd!==void 0?$.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,Q=$.runtimeOptions!==void 0?$.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:$.name??f.title,cronPattern:$.cronPattern??f.scheduleExpr??"",prompt:$.prompt??f.prompt??"",workspaceRoot:$.workspaceRoot??f.workspaceRoot??"",cwd:H,modelSelection:$.modelSelection!==void 0?$.modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:$.enabled??f.enabled,mode:$.mode??(f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"),systemPrompt:$.systemPrompt===null?void 0:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,maxIterations:$.maxIterations===null?void 0:$.maxIterations!==void 0?$.maxIterations:f.maxIterations,timeoutSeconds:$.timeoutSeconds===null?void 0:$.timeoutSeconds!==void 0?$.timeoutSeconds:f.timeoutSeconds,maxParallel:$.maxParallel??f.maxParallel??1,createdBy:W,tags:$.tags??f.tags,runtimeOptions:Q,metadata:$.metadata!==void 0?$.metadata:Object.keys(J).length>0?J:void 0}}class S1{db;constructor(f={}){let $=f.dbPath??LF();this.db=MF($),EQ(this.db)}close(){this.db.close?.()}getSpecBySourcePath(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get(f);return $?O0($):void 0}getSpec(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f);return $?O0($):void 0}getSpecByExternalId(f){let $=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get(f);return $?O0($):void 0}listSpecs(f={}){let $=[],J=[];if(f.triggerKind)$.push("trigger_kind = ?"),J.push(f.triggerKind);if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.parseStatus)$.push("parse_status = ?"),J.push(f.parseStatus);if(!f.includeRemoved)$.push("removed = 0");let W=$.length>0?`WHERE ${$.join(" AND ")}`:"",H=Math.max(1,Math.floor(f.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,H).map((Z)=>O0(Z))}createHubSchedule(f){let $=`sched_${E1()}`,J=this.upsertSpec({externalId:$,sourcePath:NF($),triggerKind:"schedule",sourceHash:mQ(f),parseStatus:"valid",spec:iJ(f)});this.initializeScheduleNextRun(J.record.specId);let W=this.getSpec(J.record.specId);if(!W)throw Error("failed to create hub schedule");return W}getHubSchedule(f){let $=this.db.prepare(`SELECT * FROM cron_specs
|
|
281
281
|
WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
|
|
282
|
-
ORDER BY created_at ASC LIMIT 1`).get(f);return $?
|
|
282
|
+
ORDER BY created_at ASC LIMIT 1`).get(f);return $?O0($):void 0}listHubSchedules(f={}){let $=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof f.enabled==="boolean")$.push("enabled = ?"),J.push(f.enabled?1:0);if(f.tags&&f.tags.length>0)for(let Q of f.tags)$.push("tags_json LIKE ?"),J.push(`%"${Q.trim()}"%`);let W=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
|
|
283
283
|
WHERE ${$.join(" AND ")}
|
|
284
|
-
ORDER BY created_at DESC LIMIT ?`).all(...J,
|
|
284
|
+
ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Q)=>O0(Q))}updateHubSchedule(f,$){let J=this.getHubSchedule(f);if(!J)return;let W=wF(J,$),H=this.upsertSpec({externalId:f,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:mQ(W),parseStatus:"valid",spec:iJ(W)});if($.cronPattern!==void 0||$.enabled!==void 0)this.initializeScheduleNextRun(H.record.specId);return this.getSpec(H.record.specId)}deleteHubSchedule(f){let $=this.getHubSchedule(f);if(!$)return!1;return this.markSpecRemoved($.specId),this.cancelQueuedRunsForSpec($.specId),!0}enqueueHubScheduleRun(f,$="manual"){let J=this.getHubSchedule(f);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:$,scheduledFor:jf()})}listEventSpecsForType(f){return this.db.prepare(`SELECT * FROM cron_specs
|
|
285
285
|
WHERE trigger_kind = 'event'
|
|
286
286
|
AND event_type = ?
|
|
287
287
|
AND enabled = 1
|
|
288
288
|
AND removed = 0
|
|
289
289
|
AND parse_status = 'valid'
|
|
290
|
-
ORDER BY created_at ASC`).all(f).map((J)=>
|
|
290
|
+
ORDER BY created_at ASC`).all(f).map((J)=>O0(J))}upsertSpec(f){let $=jf(),J=this.getSpecBySourcePath(f.sourcePath),W=f.spec,H={title:W?.title??J?.title??zF(f.sourcePath),prompt:W?.prompt,workspaceRoot:W?.workspaceRoot,scheduleExpr:W?.triggerKind==="schedule"?W.schedule:void 0,timezone:W?.triggerKind==="schedule"?W.timezone:void 0,eventType:W?.triggerKind==="event"?W.event:void 0,filters:W?.triggerKind==="event"?W.filters:void 0,debounceSeconds:W?.triggerKind==="event"?W.debounceSeconds:void 0,dedupeWindowSeconds:W?.triggerKind==="event"?W.dedupeWindowSeconds:void 0,cooldownSeconds:W?.triggerKind==="event"?W.cooldownSeconds:void 0,mode:W?.mode,systemPrompt:W?.systemPrompt,providerId:W?.modelSelection?.providerId,modelId:W?.modelSelection?.modelId,maxIterations:W?.maxIterations,timeoutSeconds:W?.timeoutSeconds,maxParallel:W&&"maxParallel"in W?W.maxParallel:void 0,tools:W?.tools,notesDirectory:W?.notesDirectory,extensions:W?.extensions,source:W?.source},Q=f.parseStatus==="valid"&&(W?.enabled??!0);if(!J){let P=`cspec_${E1()}`;this.insertSpecRow(P,f,H,Q,$);let B=this.getSpec(P);if(!B)throw Error("failed to insert cron_spec row");return{record:B,created:!0,revisionChanged:!0}}let j=J.sourceHash!==f.sourceHash&&OF(J,H,J.enabled,Q),X=j?J.revision+1:J.revision;this.updateSpecRow(J.specId,f,H,Q,X,$);let A=this.getSpec(J.specId);if(!A)throw Error("failed to reload cron_spec after update");return{record:A,created:!1,revisionChanged:j}}insertSpecRow(f,$,J,W,H){let Q=$.spec;this.db.prepare(`INSERT INTO cron_specs (
|
|
291
291
|
spec_id, external_id, source_path, trigger_kind,
|
|
292
292
|
source_mtime_ms, source_hash, parse_status, parse_error,
|
|
293
293
|
enabled, removed, title, prompt, workspace_root,
|
|
@@ -298,7 +298,7 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
298
298
|
tools_json, notes_directory, extensions_json, source,
|
|
299
299
|
tags_json, metadata_json, revision,
|
|
300
300
|
created_at, updated_at
|
|
301
|
-
) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run(f,$.externalId,$.sourcePath,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,
|
|
301
|
+
) VALUES (${Array.from({length:36},()=>"?").join(",")})`).run(f,$.externalId,$.sourcePath,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,W?1:0,0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,Q?.tags?JSON.stringify(Q.tags):null,Q?.metadata?JSON.stringify(Q.metadata):null,1,H,H)}updateSpecRow(f,$,J,W,H,Q){let Z=$.spec;this.db.prepare(`UPDATE cron_specs SET
|
|
302
302
|
external_id = ?, trigger_kind = ?,
|
|
303
303
|
source_mtime_ms = ?, source_hash = ?, parse_status = ?, parse_error = ?,
|
|
304
304
|
enabled = ?, removed = 0, title = ?, prompt = ?,
|
|
@@ -310,31 +310,31 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
310
310
|
tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
|
|
311
311
|
tags_json = ?, metadata_json = ?,
|
|
312
312
|
revision = ?, updated_at = ?
|
|
313
|
-
WHERE spec_id = ?`).run($.externalId,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,
|
|
313
|
+
WHERE spec_id = ?`).run($.externalId,$.triggerKind,$.sourceMtimeMs??null,$.sourceHash,$.parseStatus,$.parseError??null,W?1:0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,Z?.tags?JSON.stringify(Z.tags):null,Z?.metadata?JSON.stringify(Z.metadata):null,H,Q,f)}markSpecRemoved(f){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(jf(),f)}updateSpecNextRunAt(f,$){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run($??null,jf(),f)}updateSpecLastRunAt(f,$){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run($,jf(),f)}updateLastMaterializedRunId(f,$){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run($,jf(),f)}initializeScheduleNextRun(f){let $=this.getSpec(f);if(!$||$.triggerKind!=="schedule"||!$.enabled||!$.scheduleExpr){this.updateSpecNextRunAt(f,void 0);return}let J=new Date(H$($.scheduleExpr,Date.now(),$.timezone)).toISOString();this.updateSpecNextRunAt(f,J)}materializeDueScheduleRun(f){let $=f.nowMs,J=new Date($).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get(f.specId);if(!W)return this.db.exec("COMMIT;"),{queued:!1};let H=O0(W);if(H.triggerKind!=="schedule"||!H.enabled||H.removed||H.parseStatus!=="valid"||!H.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let Q=H.nextRunAt;if(!Q){let X=new Date(H$(H.scheduleExpr,$,H.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(X,J,H.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:X}}if(new Date(Q).getTime()>$)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:Q};let Z=`crun_${E1()}`,j;try{j=new Date(H$(H.scheduleExpr,$,H.timezone)).toISOString()}catch{j=void 0}return this.db.prepare(`INSERT INTO cron_runs (
|
|
314
314
|
run_id, spec_id, spec_revision, trigger_kind, status,
|
|
315
315
|
scheduled_for, trigger_event_id, attempt_count,
|
|
316
316
|
created_at, updated_at
|
|
317
|
-
) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(Z,
|
|
317
|
+
) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(Z,H.specId,H.revision,"schedule","queued",Q,null,0,J,J),this.db.prepare(`UPDATE cron_specs SET
|
|
318
318
|
last_materialized_run_id = ?,
|
|
319
319
|
last_run_at = ?,
|
|
320
320
|
next_run_at = ?,
|
|
321
321
|
updated_at = ?
|
|
322
|
-
WHERE spec_id = ?`).run(Z,J,j??null,J,
|
|
322
|
+
WHERE spec_id = ?`).run(Z,J,j??null,J,H.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(Z),nextRunAt:j}}catch(W){throw this.db.exec("ROLLBACK;"),W}}getRun(f){let $=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get(f);return $?pJ($):void 0}insertEventLog(f,$={}){let J=jf(),W=$.receivedAtIso??J,H=f.eventId.trim();if(!H)throw Error("automation event requires eventId");let Q=f.eventType.trim();if(!Q)throw Error("automation event requires eventType");let Z=f.source.trim();if(!Z)throw Error("automation event requires source");let j=f.occurredAt.trim()||W,X=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
|
|
323
323
|
event_id, event_type, source, subject,
|
|
324
324
|
occurred_at, received_at, workspace_root, dedupe_key,
|
|
325
325
|
payload_json, attributes_json, processing_status,
|
|
326
326
|
matched_spec_count, queued_run_count, suppressed_count,
|
|
327
327
|
error, created_at, updated_at
|
|
328
|
-
) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(
|
|
328
|
+
) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(H,Q,Z,f.subject?.trim()||null,j,W,f.workspaceRoot?.trim()||null,f.dedupeKey?.trim()||null,kQ(f.payload),kQ(f.attributes),"received",0,0,0,null,J,J).changes??0,A=this.getEventLog(H);if(!A)throw Error("failed to insert cron_event_log row");return{record:A,created:X===1}}getEventLog(f){let $=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get(f);return $?SQ($):void 0}listEventLogs(f={}){let $=[],J=[];if(f.eventType)$.push("event_type = ?"),J.push(f.eventType);if(f.source)$.push("source = ?"),J.push(f.source);if(f.processingStatus)$.push("processing_status = ?"),J.push(f.processingStatus);let W=$.length>0?`WHERE ${$.join(" AND ")}`:"",H=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${W}
|
|
329
329
|
ORDER BY received_at DESC, created_at DESC
|
|
330
|
-
LIMIT ?`).all(...J,
|
|
330
|
+
LIMIT ?`).all(...J,H).map((Z)=>SQ(Z))}updateEventLogProcessing(f,$){return(this.db.prepare(`UPDATE cron_event_log SET
|
|
331
331
|
processing_status = ?,
|
|
332
332
|
matched_spec_count = COALESCE(?, matched_spec_count),
|
|
333
333
|
queued_run_count = COALESCE(?, queued_run_count),
|
|
334
334
|
suppressed_count = COALESCE(?, suppressed_count),
|
|
335
335
|
error = ?,
|
|
336
336
|
updated_at = ?
|
|
337
|
-
WHERE event_id = ?`).run($.status,$.matchedSpecCount??null,$.queuedRunCount??null,$.suppressedCount??null,$.error??null,
|
|
337
|
+
WHERE event_id = ?`).run($.status,$.matchedSpecCount??null,$.queuedRunCount??null,$.suppressedCount??null,$.error??null,jf(),f).changes??0)===1}listRuns(f={}){let $=[],J=[];if(f.specId)$.push("spec_id = ?"),J.push(f.specId);if(f.status){let Z=Array.isArray(f.status)?f.status:[f.status];if(Z.length>0){let j=Z.map(()=>"?").join(",");$.push(`status IN (${j})`);for(let X of Z)J.push(X)}}let W=$.length>0?`WHERE ${$.join(" AND ")}`:"",H=Math.max(1,Math.floor(f.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,H).map((Z)=>pJ(Z))}hasRecentEventRunForDedupe(f){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
|
|
338
338
|
INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
|
|
339
339
|
WHERE r.spec_id = ?
|
|
340
340
|
AND r.trigger_kind = 'event'
|
|
@@ -352,7 +352,7 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
352
352
|
AND r.status = 'queued'
|
|
353
353
|
AND e.dedupe_key = ?
|
|
354
354
|
ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
|
|
355
|
-
LIMIT 1`).get(f.specId,f.dedupeKey);return $?
|
|
355
|
+
LIMIT 1`).get(f.specId,f.dedupeKey);return $?pJ($):void 0}updateQueuedEventRunForDebounce(f){let $=jf();if((this.db.prepare(`UPDATE cron_runs SET
|
|
356
356
|
trigger_event_id = ?,
|
|
357
357
|
scheduled_for = ?,
|
|
358
358
|
updated_at = ?
|
|
@@ -361,12 +361,12 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
361
361
|
AND status = 'queued'`).run(f.triggerEventId,f.scheduledFor,$,f.runId).changes??0)!==1)return;return this.getRun(f.runId)}hasOneOffRunForRevision(f,$){return!!this.db.prepare(`SELECT run_id FROM cron_runs
|
|
362
362
|
WHERE spec_id = ? AND spec_revision = ?
|
|
363
363
|
AND trigger_kind = 'one_off'
|
|
364
|
-
LIMIT 1`).get(f,$)}enqueueRun(f){let $=`crun_${
|
|
364
|
+
LIMIT 1`).get(f,$)}enqueueRun(f){let $=`crun_${E1()}`,J=jf();this.db.prepare(`INSERT INTO cron_runs (
|
|
365
365
|
run_id, spec_id, spec_revision, trigger_kind, status,
|
|
366
366
|
scheduled_for, trigger_event_id, attempt_count,
|
|
367
367
|
created_at, updated_at
|
|
368
|
-
) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run($,f.specId,f.specRevision,f.triggerKind,"queued",f.scheduledFor??null,f.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId(f.specId,$);let
|
|
369
|
-
WHERE spec_id = ? AND status = 'queued'`).run(
|
|
368
|
+
) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run($,f.specId,f.specRevision,f.triggerKind,"queued",f.scheduledFor??null,f.triggerEventId??null,0,J,J),this.updateLastMaterializedRunId(f.specId,$);let W=this.getRun($);if(!W)throw Error("failed to insert cron_run row");return W}cancelQueuedRunsForSpec(f){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
|
|
369
|
+
WHERE spec_id = ? AND status = 'queued'`).run(jf(),f).changes??0}claimDueRuns(f){let $=f.nowIso,J=Math.max(1000,Math.floor(f.leaseMs)),W=new Date(new Date($).getTime()+J).toISOString(),H=Math.max(1,Math.floor(f.limit??25)),Q=[];this.db.exec("BEGIN IMMEDIATE;");try{let Z=this.db.prepare(`SELECT * FROM cron_runs
|
|
370
370
|
WHERE (
|
|
371
371
|
status = 'queued'
|
|
372
372
|
OR (
|
|
@@ -378,7 +378,7 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
378
378
|
)
|
|
379
379
|
AND (scheduled_for IS NULL OR scheduled_for <= ?)
|
|
380
380
|
ORDER BY COALESCE(scheduled_for, created_at) ASC
|
|
381
|
-
LIMIT ?`).all($,$,
|
|
381
|
+
LIMIT ?`).all($,$,H);for(let j of Z){let X=p(j.run_id);if(!X)continue;let A=`cclaim_${E1()}`;if((this.db.prepare(`UPDATE cron_runs SET
|
|
382
382
|
status = 'running',
|
|
383
383
|
claim_token = ?,
|
|
384
384
|
claim_started_at = ?,
|
|
@@ -399,8 +399,8 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
399
399
|
AND claim_until_at <= ?
|
|
400
400
|
AND completed_at IS NULL
|
|
401
401
|
)
|
|
402
|
-
)`).run(
|
|
403
|
-
WHERE run_id = ? AND claim_token = ?`).run(J,
|
|
402
|
+
)`).run(A,$,W,$,$,X,$).changes??0)!==1)continue;let B=this.getRun(X);if(!B)continue;Q.push({run:B,claimToken:A,claimUntilAt:W})}this.db.exec("COMMIT;")}catch(Z){throw this.db.exec("ROLLBACK;"),Z}return Q}renewClaim(f,$,J){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
|
|
403
|
+
WHERE run_id = ? AND claim_token = ?`).run(J,jf(),f,$).changes??0)===1}completeRun(f,$){let J=$.completedAtIso??jf(),W=$.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
|
|
404
404
|
status = ?,
|
|
405
405
|
session_id = COALESCE(?, session_id),
|
|
406
406
|
report_path = COALESCE(?, report_path),
|
|
@@ -410,7 +410,7 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
410
410
|
claim_token = NULL,
|
|
411
411
|
claim_until_at = NULL,
|
|
412
412
|
updated_at = ?
|
|
413
|
-
${
|
|
413
|
+
${W}`).run($.status,$.sessionId??null,$.reportPath??null,$.error??null,J,J,f,...$.claimToken?[$.claimToken]:[]).changes??0)>0}requeueRun(f){let $=jf();return(this.db.prepare(`UPDATE cron_runs SET
|
|
414
414
|
status = 'queued',
|
|
415
415
|
claim_started_at = NULL,
|
|
416
416
|
claim_token = NULL,
|
|
@@ -422,41 +422,41 @@ ${JSON.stringify(H,null,2)}`}startClaimLeaseHeartbeat(f){let $=Math.max(1000,Mat
|
|
|
422
422
|
error = ?,
|
|
423
423
|
scheduled_for = COALESCE(?, scheduled_for),
|
|
424
424
|
updated_at = ?
|
|
425
|
-
WHERE run_id = ? AND claim_token = ?`).run(f.error??null,f.scheduledFor??null,$,f.runId,f.claimToken).changes??0)>0}attachSessionIdToRun(f,$){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run($,
|
|
426
|
-
`)[0]?.trim())}function
|
|
427
|
-
`,"utf8")}function
|
|
428
|
-
`).trim()}function
|
|
429
|
-
`)[0]??
|
|
430
|
-
`,{encoding:"utf8",mode:384}),await
|
|
431
|
-
`,"utf8");try{return await $()}finally{await n7(J)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let Z=await sF(J),j=Z?Date.now()-Date.parse(Z.acquiredAt):i7+1;if(!Z||!nF(Z.pid)||j>i7){await n7(J);continue}if(Date.now()>=H)throw Error(`Timed out waiting for hub startup lock ${J}`);await aF(lF)}}async function Yf(f){try{let $=await fetch(oF(f));if(!$.ok)return;return await $.json()}catch{return}}function $0(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function oF(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function Fb(f){return vF(f)}import{CLINE_HUB_DEV_PORT as eF,CLINE_HUB_PORT as fy,resolveClineBuildEnv as $y}from"@cline/shared";var Jy="CLINE_HUB_HOST",Hy="CLINE_HUB_PORT",Wy="CLINE_HUB_PATHNAME",Qy="127.0.0.1",Zy=fy,jy="/hub";function $Q(f){return $y(f)==="development"?eF:Zy}function Py(f={}){return(f.env??process.env)[Jy]?.trim()||Qy}function O8(f={}){let J=(f.env??process.env)[Hy]?.trim();if(!J)return $Q(f);let H=Number.parseInt(J,10);if(!Number.isInteger(H)||H<1||H>65535)return $Q(f);return H}function Xy(f={}){return(f.env??process.env)[Wy]?.trim()||jy}function _0(f={},$={}){return{host:f.host??Py($),port:f.port??O8($),pathname:f.pathname??Xy($)}}var Vy="shared:cline";function Tb(f){let $=s0(f.trim());return H$(`workspace:${$||f.trim()}`)}function Bf(f=Vy){return H$(f)}var Ty=8000,Dy=200,My=3000,_y=100,Ly="--cline-hub-daemon";function zy(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function Oy(){try{let f=Ky(eJ(),"logs","hub-daemon.log");return Ay(yy(f),{recursive:!0}),{fd:Ry(f,"a"),logPath:f}}catch{return}}function S1(f){let $=f.buildId?.trim();return!!$&&$===m$()}async function Ny(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await Yf(f).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,_y))}return!1}async function k1(f,$){if(S1(f))return;if(await fH(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await Ny(f.url,My),await rf($).catch(()=>{return})}function qy(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return Uy(new URL(`./entry.${f}`,import.meta.url))}function by(f,$){let J=qy(),H=process.execPath?.trim();if(!H)throw Error("unable to resolve runtime executable for hub daemon");let W=Fy(H).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),Z=W&&J.toLowerCase().endsWith(".ts"),j=Q?[Ly]:[...Z?["--conditions=development"]:[],J];return{launcher:H,args:[...j,"--cwd",f,...zy($)],cwd:f,env:{...hy(process.env),CLINE_NO_INTERACTIVE:"1",[Gy]:"1"}}}function N8(f,$={}){if(JQ())return;let J=by(f,$),H=Oy();try{Yy(J.launcher,J.args,{detached:!0,stdio:H?["ignore",H.fd,H.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(H)By(H.fd)}}function HQ(f,$={}){if(JQ())return;let J=Bf(),H=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=_0($),Q=$0(W.host,W.port,W.pathname);Zf(J.discoveryPath).then(async(Z)=>{if(Z?.url){let V=await Yf(Z.url);if(V?.url&&S1(V)&&await L0(V.url,{authToken:Z.authToken}))return;if(V?.url)await k1({...V,authToken:Z.authToken},J.discoveryPath);else await rf(J.discoveryPath).catch(()=>{return})}let j=await Yf(Q);if(j?.url)await k1(j,J.discoveryPath);let X=!H&&W.port!==0?{...W,port:0}:W;N8(f,X)}).catch(()=>{})}async function Cb(f,$={}){let J=Bf(),H=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=_0($),Z=$0(Q.host,Q.port,Q.pathname),j=(A)=>{if(!H)I$(A.url,A.authToken);return A},P=await Zf(J.discoveryPath);if(P?.url){let A=await Yf(P.url);if(A?.url&&S1(A)&&await L0(A.url,{authToken:P.authToken}))return j({url:A.url,authToken:P.authToken});if(A?.url)await k1({...A,authToken:P.authToken},J.discoveryPath);else await rf(J.discoveryPath).catch(()=>{return})}let X=await Yf(Z);if(X?.url)await k1(X,J.discoveryPath);let Y=!W&&Q.port!==0?{...Q,port:0}:Q;N8(f,Y);let B=Date.now()+Ty;while(Date.now()<B){let A=await Zf(J.discoveryPath);if(A?.url){let U=await Yf(A.url);if(U?.url&&S1(U)&&await L0(U.url,{authToken:A.authToken}))return j({url:U.url,authToken:A.authToken})}let R=await Yf(Z);if(R?.url&&!S1(R))await k1(R,J.discoveryPath);await new Promise((U)=>setTimeout(U,Dy))}throw Error("Timed out waiting for detached hub startup.")}function Ey(){let f=globalThis.WebSocket;if(!f)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return f}function PQ(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();if(f&&typeof f==="object"&&"data"in f&&typeof f.data<"u")return PQ(f.data);return String(f)}function Sy(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString("utf8");if(f instanceof ArrayBuffer)return Buffer.from(f).toString("utf8");return""}function WQ(f){let $=f,J=Sy($.reason);return new zf("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:$H,{closeCode:$.code,closeReason:J||void 0})}function ky(f,$){if(f instanceof zf)return f;if(f instanceof Error)return new zf("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new zf("hub_connect_failed",f.error.message);let J=f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"?f.message.trim():"";if(J)return new zf("hub_connect_failed",J);let H=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new zf("hub_connect_failed",H?`Failed to connect to hub at ${$.toString()} (${H} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var my=8000,Iy=200,QQ="*",ZQ=8000,xy="cline-hub-auth.",XQ=new Map,VQ=new Set,gy=3000,vy=3000,uy=100,$H="Hub connection closed",cy=250,dy=5000,jQ=0.5;class zf extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function ry(f){return f instanceof zf}class q8 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function YQ(f,$){return f instanceof q8&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function BQ(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=WH(f.toString());return J?XQ.get(J):void 0}function ly(f){try{let J=new URL(f).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function WH(f){if(!ly(f))return;let $=new URL(x$(f));return $.search="",$.hash="",$.toString()}function JH(f){let $=WH(f);return!!$&&VQ.has($)}function I$(f,$){let J=WH(f);if(J){if(VQ.add(J),$?.trim())XQ.set(J,$)}return f}class J0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new zf("hub_connection_closed",$H);sawSocketClose=!1;registered=!1;constructor(f){this.options=f;this.clientId=f.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=f.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let f=new URL(this.currentUrl),$=this.options.authToken?.trim()||BQ(f);f.hash="";let H=new(Ey())(f.toString(),$?[`${xy}${$}`]:void 0);this.socket=H;let W=!1;this.connectPromise=new Promise((Q,Z)=>{let j=!1,P=setTimeout(()=>{if(j)return;j=!0,W=!0,this.lastCloseError=new zf("hub_connect_timeout",`Timed out connecting to hub after ${ZQ}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{H.close()}catch{}Z(this.lastCloseError)},ZQ);H.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(P),Q()}),H.addEventListener("error",(X)=>{if(j)return;j=!0,clearTimeout(P),this.lastCloseError=ky(X,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)}),H.addEventListener("close",(X)=>{if(j)return;if(j=!0,clearTimeout(P),!W)this.lastCloseError=WQ(X),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)})}),H.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(PQ(Q)))}),H.addEventListener("close",(Q)=>{if(this.socket!==H)return;if(!W)this.lastCloseError=WQ(Q),this.sawSocketClose=!0;this.registered=!1;for(let Z of this.pendingReplies.values())Z.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe(f,$){let J=$?.sessionId?.trim()||void 0,H={listener:f,sessionId:J};return this.listeners.add(H),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(H))return;this.adjustSubscriptionCount(J,-1)}}async command(f,$,J,H){let W=0,Q=f!=="client.register"&&f!=="client.unregister";while(!0)try{return await this.commandOnce(f,$,J,H)}catch(Z){if(!Q||W>=1||!await this.recoverLocalHubTransport(Z))throw Z;W+=1}}async commandOnce(f,$,J,H){await this.connect();let W=wy("hubreq_"),Q=Cy(f,H?.timeoutMs),Z=new Promise((P,X)=>{let V=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;X(new q8(f,"hub_command_timeout",`Hub command ${f} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${W}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(W,{resolve:(Y)=>{if(V)clearTimeout(V);P(Y)},reject:(Y)=>{if(V)clearTimeout(V);X(Y)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:f,requestId:W,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:$}})}catch(P){throw this.pendingReplies.delete(W),P}let j=await Z;if(!j.ok)throw new q8(f,j.error?.code,j.error?.message??`Hub command ${f} failed`);return j}async recoverLocalHubTransport(f){if(!JH(this.currentUrl)||!ry(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await m1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let f=Math.min(cy*2**this.reconnectAttempt,dy),$=Math.round(f*(1-jQ)+Math.random()*f*jQ);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!JH(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await m1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(f){this.currentUrl=f,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let f=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!f)return;this.lastCloseError=new zf("hub_connection_closed",$H),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{f.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(f){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new zf("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(f))}sendSubscriptionFrame(f,$){this.sendFrame({kind:f,clientId:this.clientId,...$?{sessionId:$}:{}})}adjustSubscriptionCount(f,$){let J=this.subscriptionKeyForSessionId(f),H=(this.subscriptionCounts.get(J)??0)+$;if(H<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",f);return}if(this.subscriptionCounts.set(J,H),$>0&&H===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",f)}subscriptionKeyForSessionId(f){return f??QQ}subscriptionSessionIdFromKey(f){return f===QQ?void 0:f}handleFrame(f){switch(f.kind){case"reply":{let $=f.envelope.requestId;if(!$)return;let J=this.pendingReplies.get($);if(!J)return;this.pendingReplies.delete($),J.resolve(f.envelope);return}case"event":for(let $ of this.listeners){if($.sessionId&&$.sessionId!==f.envelope.sessionId?.trim())continue;$.listener(f.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function x$(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function L0(f,$){let J=new J0({url:f,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function HH(f,$){let J=x$(f),H=await Yf(J);if(!H)return{status:"unreachable",url:J};let W=m$(),Q=H.buildId?.trim();if(!Q||Q!==W)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await L0(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function py(f){let $=Date.now()+my;while(Date.now()<$){let J=await Zf(f.discoveryPath);if(J?.url){let H=await HH(J.url,{verifyConnection:!0,authToken:J.authToken});if(H.status==="compatible")return I$(H.url,J.authToken)}await new Promise((H)=>setTimeout(H,Iy))}return}async function iy(f){let $=Date.now()+vy;while(Date.now()<$){if(!(await Yf(f).catch(()=>{return}))?.url)return!0;await new Promise((H)=>setTimeout(H,uy))}return!1}function ny(f,$){try{return x$(f)===x$($)}catch{return!1}}function ay(f){return(f&&typeof f==="object"&&Array.isArray(f.sessions)?f.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let H=J;if(H.status==="running"||H.status==="idle")return!0;return Array.isArray(H.participants)&&H.participants.length>0})}async function ty(f,$,J){let H=new J0({url:f,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let W=await H.command("session.list",{limit:500},void 0,{timeoutMs:gy});return!ay(W.payload)}catch{return!1}finally{await H.dispose().catch(()=>{return})}}async function QH(f={}){if(f.endpoint?.trim()){let W=await HH(f.endpoint);return W.status==="compatible"?W.url:void 0}let $=Bf(),J=await Zf($.discoveryPath);if(!J?.url)return;let H=await HH(J.url);if(H.status==="compatible")return I$(H.url,J.authToken);if(H.status==="build_mismatch")await rf($.discoveryPath).catch(()=>{return});return}async function m1(f={}){let $=await QH(f);if($&&await L0($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=Bf();return N8(f.workspaceRoot??process.cwd()),await py(J)}async function fH(f,$){let J=new URL(f),H=$?.trim()||BQ(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:H?{authorization:`Bearer ${H}`}:void 0})).ok}async function sy(){let f=Bf(),$=await Zf(f.discoveryPath);if(!$?.url)return!1;try{if(await fH($.url,$.authToken))return!0}catch{}return!1}async function AQ(f){if(!JH(f.url))return;let $=Bf(),J=await Zf($.discoveryPath);if(!J?.url||!ny(J.url,f.url))return;if(!await ty(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await sy())return;if(!await iy(J.url))return;return await rf($.discoveryPath).catch(()=>{return}),await m1({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}import{createSessionId as RQ,HUB_CHECKPOINT_CAPABILITY as $K,HUB_COMPACTION_CAPABILITY as JK,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as HK,HUB_HOOK_CAPABILITY_PREFIX as WK,HUB_MISTAKE_LIMIT_CAPABILITY as QK,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ZK,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as jK,isHubToolExecutorName as PK}from"@cline/shared";function oy(f){return f?JSON.parse(JSON.stringify(f)):void 0}function ey(f){return f?JSON.parse(JSON.stringify(f)):void 0}function fK(f){let $=f?.checkpoint&&typeof f.checkpoint==="object"&&!Array.isArray(f.checkpoint)?f.checkpoint:void 0,H=(Array.isArray($?.history)?$.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let j=typeof Z.ref==="string"?Z.ref.trim():"",P=Number(Z.createdAt),X=Number(Z.runCount);if(!j||!Number.isFinite(P)||!Number.isInteger(X))return[];return[{ref:j,createdAt:P,runCount:X,...Z.kind==="stash"||Z.kind==="commit"?{kind:Z.kind}:{}}]}),W=H.at(-1),Q=f?.checkpointEnabled===!0?!0:void 0;if(!Q&&H.length===0)return;return{...Q?{enabled:Q}:{},...W?{latest:W}:{},history:H}}function z0(f){let{session:$}=f,J=oy($.metadata);return{version:1,sessionId:$.sessionId,source:$.source,status:$.status,createdAt:$.startedAt,updatedAt:$.updatedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,interactive:$.interactive,workspace:{cwd:$.cwd,root:$.workspaceRoot},model:{providerId:$.provider,modelId:$.model},capabilities:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams},lineage:{...$.parentSessionId?{parentSessionId:$.parentSessionId}:{},...$.parentAgentId?{parentAgentId:$.parentAgentId}:{},...$.agentId?{agentId:$.agentId}:{},...$.conversationId?{conversationId:$.conversationId}:{},isSubagent:$.isSubagent},...$.teamName?{team:{name:$.teamName}}:{},...$.prompt?{prompt:$.prompt}:{},...J?{metadata:J}:{},...$.messagesPath?{artifacts:{messagesPath:$.messagesPath}}:{},...f.messages?{messages:ey(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...(()=>{let H=fK(J);return H?{checkpoint:H}:{}})()}}function ZH(f){return{sessionId:f.sessionId,parentSessionId:f.lineage.parentSessionId,agentId:f.lineage.agentId,parentAgentId:f.lineage.parentAgentId,conversationId:f.lineage.conversationId,isSubagent:f.lineage.isSubagent,source:f.source,startedAt:f.createdAt,endedAt:f.endedAt??void 0,exitCode:f.exitCode??void 0,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspaceRoot:f.workspace.root,teamName:f.team?.name,enableTools:f.capabilities.enableTools,enableSpawn:f.capabilities.enableSpawn,enableTeams:f.capabilities.enableTeams,prompt:f.prompt,metadata:f.metadata,updatedAt:f.updatedAt,messagesPath:f.artifacts?.messagesPath}}function g$(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var XK=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function FQ(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function yQ(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function KQ(f){let $=f&&typeof f==="object"&&!Array.isArray(f)?f:{};return{agentId:typeof $.agentId==="string"?$.agentId:"",conversationId:typeof $.conversationId==="string"?$.conversationId:"",iteration:typeof $.iteration==="number"?$.iteration:0,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}}function W$(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function UQ(f,$){let J={manifest:[],handlers:new Map};for(let W of Object.keys($.toolExecutors??{}).filter(PK)){let Q=$.toolExecutors?.[W];if(typeof Q!=="function")continue;W$(J,{kind:"toolExecutor",executor:W,capabilityName:`${ZK}${W}`},async({payload:Z,abortSignal:j})=>{let P=Array.isArray(Z.args)?[...Z.args]:[],X={...KQ(Z.context),signal:j};return{result:await Q(...P,X)}})}for(let W of f?.extraTools??[])W$(J,{kind:"tool",name:W.name,description:W.description,inputSchema:g$(W.inputSchema)??{},...W.lifecycle?{lifecycle:g$(W.lifecycle)}:{},capabilityName:`${HK}${W.name}`},async({payload:Q,abortSignal:Z,progress:j})=>{let P={...KQ(Q.context),signal:Z};return{result:await W.execute(Q.input,{...P,emitUpdate:(V)=>{j({update:V})}})}});let H=f?.hooks;if(H)for(let W of XK){let Q=H[W];if(typeof Q!=="function")continue;W$(J,{kind:"hook",name:W,capabilityName:`${WK}${W}`},async({payload:Z})=>({control:await Q(Z.context)}))}if(f?.compaction?.compact){let W=f.compaction.compact;W$(J,{kind:"compaction",capabilityName:JK,config:FQ(f.compaction)},async({payload:Q})=>({result:await W(Q.context)}))}if(f?.checkpoint?.createCheckpoint){let W=f.checkpoint.createCheckpoint;W$(J,{kind:"checkpoint",capabilityName:$K,config:FQ(f.checkpoint)},async({payload:Q})=>({result:await W(Q.context)}))}if(f?.onConsecutiveMistakeLimitReached){let W=f.onConsecutiveMistakeLimitReached;W$(J,{kind:"mistakeLimit",capabilityName:QK},async({payload:Q})=>({result:await W(Q.context)}))}if(f?.userInstructionService){let W=f.userInstructionService;W$(J,{kind:"userInstructionService",capabilityName:jK},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return J}function VK(f){if(typeof f==="string"&&f.trim())return f.trim();if(f instanceof Error)return f.message;if(f&&typeof f==="object"&&"message"in f){let $=f.message;if(typeof $==="string"&&$.trim())return $.trim()}return"Capability request was cancelled."}function YK(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function BK(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function AK(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=typeof $.inputTokens==="number"?$.inputTokens:void 0,H=typeof $.outputTokens==="number"?$.outputTokens:void 0;if(J===void 0||H===void 0)return;return{inputTokens:J,outputTokens:H,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function RK(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,H=BK(J)?J:J==="failed"?"error":"completed",W=AK(f?.usage??$?.usage);return{type:"done",reason:H,text:typeof f?.text==="string"?f.text:typeof $?.text==="string"?$.text:"",iterations:typeof f?.iterations==="number"?f.iterations:typeof $?.iterations==="number"?$.iterations:0,usage:W}}function jH(f,$){return f.error?.message??`hub command failed: ${$}`}function I1(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function TQ(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):void 0;return{sessionId:f.sessionId,parentSessionId:typeof $?.parentSessionId==="string"?$.parentSessionId:void 0,agentId:f.runtimeSession?.agentId||(typeof $?.agentId==="string"?$.agentId:void 0),parentAgentId:typeof $?.parentAgentId==="string"?$.parentAgentId:void 0,conversationId:typeof $?.conversationId==="string"?$.conversationId:void 0,isSubagent:typeof $?.isSubagent==="boolean"?$.isSubagent:!1,source:typeof $?.source==="string"?$.source:Pf.CORE,pid:typeof $?.pid==="number"?$.pid:void 0,startedAt:new Date(f.createdAt).toISOString(),endedAt:I1(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:I1(f.status)==="completed"?0:I1(f.status)==="failed"?1:void 0,status:I1(f.status),interactive:$?.interactive===!0,provider:typeof $?.provider==="string"?$.provider:"hub",model:typeof $?.model==="string"?$.model:"hub",cwd:f.cwd?.trim()||f.workspaceRoot,workspaceRoot:f.workspaceRoot,teamName:typeof $?.teamName==="string"?$.teamName:void 0,enableTools:f.runtimeOptions?.enableTools??$?.enableTools===!0,enableSpawn:f.runtimeOptions?.enableSpawn??$?.enableSpawn===!0,enableTeams:f.runtimeOptions?.enableTeams??$?.enableTeams===!0,prompt:typeof $?.prompt==="string"?$.prompt:void 0,metadata:$,updatedAt:new Date(f.updatedAt).toISOString(),messagesPath:typeof $?.messagesPath==="string"?$.messagesPath:void 0,hookPath:typeof $?.hookPath==="string"?$.hookPath:void 0}}function Q$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;return $.version===1&&typeof $.sessionId==="string"?JSON.parse(JSON.stringify($)):void 0}function FK(f){let $=Q$(f?.snapshot);if($)return ZH($);let J=f?.session;return J?TQ(J):void 0}function GQ(f,$,J){let H=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return yf.parse({version:1,session_id:f,source:$.source??Pf.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:I1(J?.status),interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:J?.cwd?.trim()||$.config.cwd,workspace_root:H,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,metadata:$.sessionMetadata&&Object.keys($.sessionMetadata).length>0?$.sessionMetadata:void 0})}function hQ(f,$){return yf.parse({version:1,session_id:f.sessionId,source:f.source,pid:process.pid,started_at:f.createdAt,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspace_root:f.workspace.root,team_name:f.team?.name,enable_tools:f.capabilities.enableTools,enable_spawn:f.capabilities.enableSpawn,enable_teams:f.capabilities.enableTeams,prompt:(f.prompt??$.prompt?.trim())||void 0,metadata:f.metadata,messages_path:f.artifacts?.messagesPath})}class Z${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new E1;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;constructor(f,$){this.clientContext=$,this.clientOptions={authToken:f.authToken,clientType:f.clientType??"core-hub-runtime",displayName:f.displayName??"core hub runtime",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd},this.defaultCapabilities=Vf(f.capabilities)??{},this.runtimeAddress=f.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient(f.url)}createClient(f){return new J0({...this.clientOptions,url:f})}async replaceClient(f){let $=this.client;this.client=this.createClient(f),this.runtimeAddress=f,await Promise.resolve($.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock(f){if(!YQ(f,"session.create"))return!1;let $=await AQ({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!$)return!1;return await this.replaceClient($),!0}registerPlannedSession(f,$,J){if(this.sessionCapabilities.set(f,$),J.size>0)this.sessionClientContributionHandlers.set(f,J);this.ensureSessionSubscription(f)}cleanupPlannedSession(f){this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f)}async connect(){await this.client.connect()}async startSession(f){let $=this.resolveCapabilities(f),J=UQ(f.localRuntime,$),H=f.config.sessionId?.trim()||RQ(),W=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:g$({...f.config,sessionId:H}),metadata:{...f.sessionMetadata??{},source:f.source??Pf.CORE,provider:f.config.providerId,model:f.config.modelId,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,teamName:f.config.teamName,prompt:f.prompt,interactive:f.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...f.localRuntime?.configExtensions?{configExtensions:f.localRuntime.configExtensions}:{}},toolPolicies:g$(f.toolPolicies),initialMessages:f.initialMessages});this.registerPlannedSession(H,$,J.handlers);let Q;try{Q=await W()}catch(X){if(this.cleanupPlannedSession(H),await this.recoverLocalHubStartupDeadlock(X)){this.registerPlannedSession(H,$,J.handlers);try{Q=await W()}catch(V){throw this.cleanupPlannedSession(H),V}}else throw X}let Z=Q$(Q.payload?.snapshot),j=Q.payload?.session,P=(Z?.sessionId??j?.sessionId)?.trim();if(!P)throw this.cleanupPlannedSession(H),Error("Hub runtime did not return a session id.");if(P!==H)this.cleanupPlannedSession(H),this.registerPlannedSession(P,$,J.handlers);return{sessionId:P,manifest:Z?hQ(Z,f):GQ(P,f,j),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.start)throw Error("start is required when restore.messages is true");let H=f.start,W=H?this.resolveCapabilities(H):void 0,Q=H?UQ(H.localRuntime,W??{}):{manifest:[],handlers:new Map},Z=H?H.config.sessionId?.trim()||RQ():void 0;if(Z&&W)this.sessionCapabilities.set(Z,W);if(Z&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(Z,Q.handlers),this.ensureSessionSubscription(Z);let j;try{j=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...H?{workspaceRoot:H.config.workspaceRoot?.trim()||H.config.cwd,cwd:H.config.cwd??f.cwd,sessionConfig:g$({...H.config,sessionId:Z}),metadata:{...H.sessionMetadata??{},source:H.source??Pf.CORE,provider:H.config.providerId,model:H.config.modelId,enableTools:H.config.enableTools,enableSpawn:H.config.enableSpawnAgent,enableTeams:H.config.enableAgentTeams,teamName:H.config.teamName,prompt:H.prompt,interactive:H.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...H.localRuntime?.configExtensions?{configExtensions:H.localRuntime.configExtensions}:{}},toolPolicies:g$(H.toolPolicies)}:{}},$)}catch(A){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw A}if(!j.ok){let A=typeof j.payload?.error==="string"?j.payload.error:"session.restore failed";if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error(A)}let P=Q$(j.payload?.snapshot),X=j.payload?.session,V=(P?.sessionId??X?.sessionId)?.trim();if(J&&!V){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error("Hub checkpoint restore returned no session id")}if(V&&Z&&V!==Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);if(V&&W)this.sessionCapabilities.set(V,W);if(V&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(V,Q.handlers);if(V)this.ensureSessionSubscription(V);let Y=Array.isArray(j.payload?.messages)?j.payload.messages:void 0,B=j.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:V,startResult:V?{sessionId:V,manifest:P?hQ(P,H??{}):GQ(V,H??{},X),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:Y,checkpoint:B}}async runTurn(f){return this.ensureSessionSubscription(f.sessionId),(await this.client.command("run.start",{sessionId:f.sessionId,input:f.prompt,attachments:(f.userImages?.length??0)>0||(f.userFiles?.length??0)>0?{...f.userImages?.length?{userImages:f.userImages}:{},...f.userFiles?.length?{userFiles:f.userFiles}:{}}:void 0,delivery:f.delivery,timeoutMs:f.timeoutMs},f.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.pending_prompts",{sessionId:f.sessionId},f.sessionId);return Array.isArray($.payload?.prompts)?$.payload.prompts:[]}async requestPendingPromptUpdate(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.update_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,updated:$.payload?.updated===!0}}async requestPendingPromptDelete(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.remove_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,removed:$.payload?.removed===!0}}async getAccumulatedUsage(f){let $=await this.client.command("session.get",{includeSnapshot:!0},f),J=Q$($.payload?.snapshot);if(J?.usage)return{...J.usage};let H=$.payload?.session;return H?.usage?{...H.usage}:void 0}async abort(f,$){await this.client.command("run.abort",{sessionId:f,reason:typeof $==="string"?$:void 0},f)}async stopSession(f){this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),await this.client.command("session.detach",{sessionId:f},f)}async dispose(){for(let[f,$]of this.sessionSubscriptions){$();try{await this.client.command("session.detach",{sessionId:f},f)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let f of this.activeCapabilityAbortControllers.values())f.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession(f){let $=await this.client.command("session.get",void 0,f);return FK($.payload)}async listSessions(f=100){let $=await this.client.command("session.list",{limit:f}),J=Array.isArray($.payload?.snapshots)?$.payload.snapshots.flatMap((W)=>{let Q=Q$(W);return Q?[ZH(Q)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(TQ)}async listSettings(f){let $=await this.client.command("settings.list",yQ(f));if(!$.ok)throw Error(jH($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",yQ(f));if(!$.ok)throw Error(jH($,"settings.toggle"));return{snapshot:$.payload?.snapshot,changedTypes:Array.isArray($.payload?.changedTypes)?$.payload.changedTypes:[]}}async deleteSession(f){return this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),(await this.client.command("session.delete",{sessionId:f})).payload?.deleted===!0}async updateSession(f,$){let J={...$.metadata??{}};if(typeof $.prompt==="string")J.prompt=$.prompt;if(typeof $.title==="string")J.title=$.title;return{updated:(await this.client.command("session.update",{sessionId:f,metadata:J})).ok}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(jH(J,"session.messages"));let H=J.payload?.messages;return Array.isArray(H)?H:[]}async dispatchHookEvent(f){await this.client.command("session.hook",{payload:f})}subscribe(f,$){return this.events.subscribe(f,$)}ensureSessionSubscription(f){let $=f.trim();if(!$||this.sessionSubscriptions.has($))return;let J=this.client.subscribe((H)=>{this.handleHubEvent(H)},{sessionId:$});this.sessionSubscriptions.set($,typeof J==="function"?J:()=>{})}disposeSessionSubscription(f){let $=f.trim();if(!$)return;this.sessionSubscriptions.get($)?.(),this.sessionSubscriptions.delete($),this.agentDoneEmittedForCurrentRunBySession.delete($)}resolveCapabilities(f){return Vf(this.defaultCapabilities,f.capabilities)??{}}emitToolCallContentStart(f){this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:f.toolCallId,toolName:f.toolName,input:f.toolInput}}})}emitAgentDoneIfNeeded(f){if(this.agentDoneEmittedForCurrentRunBySession.has(f.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add(f.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:RK(f.payload)}})}handleHubEvent(f){let $=f.sessionId?.trim();if(f.event==="capability.requested"){this.handleCapabilityRequest(f);return}if(f.event==="capability.resolved"){this.handleCapabilityResolved(f);return}if(f.event==="approval.requested"){this.handleApprovalRequested(f);return}if(!$)return;switch(f.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete($);let J=Q$(f.payload?.snapshot),H=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:H?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_start",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_end",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,hadToolCalls:f.payload?.hadToolCalls===!0,toolCallCount:typeof f.payload?.toolCallCount==="number"?f.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"text",text:typeof f.payload?.text==="string"?f.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"",H=f.payload?.redacted===!0;if(!J&&!H)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:H}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"reasoning",reasoning:typeof f.payload?.reasoning==="string"?f.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:$,payload:f.payload});return}case"tool.started":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:$,toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,toolInput:f.payload?.input});return}case"tool.finished":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,output:f.payload?.output,error:typeof f.payload?.error==="string"?f.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=Q$(f.payload?.snapshot),H=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:H?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:$,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=f.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:$,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=typeof f.payload?.reason==="string"?f.payload.reason:f.event==="run.aborted"?"aborted":f.event==="run.failed"?"error":"completed";this.emitAgentDoneIfNeeded({sessionId:$,payload:{...f.payload,reason:J}}),this.events.emit({type:"ended",payload:{sessionId:$,reason:J,ts:f.timestamp??Date.now()}});return}default:return}}async handleCapabilityRequest(f){let $=f.sessionId?.trim();if(!$)return;let J=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let H=typeof f.payload?.requestId==="string"?f.payload.requestId:"",W=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName:"";if(!H)return;let Q=this.sessionClientContributionHandlers.get($)?.get(W);if(!Q){await this.client.command("capability.respond",{requestId:H,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${$}.`},$).catch(()=>{});return}let Z=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=new AbortController;this.activeCapabilityAbortControllers.set(H,j);let P=(X)=>{this.client.command("capability.progress",{requestId:H,payload:X},$)};try{let X=await Q({payload:Z,abortSignal:j.signal,progress:P});if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:H,ok:!0,payload:X},$)}catch(X){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:H,ok:!1,error:X instanceof Error?X.message:String(X)},$)}finally{this.activeCapabilityAbortControllers.delete(H)}}handleCapabilityResolved(f){if(f.payload?.cancelled!==!0)return;let $=typeof f.payload.requestId==="string"?f.payload.requestId.trim():"";if(!$)return;let J=this.activeCapabilityAbortControllers.get($);if(!J)return;J.abort(VK(f.payload.error))}async handleApprovalRequested(f){let $=f.sessionId?.trim();if(!$)return;let J=this.sessionCapabilities.get($)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let H=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"",W=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:"",Q=typeof f.payload?.toolName==="string"?f.payload.toolName:"";if(!H||!W||!Q)return;let Z=f.payload?.policy&&typeof f.payload.policy==="object"&&!Array.isArray(f.payload.policy)?f.payload.policy:{autoApprove:!1},j=YK(f.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:$,toolCallId:W,toolName:Q,toolInput:j});let P=await Promise.resolve(J({sessionId:$,agentId:typeof f.payload?.agentId==="string"?f.payload.agentId:"",conversationId:typeof f.payload?.conversationId==="string"?f.payload.conversationId:$,iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,toolCallId:W,toolName:Q,input:j,policy:Z})).catch((X)=>({approved:!1,reason:X instanceof Error?X.message:`Tool approval request failed: ${String(X)}`}));await this.client.command("approval.respond",{approvalId:H,approved:P.approved,reason:P.reason},$).catch(()=>{})}}class b8 extends Z${constructor(f){super({url:x$(f.endpoint),authToken:f.authToken,clientType:f.clientType??"core-remote-runtime",displayName:f.displayName??"core remote runtime",capabilities:f.capabilities},{workspaceRoot:f.workspaceRoot,cwd:f.cwd})}}import{existsSync as yK,mkdirSync as KK}from"node:fs";import{join as UK}from"node:path";import{asBool as x1,asOptionalString as lf,asString as H0,ensureSessionSchema as GK,loadSqliteDb as hK,nowIso as w8,toBoolInt as g1}from"@cline/shared/db";import{resolveDbDataDir as TK}from"@cline/shared/storage";class O0{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??TK()}init(){this.getRawDb()}ensureSessionsDir(){if(!yK(this.sessionsDirPath))KK(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return UK(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=hK(this.sessionDbPath());return GK(f,{includeLegacyMigrations:!0}),this.db=f,f}close(){this.db?.close?.(),this.db=void 0}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}create(f){let $=w8();this.run(`INSERT OR REPLACE INTO sessions (
|
|
425
|
+
WHERE run_id = ? AND claim_token = ?`).run(f.error??null,f.scheduledFor??null,$,f.runId,f.claimToken).changes??0)>0}attachSessionIdToRun(f,$){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run($,jf(),f)}attachReportPathToRun(f,$){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run($,jf(),f)}}class k1{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new S1({dbPath:f.dbPath});let $=f.specs;this.reconciler=new dJ({store:this.store,specs:$}),this.materializer=new q1({store:this.store}),this.eventIngress=new wJ({store:this.store,logger:f.logger}),this.runner=new w1({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:f.workspaceRoot,specs:$,logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency}),this.watcher=new rJ({reconciler:this.reconciler,debounceMs:f.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let W=f.logger;if(W)if(W.error)W.error("cron.watcher.failed",{error:J});else W.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs(f){return this.store.listSpecs(f)}getSpec(f){return this.store.getSpec(f)}listRuns(f){return this.store.listRuns(f)}getRun(f){return this.store.getRun(f)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns(f=20){return this.store.listRuns({status:"queued",limit:f})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent(f){return this.eventIngress.ingestEvent(f)}listEventLogs(f){return this.store.listEventLogs(f)}getEventLog(f){return this.store.getEventLog(f)}}import{readdir as cF,readFile as iQ}from"node:fs/promises";import{join as nQ}from"node:path";import{formatDisplayUserInput as dF,normalizeUserInput as rF}from"@cline/shared";import{resolveSessionDataDir as aQ}from"@cline/shared/storage";import{mkdirSync as EF,writeFileSync as SF}from"node:fs";import{dirname as kF}from"node:path";import{normalizeUserInput as IF}from"@cline/shared";import{nanoid as mF}from"nanoid";import{nanoid as bF}from"nanoid";function I1(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function L8(f,$){let J=I1(f),W=I1($),H=`${J}__${W}`;return H.length>180?H.slice(0,180):H}function nJ(f,$){let J=I1(f),W=I1($);return`${J}__teamtask__${W}__${bF(6)}`}function m1(f){let J=f.indexOf("__teamtask__");if(J<=0)return null;let W=f.slice(0,J),H=f.slice(J+12),Q=H.lastIndexOf("__");if(Q<=0)return null;let Z=H.slice(0,Q),j=H.slice(Q+2);if(!W||!Z||!j)return null;return{rootSessionId:W,agentId:Z,teamTaskId:j}}function h8(f){if(m1(f))return null;let $="__",J=f.indexOf($);if(J<=0)return null;let W=f.slice(0,J),H=f.slice(J+$.length);if(!W||!H)return null;return{rootSessionId:W,agentId:H}}function aJ(f){switch(f.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let $=String(f.reason??"").toLowerCase();if($.includes("cancel")||$.includes("abort")||$.includes("interrupt"))return"cancelled";if($.includes("fail")||$.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as i}from"zod";var CF=i.enum(D6),Df=i.object({version:i.literal(1),session_id:i.string().min(1),source:i.string().min(1),pid:i.number().int(),started_at:i.string().min(1),ended_at:i.string().min(1).optional(),exit_code:i.number().int().nullable().optional(),status:CF,interactive:i.boolean(),provider:i.string().min(1),model:i.string().min(1),cwd:i.string().min(1),workspace_root:i.string().min(1),team_name:i.string().min(1).optional(),enable_tools:i.boolean(),enable_spawn:i.boolean(),enable_teams:i.boolean(),prompt:i.string().optional(),metadata:i.record(i.string(),i.unknown()).optional(),messages_path:i.string().min(1).optional()});function xQ(f){if(!f)return!1;return Object.values(f).some(($)=>typeof $==="function")}function sJ(f,$){let J=[...f??[],...$??[]];if(J.length===0)return;let W=[],H=new Set;for(let Q of J){if(H.has(Q.name))continue;H.add(Q.name),W.push(Q)}return W}function gQ(f){return JSON.stringify(f,($,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function H0(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function tJ(f,$){let J={...f};J.id=H0(J.id)??mF();let W=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,H={id:H0(W?.id)??H0(J.modelId)??H0($?.id),provider:H0(W?.provider)??H0(J.providerId)??H0($?.provider),family:H0(W?.family)??H0($?.family)};if(delete J.providerId,delete J.modelId,H.id&&H.provider)J.modelInfo={id:H.id,provider:H.provider,...H.family?{family:H.family}:{}};else delete J.modelInfo;return J}function O8(f){return f.map(($)=>tJ($))}function z8(f,$,J=[]){let W=f.map((j,X)=>{let A=J[X],B=A?.role===j.role&&JSON.stringify(A.content)===JSON.stringify(j.content)?{...A,...j}:{...j};return tJ(B)}),H=J.length,Q=[];for(let j=H;j<W.length;j+=1)if(W[j]?.role==="assistant")Q.push(j);if(Q.length===0){let j=[...W].reverse().findIndex((X)=>X.role==="assistant");if(j===-1)return W;Q.push(W.length-1-j)}let Z=Q[Q.length-1];for(let j of Q){let X=W[j],A=X.metrics;if(!A&&j===Z){let P=$.usage;A={inputTokens:P.inputTokens,outputTokens:P.outputTokens,cacheReadTokens:P.cacheReadTokens??0,cacheWriteTokens:P.cacheWriteTokens??0,cost:P.totalCost}}W[j]={...tJ(X,{id:$.model.id,provider:$.model.provider,family:$.model.info?.family}),...A?{metrics:A}:{},ts:X.ts??$.endedAt.getTime()}}return W}function x1(f){return{sessionId:f.sessionId,source:f.source,pid:f.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??void 0,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:f.parentSessionId??void 0,parentAgentId:f.parentAgentId??void 0,agentId:f.agentId??void 0,conversationId:f.conversationId??void 0,isSubagent:f.isSubagent,prompt:f.prompt??void 0,metadata:f.metadata??void 0,messagesPath:f.messagesPath??void 0,updatedAt:f.updatedAt}}var xF=120;function Z$(f){let $=f?.trim();return $?$.slice(0,xF):void 0}function oJ(f){let $=IF(f??"").trim();if(!$)return;return Z$($.split(`
|
|
426
|
+
`)[0]?.trim())}function z0(f){if(!f)return;let $={...f},J=Z$(typeof $.title==="string"?$.title:void 0);if(J)$.title=J;else delete $.title;return Object.keys($).length>0?$:void 0}function g1(f){let $=z0(f.metadata)??{},J=f.title!==void 0?Z$(f.title):oJ(f.prompt);if(J)$.title=J;return Object.keys($).length>0?$:void 0}function eJ(f){let $=m1(f);if($)return{agent:"teammate",sessionId:$.rootSessionId,taskType:"team"};let J=h8(f);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:f}}function f5(f){return{version:1,updated_at:f.updatedAt,agent:f.context.agent,sessionId:f.context.sessionId,...f.context.taskType?{taskType:f.context.taskType}:{},messages:O8(f.messages),...f.systemPrompt?{system_prompt:f.systemPrompt}:{}}}function vQ(f,$,J){EF(kF(f),{recursive:!0}),SF(f,`${JSON.stringify(f5({updatedAt:$,context:J,messages:[]}),null,2)}
|
|
427
|
+
`,"utf8")}function uQ(f,$){return Df.parse({version:1,session_id:f.sessionId,source:f.source,pid:f.pid,started_at:f.startedAt,ended_at:$?.endedAt??f.endedAt??void 0,exit_code:$?.exitCode??f.exitCode??void 0,status:$?.status??f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName??void 0,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt??void 0,metadata:$?.metadata??f.metadata??void 0,messages_path:f.messagesPath??void 0})}async function cQ(f,$,J){let W=0;while(!0){let H=await f();if(H===void 0)return{updated:!1};let Q=await $(H);if(typeof Q==="object"&&Q!==null&&"updated"in Q&&Q.updated===!1){if(W+=1,W>=J)return Q;continue}return Q}}import{existsSync as gF}from"node:fs";import{readFile as vF}from"node:fs/promises";import{formatDisplayUserInput as dQ}from"@cline/shared";class v1{listeners=new Set;subscribe(f,$){let J={listener:f,sessionId:$?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit(f){let $=f.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$)continue;J.listener(f)}}get size(){return this.listeners.size}}async function N0(f){let $=f?.trim();if(!$||!gF($))return[];try{let J=(await vF($,"utf8")).trim();if(!J)return[];let W=JSON.parse(J);if(Array.isArray(W))return rQ(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let H=W.messages;if(Array.isArray(H))return rQ(H)}return[]}catch{return[]}}function uF(f){if(f.role!=="user")return f;if(typeof f.content==="string")return{...f,content:dQ(f.content)};return{...f,content:f.content.map(($)=>{if($.type!=="text"||typeof $.text!=="string")return $;return{...$,text:dQ($.text)}})}}function rQ(f){return f.map(uF)}function $5(f){return f?{...f}:void 0}async function lQ(f,$){if(!(f.hookName==="tool_call"||!!f.parent_agent_id))return;await $.queueSpawnRequest(f);let W=await $.upsertSubagentSessionFromHook(f);if(!W)return;await $.appendSubagentHookAudit(W,f),await $.applySubagentStatus(W,f)}function N8(f){if(typeof f!=="string")return;let $=f.trim();return $.length>0?$:void 0}function wf(f){let $=N8(f);if(!$)return;return $.toLowerCase()==="unknown"?void 0:$}function q8(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function lF(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return{...f}}function W5(f){let $=f??200;return Number.isFinite($)?Math.max(0,Math.floor($)):200}function pF(f){let $=f.match(/\d{13,}/g);if(!$||$.length===0)return 0;let J=0;for(let W of $){let H=Number.parseInt(W,10);if(Number.isFinite(H)&&H>J)J=H}return J}function H5(f){return{sessionId:f.session_id,source:f.source,pid:f.pid,startedAt:f.started_at,endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:f.status,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspace_root,teamName:f.team_name,enableTools:f.enable_tools,enableSpawn:f.enable_spawn,enableTeams:f.enable_teams,isSubagent:!1,prompt:f.prompt,metadata:f.metadata,messagesPath:f.messages_path,updatedAt:f.ended_at??f.started_at}}async function iF(f){let $=W5(f);if($===0)return[];let J=aQ(),H=(await cF(J,{withFileTypes:!0}).catch(()=>[])).filter((Z)=>Z.isDirectory()).map((Z)=>({entry:Z,recency:pF(Z.name.trim())})).sort((Z,j)=>j.recency-Z.recency||j.entry.name.localeCompare(Z.entry.name));return(await Promise.all(H.map(async({entry:Z})=>{let j=Z.name.trim();if(!j)return;let X=nQ(J,j,`${j}.json`),A=await iQ(X,"utf8").catch(()=>{return});if(!A)return;let P;try{P=JSON.parse(A)}catch{return}let B=Df.safeParse(P);if(!B.success)return;return H5(B.data)}))).filter((Z)=>Boolean(Z)).sort((Z,j)=>j.startedAt.localeCompare(Z.startedAt)).slice(0,$)}async function nF(f,$){let J=W5($);if(J===0)return await f.listSessions(0),[];return(await f.listSessions(J)).slice(0,J)}function aF(f){if(typeof f==="string")return f.trim();let $=[];for(let J of f){if(!J||typeof J!=="object")continue;let W=J;if(W.type!=="text")continue;let H=W.text?.trim();if(H)$.push(H)}return $.join(`
|
|
428
|
+
`).trim()}function pQ(f){return f.replace(/\s+/g," ").trim()}function tF(f,$){if(f.length<=$)return f;return`${f.slice(0,Math.max(0,$-3)).trimEnd()}...`}function sF(f){for(let $ of["user","assistant"])for(let J of f){if(J.role!==$)continue;let W=pQ(aF(J.content));if(!W)continue;let H=$==="user"?pQ(dF(W)):W,Q=rF(H.split(`
|
|
429
|
+
`)[0]??H);return tF(Q,50)}return}function oF(f){let $=0;for(let J of f)$+=q8(J.metrics?.cost)??0;return $}function eF(f){let $,J;for(let W=f.length-1;W>=0;W-=1){let H=f[W];if(!$)$=wf(H.modelInfo?.provider);if(!J)J=wf(H.modelInfo?.id);if($&&J)break}return{provider:$,model:J}}function fK(f){return wf(f?.provider)??wf(f?.provider&&typeof f.provider==="object"&&!Array.isArray(f.provider)?f.provider.id:void 0)}function $K(f){return wf(f?.model)??wf(f?.model&&typeof f.model==="object"&&!Array.isArray(f.model)?f.model.id:void 0)}function J5(f,$){let J=lF(f.metadata),W=N8($?.title)??N8(J?.title),H=q8($?.totalCost)??q8(J?.totalCost),Q=J||W!==void 0||H!==void 0?{...J??{},...W!==void 0?{title:W}:{},...H!==void 0?{totalCost:H}:{}}:void 0;return{...f,provider:wf($?.provider)??wf(f.provider)??fK(J)??"",model:wf($?.model)??wf(f.model)??$K(J)??"",metadata:Q}}async function JK(f,$){return await Promise.all($.map(async(J)=>{let W=J5(J),H=Boolean(N8(W.metadata?.title)),Q=Boolean(wf(W.provider)),Z=Boolean(wf(W.model)),j=q8(W.metadata?.totalCost),X=j!==void 0&&j>0;if(H&&Q&&Z&&X)return W;let A=await f.readSessionMessages(J.sessionId);if(A.length===0)return W;let P=eF(A),B=oF(A);return J5(J,{title:H?void 0:sF(A),provider:Q?void 0:P.provider,model:Z?void 0:P.model,totalCost:X||B<=0?void 0:B})}))}async function Q5(f,$={}){let J=W5($.limit),W=await nF(f,J),H=$.includeManifestFallback===!0&&W.length<J?await iF(Math.min(Math.max(J*2,100),500)):[],Q=new Map;for(let j of[...W,...H]){if(Q.has(j.sessionId))continue;Q.set(j.sessionId,j)}let Z=H.length===0?W:Array.from(Q.values()).sort((j,X)=>X.startedAt.localeCompare(j.startedAt)).slice(0,J);if($.hydrate===!1)return Z.map((j)=>J5(j));return await JK(f,Z)}async function WK(f){let $=f.trim();if(!$)return;let J=nQ(aQ(),$,`${$}.json`),W=await iQ(J,"utf8").catch(()=>{return});if(!W)return;try{let H=Df.safeParse(JSON.parse(W));return H.success?H.data.messages_path:void 0}catch{return}}async function HK(f,$={}){let J=new Map;return await Q5({listSessions:async(H)=>{let Q=await f.listSessions(H);J.clear();for(let Z of Q)J.set(Z.sessionId,Z);return Q.map(x1)},readSessionMessages:async(H)=>{let Q=J.get(H)?.messagesPath??await WK(H);return await N0(Q)}},$)}import{createSessionId as $y,resolveHubCommandTimeoutMs as Jy}from"@cline/shared";import{spawn as CK}from"node:child_process";import{closeSync as EK,mkdirSync as SK,openSync as kK}from"node:fs";import{basename as IK,dirname as mK,join as xK}from"node:path";import{fileURLToPath as gK}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as vK,isHubDaemonProcess as X7,withResolvedClineBuildEnv as uK}from"@cline/shared";import{createHash as QK,randomBytes as ZK}from"node:crypto";import{existsSync as jK}from"node:fs";import{chmod as XK,mkdir as Z5,readFile as $7,rm as j5,writeFile as J7}from"node:fs/promises";import{dirname as W7,join as X5}from"node:path";import{resolveClineDataDir as A5,resolveClineDir as fb}from"@cline/shared/storage";var sQ="0.0.39";var oQ={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:sQ,repository:{type:"git",url:"https://github.com/cline/sdk",directory:"packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"rm -rf dist && bun run ./bun.mts && bun tsc -p tsconfig.build.json",clean:"rm -rf dist node_modules",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^1.21.7","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"^3.32.3",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var AK="CLINE_HUB_DISCOVERY_PATH",PK="CLINE_HUB_BUILD_ID",eQ=30000,BK=15000,YK=100;function VK(f){return f.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function RK(f){return QK("sha256").update(f).digest("hex").slice(0,12)}function FK(f){if(!Number.isInteger(f)||!f||f<=0)return!1;try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $?String($.code)==="EPERM":!1}}function H7(){return ZK(32).toString("hex")}function KK(f){return new Promise(($)=>setTimeout($,f))}function yK(f){return`${f}.lock`}async function UK(f){try{let $=JSON.parse(await $7(X5(f,"owner.json"),"utf8"));if(typeof $.pid!=="number"||typeof $.acquiredAt!=="string")return;return{pid:$.pid,acquiredAt:$.acquiredAt}}catch{return}}async function f7(f){await j5(f,{recursive:!0,force:!0}).catch(()=>{return})}function d$(){return process.env[PK]?.trim()||String(oQ.version)}function j$(f=process.argv[1]?.trim()||process.cwd()){let $=`hub-${RK(f)}`,J=process.env[AK]?.trim()||X5(A5(),"locks","hub","owners",`${VK($)}.json`);return{ownerId:$,discoveryPath:J}}function Jb(f=`hub-${Date.now().toString(36)}`){return j$(f)}async function Yf(f){try{let $=JSON.parse(await $7(f,"utf8"));if(typeof $.hubId!=="string"||typeof $.protocolVersion!=="string"||typeof $.authToken!=="string"||typeof $.host!=="string"||typeof $.port!=="number"||typeof $.url!=="string"||typeof $.startedAt!=="string"||typeof $.updatedAt!=="string")return;return{hubId:$.hubId,protocolVersion:$.protocolVersion,buildId:typeof $.buildId==="string"?$.buildId:void 0,authToken:$.authToken,host:$.host,port:$.port,url:$.url,pid:typeof $.pid==="number"?$.pid:void 0,startedAt:$.startedAt,updatedAt:$.updatedAt}}catch{return}}async function Q7(f,$){await Z5(W7(f),{recursive:!0}),await j5(f,{force:!0}).catch(()=>{return}),await J7(f,`${JSON.stringify($,null,2)}
|
|
430
|
+
`,{encoding:"utf8",mode:384}),await XK(f,384)}async function pf(f){await j5(f,{force:!0}).catch(()=>{return})}async function Z7(f,$){let J=yK(f);await Z5(W7(J),{recursive:!0});let W=Date.now()+BK;while(!0)try{await Z5(J,{recursive:!1}),await J7(X5(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
|
|
431
|
+
`,"utf8");try{return await $()}finally{await f7(J)}}catch(H){if((H instanceof Error&&"code"in H?String(H.code):"")!=="EEXIST")throw H;let Z=await UK(J),j=Z?Date.now()-Date.parse(Z.acquiredAt):eQ+1;if(!Z||!FK(Z.pid)||j>eQ){await f7(J);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${J}`);await KK(YK)}}async function Kf(f){try{let $=await fetch(GK(f));if(!$.ok)return;return await $.json()}catch{return}}function Q0(f,$,J="/hub"){return new URL(`ws://${f}:${$}${J}`).toString()}function GK(f){let $=new URL(f);return $.protocol=$.protocol==="wss:"?"https:":"http:",$.pathname="/health",$.search="",$.toString()}function Wb(f){return jK(f)}import{CLINE_HUB_DEV_PORT as TK,CLINE_HUB_PORT as DK,resolveClineBuildEnv as _K}from"@cline/shared";var MK="CLINE_HUB_HOST",LK="CLINE_HUB_PORT",hK="CLINE_HUB_PATHNAME",OK="127.0.0.1",zK=DK,NK="/hub";function j7(f){return _K(f)==="development"?TK:zK}function qK(f={}){return(f.env??process.env)[MK]?.trim()||OK}function w8(f={}){let J=(f.env??process.env)[LK]?.trim();if(!J)return j7(f);let W=Number.parseInt(J,10);if(!Number.isInteger(W)||W<1||W>65535)return j7(f);return W}function wK(f={}){return(f.env??process.env)[hK]?.trim()||NK}function q0(f={},$={}){return{host:f.host??qK($),port:f.port??w8($),pathname:f.pathname??wK($)}}var bK="shared:cline";function Ab(f){let $=J$(f.trim());return j$(`workspace:${$||f.trim()}`)}function yf(f=bK){return j$(f)}var cK=8000,dK=200,rK=3000,lK=100,pK=[100,250,500,1000,2000],iK="--cline-hub-daemon";function nK(f){return[...f.host?["--host",f.host]:[],...typeof f.port==="number"?["--port",String(f.port)]:[],...f.pathname?["--pathname",f.pathname]:[]]}function aK(){try{let f=xK(A5(),"logs","hub-daemon.log");return SK(mK(f),{recursive:!0}),{fd:kK(f,"a"),logPath:f}}catch{return}}function u1(f){let $=f.buildId?.trim();return!!$&&$===d$()}async function tK(f,$){let J=Date.now()+$;while(Date.now()<J){if(!(await Kf(f).catch(()=>{return}))?.url)return!0;await new Promise((H)=>setTimeout(H,lK))}return!1}async function c1(f,$){if(u1(f))return;if(await P5(f.url,f.authToken).catch(()=>!1),f.pid)try{process.kill(f.pid,"SIGTERM")}catch{}await tK(f.url,rK),await pf($).catch(()=>{return})}function sK(){let f=import.meta.url.endsWith(".ts")?"ts":"js";return gK(new URL(`./entry.${f}`,import.meta.url))}function oK(f,$){let J=sK(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let H=IK(W).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),Z=H&&J.toLowerCase().endsWith(".ts"),j=Q?[iK]:[...Z?["--conditions=development"]:[],J];return{launcher:W,args:[...j,"--cwd",f,...nK($)],cwd:f,env:{...uK(process.env),CLINE_NO_INTERACTIVE:"1",[vK]:"1"}}}function eK(f){if(!f||typeof f!=="object")return!1;if(("code"in f?f.code:void 0)==="ETXTBSY")return!0;let J="message"in f?f.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function fy(f,$={}){if(X7())return;let J=oK(f,$),W=aK();try{CK(J.launcher,J.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(W)EK(W.fd)}}async function b8(f,$={}){for(let J=0;;J++)try{fy(f,$);return}catch(W){let H=pK[J];if(!eK(W)||H===void 0)throw W;await new Promise((Q)=>setTimeout(Q,H))}}function A7(f,$={}){if(X7())return;let J=yf(),W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),H=q0($),Q=Q0(H.host,H.port,H.pathname);Yf(J.discoveryPath).then(async(Z)=>{if(Z?.url){let P=await Kf(Z.url);if(P?.url&&u1(P)&&await w0(P.url,{authToken:Z.authToken}))return;if(P?.url)await c1({...P,authToken:Z.authToken},J.discoveryPath);else await pf(J.discoveryPath).catch(()=>{return})}let j=await Kf(Q);if(j?.url)await c1(j,J.discoveryPath);let A=!W&&H.port!==0?{...H,port:0}:H;await b8(f,A)}).catch(()=>{})}async function Tb(f,$={}){let J=yf(),W=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),H=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=q0($),Z=Q0(Q.host,Q.port,Q.pathname),j=(V)=>{if(!W)r$(V.url,V.authToken);return V},X=await Yf(J.discoveryPath);if(X?.url){let V=await Kf(X.url);if(V?.url&&u1(V)&&await w0(V.url,{authToken:X.authToken}))return j({url:V.url,authToken:X.authToken});if(V?.url)await c1({...V,authToken:X.authToken},J.discoveryPath);else await pf(J.discoveryPath).catch(()=>{return})}let A=await Kf(Z);if(A?.url)await c1(A,J.discoveryPath);let B=!H&&Q.port!==0?{...Q,port:0}:Q;await b8(f,B);let Y=Date.now()+cK;while(Date.now()<Y){let V=await Yf(J.discoveryPath);if(V?.url){let U=await Kf(V.url);if(U?.url&&u1(U)&&await w0(U.url,{authToken:V.authToken}))return j({url:U.url,authToken:V.authToken})}let R=await Kf(Z);if(R?.url&&!u1(R))await c1(R,J.discoveryPath);await new Promise((U)=>setTimeout(U,dK))}throw Error("Timed out waiting for detached hub startup.")}function Wy(){let f=globalThis.WebSocket;if(!f)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return f}function R7(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();if(f&&typeof f==="object"&&"data"in f&&typeof f.data<"u")return R7(f.data);return String(f)}function Hy(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString("utf8");if(f instanceof ArrayBuffer)return Buffer.from(f).toString("utf8");return""}function P7(f){let $=f,J=Hy($.reason);return new bf("hub_connection_closed",$.code||J?`Hub connection closed (code=${$.code??0}${J?`, reason=${J}`:""})`:B5,{closeCode:$.code,closeReason:J||void 0})}function Qy(f,$){if(f instanceof bf)return f;if(f instanceof Error)return new bf("hub_connect_failed",f.message);if(f&&typeof f==="object"&&"error"in f&&f.error instanceof Error)return new bf("hub_connect_failed",f.error.message);let J=f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"?f.message.trim():"";if(J)return new bf("hub_connect_failed",J);let W=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return new bf("hub_connect_failed",W?`Failed to connect to hub at ${$.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${$.toString()}.`)}var Zy=8000,jy=200,B7="*",Y7=8000,Xy="cline-hub-auth.",F7=new Map,K7=new Set,Ay=3000,Py=3000,By=100,B5="Hub connection closed",Yy=250,Vy=5000,V7=0.5;class bf extends Error{code;details;constructor(f,$,J){super($);this.code=f;this.details=J;this.name="HubTransportError"}}function Ry(f){return f instanceof bf}class C8 extends Error{command;code;constructor(f,$,J){super(J);this.command=f;this.code=$;this.name="HubCommandError"}}function y7(f,$){return f instanceof C8&&f.code==="hub_command_timeout"&&($===void 0||f.command===$)}function U7(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=R5(f.toString());return J?F7.get(J):void 0}function Fy(f){try{let J=new URL(f).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function R5(f){if(!Fy(f))return;let $=new URL(l$(f));return $.search="",$.hash="",$.toString()}function Y5(f){let $=R5(f);return!!$&&K7.has($)}function r$(f,$){let J=R5(f);if(J){if(K7.add(J),$?.trim())F7.set(J,$)}return f}class Z0{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new bf("hub_connection_closed",B5);sawSocketClose=!1;registered=!1;constructor(f){this.options=f;this.clientId=f.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=f.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let f=new URL(this.currentUrl),$=this.options.authToken?.trim()||U7(f);f.hash="";let W=new(Wy())(f.toString(),$?[`${Xy}${$}`]:void 0);this.socket=W;let H=!1;this.connectPromise=new Promise((Q,Z)=>{let j=!1,X=setTimeout(()=>{if(j)return;j=!0,H=!0,this.lastCloseError=new bf("hub_connect_timeout",`Timed out connecting to hub after ${Y7}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}Z(this.lastCloseError)},Y7);W.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(X),Q()}),W.addEventListener("error",(A)=>{if(j)return;j=!0,clearTimeout(X),this.lastCloseError=Qy(A,f),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)}),W.addEventListener("close",(A)=>{if(j)return;if(j=!0,clearTimeout(X),!H)this.lastCloseError=P7(A),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Z(this.lastCloseError)})}),W.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(R7(Q)))}),W.addEventListener("close",(Q)=>{if(this.socket!==W)return;if(!H)this.lastCloseError=P7(Q),this.sawSocketClose=!0;this.registered=!1;for(let Z of this.pendingReplies.values())Z.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe(f,$){let J=$?.sessionId?.trim()||void 0,W={listener:f,sessionId:J};return this.listeners.add(W),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(W))return;this.adjustSubscriptionCount(J,-1)}}async command(f,$,J,W){let H=0,Q=f!=="client.register"&&f!=="client.unregister";while(!0)try{return await this.commandOnce(f,$,J,W)}catch(Z){if(!Q||H>=1||!await this.recoverLocalHubTransport(Z))throw Z;H+=1}}async commandOnce(f,$,J,W){await this.connect();let H=$y("hubreq_"),Q=Jy(f,W?.timeoutMs),Z=new Promise((X,A)=>{let P=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(H))return;A(new C8(f,"hub_command_timeout",`Hub command ${f} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${H}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(H,{resolve:(B)=>{if(P)clearTimeout(P);X(B)},reject:(B)=>{if(P)clearTimeout(P);A(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:f,requestId:H,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:$}})}catch(X){throw this.pendingReplies.delete(H),X}let j=await Z;if(!j.ok)throw new C8(f,j.error?.code,j.error?.message??`Hub command ${f} failed`);return j}async recoverLocalHubTransport(f){if(!Y5(this.currentUrl)||!Ry(f))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let $=await d1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!$)return!1;return this.currentUrl=$,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let f=Math.min(Yy*2**this.reconnectAttempt,Vy),$=Math.round(f*(1-V7)+Math.random()*f*V7);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},$)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Y5(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let f=await d1({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if(f){this.currentUrl=f,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let f=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!f)return;this.lastCloseError=new bf("hub_connection_closed",B5),this.sawSocketClose=!1;for(let $ of this.pendingReplies.values())$.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{f.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame(f){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new bf("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify(f))}sendSubscriptionFrame(f,$){this.sendFrame({kind:f,clientId:this.clientId,...$?{sessionId:$}:{}})}adjustSubscriptionCount(f,$){let J=this.subscriptionKeyForSessionId(f),W=(this.subscriptionCounts.get(J)??0)+$;if(W<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if($<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",f);return}if(this.subscriptionCounts.set(J,W),$>0&&W===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",f)}subscriptionKeyForSessionId(f){return f??B7}subscriptionSessionIdFromKey(f){return f===B7?void 0:f}handleFrame(f){switch(f.kind){case"reply":{let $=f.envelope.requestId;if(!$)return;let J=this.pendingReplies.get($);if(!J)return;this.pendingReplies.delete($),J.resolve(f.envelope);return}case"event":for(let $ of this.listeners){if($.sessionId&&$.sessionId!==f.envelope.sessionId?.trim())continue;$.listener(f.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function l$(f){let $=new URL(f);if($.protocol==="http:")$.protocol="ws:";else if($.protocol==="https:")$.protocol="wss:";return $.toString()}async function w0(f,$){let J=new Z0({url:f,authToken:$?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function V5(f,$){let J=l$(f),W=await Kf(J);if(!W)return{status:"unreachable",url:J};let H=d$(),Q=W.buildId?.trim();if(!Q||Q!==H)return{status:"build_mismatch",url:J};if($?.verifyConnection===!0&&!await w0(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd,authToken:$.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function Ky(f){let $=Date.now()+Zy;while(Date.now()<$){let J=await Yf(f.discoveryPath);if(J?.url){let W=await V5(J.url,{verifyConnection:!0,authToken:J.authToken});if(W.status==="compatible")return r$(W.url,J.authToken)}await new Promise((W)=>setTimeout(W,jy))}return}async function yy(f){let $=Date.now()+Py;while(Date.now()<$){if(!(await Kf(f).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,By))}return!1}function Uy(f,$){try{return l$(f)===l$($)}catch{return!1}}function Gy(f){return(f&&typeof f==="object"&&Array.isArray(f.sessions)?f.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let W=J;if(W.status==="running"||W.status==="idle")return!0;return Array.isArray(W.participants)&&W.participants.length>0})}async function Ty(f,$,J){let W=new Z0({url:f,authToken:$,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let H=await W.command("session.list",{limit:500},void 0,{timeoutMs:Ay});return!Gy(H.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function F5(f={}){if(f.endpoint?.trim()){let H=await V5(f.endpoint);return H.status==="compatible"?H.url:void 0}let $=yf(),J=await Yf($.discoveryPath);if(!J?.url)return;let W=await V5(J.url);if(W.status==="compatible")return r$(W.url,J.authToken);if(W.status==="build_mismatch")await pf($.discoveryPath).catch(()=>{return});return}async function d1(f={}){let $=await F5(f);if($&&await w0($,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return $;if(f.endpoint?.trim())return;let J=yf();return await b8(f.workspaceRoot??process.cwd()),await Ky(J)}async function P5(f,$){let J=new URL(f),W=$?.trim()||U7(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 Dy(){let f=yf(),$=await Yf(f.discoveryPath);if(!$?.url)return!1;try{if(await P5($.url,$.authToken))return!0}catch{}return!1}async function G7(f){if(!Y5(f.url))return;let $=yf(),J=await Yf($.discoveryPath);if(!J?.url||!Uy(J.url,f.url))return;if(!await Ty(J.url,J.authToken,{workspaceRoot:f.workspaceRoot,cwd:f.cwd}))return;if(!await Dy())return;if(!await yy(J.url))return;return await pf($.discoveryPath).catch(()=>{return}),await d1({workspaceRoot:f.workspaceRoot,cwd:f.cwd})}import{createSessionId as T7,HUB_CHECKPOINT_CAPABILITY as hy,HUB_COMPACTION_CAPABILITY as Oy,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as zy,HUB_HOOK_CAPABILITY_PREFIX as Ny,HUB_MISTAKE_LIMIT_CAPABILITY as qy,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as wy,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as by,isHubToolExecutorName as Cy}from"@cline/shared";function _y(f){return f?JSON.parse(JSON.stringify(f)):void 0}function My(f){return f?JSON.parse(JSON.stringify(f)):void 0}function Ly(f){let $=f?.checkpoint&&typeof f.checkpoint==="object"&&!Array.isArray(f.checkpoint)?f.checkpoint:void 0,W=(Array.isArray($?.history)?$.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let j=typeof Z.ref==="string"?Z.ref.trim():"",X=Number(Z.createdAt),A=Number(Z.runCount);if(!j||!Number.isFinite(X)||!Number.isInteger(A))return[];return[{ref:j,createdAt:X,runCount:A,...Z.kind==="stash"||Z.kind==="commit"?{kind:Z.kind}:{}}]}),H=W.at(-1),Q=f?.checkpointEnabled===!0?!0:void 0;if(!Q&&W.length===0)return;return{...Q?{enabled:Q}:{},...H?{latest:H}:{},history:W}}function b0(f){let{session:$}=f,J=_y($.metadata);return{version:1,sessionId:$.sessionId,source:$.source,status:$.status,createdAt:$.startedAt,updatedAt:$.updatedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,interactive:$.interactive,workspace:{cwd:$.cwd,root:$.workspaceRoot},model:{providerId:$.provider,modelId:$.model},capabilities:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams},lineage:{...$.parentSessionId?{parentSessionId:$.parentSessionId}:{},...$.parentAgentId?{parentAgentId:$.parentAgentId}:{},...$.agentId?{agentId:$.agentId}:{},...$.conversationId?{conversationId:$.conversationId}:{},isSubagent:$.isSubagent},...$.teamName?{team:{name:$.teamName}}:{},...$.prompt?{prompt:$.prompt}:{},...J?{metadata:J}:{},...$.messagesPath?{artifacts:{messagesPath:$.messagesPath}}:{},...f.messages?{messages:My(f.messages)}:{},...f.usage?{usage:{...f.usage}}:{},...f.aggregateUsage?{aggregateUsage:{...f.aggregateUsage}}:{},...(()=>{let W=Ly(J);return W?{checkpoint:W}:{}})()}}function K5(f){return{sessionId:f.sessionId,parentSessionId:f.lineage.parentSessionId,agentId:f.lineage.agentId,parentAgentId:f.lineage.parentAgentId,conversationId:f.lineage.conversationId,isSubagent:f.lineage.isSubagent,source:f.source,startedAt:f.createdAt,endedAt:f.endedAt??void 0,exitCode:f.exitCode??void 0,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspaceRoot:f.workspace.root,teamName:f.team?.name,enableTools:f.capabilities.enableTools,enableSpawn:f.capabilities.enableSpawn,enableTeams:f.capabilities.enableTeams,prompt:f.prompt,metadata:f.metadata,updatedAt:f.updatedAt,messagesPath:f.artifacts?.messagesPath}}function p$(f){if(!f)return;return JSON.parse(JSON.stringify(f))}var Ey=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function D7(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return JSON.parse(JSON.stringify(f))}function _7(f){if(!f)return;let{userInstructionService:$,...J}=f;return JSON.parse(JSON.stringify(J))}function M7(f){let $=f&&typeof f==="object"&&!Array.isArray(f)?f:{};return{agentId:typeof $.agentId==="string"?$.agentId:"",conversationId:typeof $.conversationId==="string"?$.conversationId:"",iteration:typeof $.iteration==="number"?$.iteration:0,metadata:$.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)?$.metadata:void 0}}function X$(f,$,J){f.manifest.push($),f.handlers.set($.capabilityName,J)}function L7(f,$){let J={manifest:[],handlers:new Map};for(let H of Object.keys($.toolExecutors??{}).filter(Cy)){let Q=$.toolExecutors?.[H];if(typeof Q!=="function")continue;X$(J,{kind:"toolExecutor",executor:H,capabilityName:`${wy}${H}`},async({payload:Z,abortSignal:j})=>{let X=Array.isArray(Z.args)?[...Z.args]:[],A={...M7(Z.context),signal:j};return{result:await Q(...X,A)}})}for(let H of f?.extraTools??[])X$(J,{kind:"tool",name:H.name,description:H.description,inputSchema:p$(H.inputSchema)??{},...H.lifecycle?{lifecycle:p$(H.lifecycle)}:{},capabilityName:`${zy}${H.name}`},async({payload:Q,abortSignal:Z,progress:j})=>{let X={...M7(Q.context),signal:Z};return{result:await H.execute(Q.input,{...X,emitUpdate:(P)=>{j({update:P})}})}});let W=f?.hooks;if(W)for(let H of Ey){let Q=W[H];if(typeof Q!=="function")continue;X$(J,{kind:"hook",name:H,capabilityName:`${Ny}${H}`},async({payload:Z})=>({control:await Q(Z.context)}))}if(f?.compaction?.compact){let H=f.compaction.compact;X$(J,{kind:"compaction",capabilityName:Oy,config:D7(f.compaction)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.checkpoint?.createCheckpoint){let H=f.checkpoint.createCheckpoint;X$(J,{kind:"checkpoint",capabilityName:hy,config:D7(f.checkpoint)},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.onConsecutiveMistakeLimitReached){let H=f.onConsecutiveMistakeLimitReached;X$(J,{kind:"mistakeLimit",capabilityName:qy},async({payload:Q})=>({result:await H(Q.context)}))}if(f?.userInstructionService){let H=f.userInstructionService;X$(J,{kind:"userInstructionService",capabilityName:by},async()=>{return await H.start().catch(()=>{}),{snapshot:{records:{skill:H.listRecords("skill"),rule:H.listRecords("rule"),workflow:H.listRecords("workflow")},runtimeCommands:H.listRuntimeCommands()}}})}return J}function Sy(f){if(typeof f==="string"&&f.trim())return f.trim();if(f instanceof Error)return f.message;if(f&&typeof f==="object"&&"message"in f){let $=f.message;if(typeof $==="string"&&$.trim())return $.trim()}return"Capability request was cancelled."}function ky(f){if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return f}}function Iy(f){return f==="completed"||f==="max_iterations"||f==="aborted"||f==="mistake_limit"||f==="error"}function my(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=typeof $.inputTokens==="number"?$.inputTokens:void 0,W=typeof $.outputTokens==="number"?$.outputTokens:void 0;if(J===void 0||W===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:typeof $.cacheReadTokens==="number"?$.cacheReadTokens:0,cacheWriteTokens:typeof $.cacheWriteTokens==="number"?$.cacheWriteTokens:0,totalCost:typeof $.totalCost==="number"?$.totalCost:0}}function h7(f){if(!f)return;return{inputTokens:typeof f.inputTokens==="number"?f.inputTokens:0,outputTokens:typeof f.outputTokens==="number"?f.outputTokens:0,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function U5(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function C0(f,$){return U5(f?.[$])??0}function xy(f){let $=f?.delta&&typeof f.delta==="object"?f.delta:void 0,J=f?.totals&&typeof f.totals==="object"?f.totals:void 0,W=f?.agent&&typeof f.agent==="object"?f.agent:void 0,H=W?.teamRole==="teammate"||W?.teamRole==="lead"?W.teamRole:void 0;return{event:{type:"usage",agentId:typeof W?.agentId==="string"?W.agentId:void 0,conversationId:typeof W?.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W?.parentAgentId==="string"?W.parentAgentId:void 0,inputTokens:C0($,"inputTokens"),outputTokens:C0($,"outputTokens"),cacheReadTokens:C0($,"cacheReadTokens"),cacheWriteTokens:C0($,"cacheWriteTokens"),cost:U5($?.totalCost),totalInputTokens:C0(J,"inputTokens"),totalOutputTokens:C0(J,"outputTokens"),totalCacheReadTokens:C0(J,"cacheReadTokens"),totalCacheWriteTokens:C0(J,"cacheWriteTokens"),totalCost:U5(J?.totalCost)},teamAgentId:typeof W?.teamAgentId==="string"?W.teamAgentId:void 0,teamRole:H}}function gy(f){let $=f?.result&&typeof f.result==="object"&&!Array.isArray(f.result)?f.result:void 0,J=f?.reason??$?.finishReason,W=Iy(J)?J:J==="failed"?"error":"completed",H=my(f?.usage??$?.usage);return{type:"done",reason:W,text:typeof f?.text==="string"?f.text:typeof $?.text==="string"?$.text:"",iterations:typeof f?.iterations==="number"?f.iterations:typeof $?.iterations==="number"?$.iterations:0,usage:H}}function y5(f,$){return f.error?.message??`hub command failed: ${$}`}function r1(f){switch(f){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function N7(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):void 0;return{sessionId:f.sessionId,parentSessionId:typeof $?.parentSessionId==="string"?$.parentSessionId:void 0,agentId:f.runtimeSession?.agentId||(typeof $?.agentId==="string"?$.agentId:void 0),parentAgentId:typeof $?.parentAgentId==="string"?$.parentAgentId:void 0,conversationId:typeof $?.conversationId==="string"?$.conversationId:void 0,isSubagent:typeof $?.isSubagent==="boolean"?$.isSubagent:!1,source:typeof $?.source==="string"?$.source:Rf.CORE,pid:typeof $?.pid==="number"?$.pid:void 0,startedAt:new Date(f.createdAt).toISOString(),endedAt:r1(f.status)==="running"?void 0:new Date(f.updatedAt).toISOString(),exitCode:r1(f.status)==="completed"?0:r1(f.status)==="failed"?1:void 0,status:r1(f.status),interactive:$?.interactive===!0,provider:typeof $?.provider==="string"?$.provider:"hub",model:typeof $?.model==="string"?$.model:"hub",cwd:f.cwd?.trim()||f.workspaceRoot,workspaceRoot:f.workspaceRoot,teamName:typeof $?.teamName==="string"?$.teamName:void 0,enableTools:f.runtimeOptions?.enableTools??$?.enableTools===!0,enableSpawn:f.runtimeOptions?.enableSpawn??$?.enableSpawn===!0,enableTeams:f.runtimeOptions?.enableTeams??$?.enableTeams===!0,prompt:typeof $?.prompt==="string"?$.prompt:void 0,metadata:$,updatedAt:new Date(f.updatedAt).toISOString(),messagesPath:typeof $?.messagesPath==="string"?$.messagesPath:void 0,hookPath:typeof $?.hookPath==="string"?$.hookPath:void 0}}function A$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;return $.version===1&&typeof $.sessionId==="string"?JSON.parse(JSON.stringify($)):void 0}function vy(f){let $=A$(f?.snapshot);if($)return K5($);let J=f?.session;return J?N7(J):void 0}function O7(f,$,J){let W=J?.workspaceRoot?.trim()||$.config.workspaceRoot||$.config.cwd;return Df.parse({version:1,session_id:f,source:$.source??Rf.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:r1(J?.status),interactive:$.interactive===!0,provider:$.config.providerId,model:$.config.modelId,cwd:J?.cwd?.trim()||$.config.cwd,workspace_root:W,team_name:$.config.teamName,enable_tools:$.config.enableTools,enable_spawn:$.config.enableSpawnAgent,enable_teams:$.config.enableAgentTeams,prompt:$.prompt?.trim()||void 0,metadata:$.sessionMetadata&&Object.keys($.sessionMetadata).length>0?$.sessionMetadata:void 0})}function z7(f,$){return Df.parse({version:1,session_id:f.sessionId,source:f.source,pid:process.pid,started_at:f.createdAt,status:f.status,interactive:f.interactive,provider:f.model.providerId,model:f.model.modelId,cwd:f.workspace.cwd,workspace_root:f.workspace.root,team_name:f.team?.name,enable_tools:f.capabilities.enableTools,enable_spawn:f.capabilities.enableSpawn,enable_teams:f.capabilities.enableTeams,prompt:(f.prompt??$.prompt?.trim())||void 0,metadata:f.metadata,messages_path:f.artifacts?.messagesPath})}class P${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new v1;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;constructor(f,$){this.clientContext=$,this.clientOptions={authToken:f.authToken,clientType:f.clientType??"core-hub-runtime",displayName:f.displayName??"core hub runtime",workspaceRoot:$?.workspaceRoot,cwd:$?.cwd},this.defaultCapabilities=Ff(f.capabilities)??{},this.runtimeAddress=f.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient(f.url)}createClient(f){return new Z0({...this.clientOptions,url:f})}async replaceClient(f){let $=this.client;this.client=this.createClient(f),this.runtimeAddress=f,await Promise.resolve($.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock(f){if(!y7(f,"session.create"))return!1;let $=await G7({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!$)return!1;return await this.replaceClient($),!0}registerPlannedSession(f,$,J){if(this.sessionCapabilities.set(f,$),J.size>0)this.sessionClientContributionHandlers.set(f,J);this.ensureSessionSubscription(f)}cleanupPlannedSession(f){this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f)}async connect(){await this.client.connect()}async startSession(f){let $=this.resolveCapabilities(f),J=L7(f.localRuntime,$),W=f.config.sessionId?.trim()||T7(),H=()=>this.client.command("session.create",{workspaceRoot:f.config.workspaceRoot?.trim()||f.config.cwd,cwd:f.config.cwd,sessionConfig:p$({...f.config,sessionId:W}),metadata:{...f.sessionMetadata??{},source:f.source??Rf.CORE,provider:f.config.providerId,model:f.config.modelId,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,teamName:f.config.teamName,prompt:f.prompt,interactive:f.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...f.localRuntime?.configExtensions?{configExtensions:f.localRuntime.configExtensions}:{}},toolPolicies:p$(f.toolPolicies),initialMessages:f.initialMessages});this.registerPlannedSession(W,$,J.handlers);let Q;try{Q=await H()}catch(A){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(A)){this.registerPlannedSession(W,$,J.handlers);try{Q=await H()}catch(P){throw this.cleanupPlannedSession(W),P}}else throw A}let Z=A$(Q.payload?.snapshot),j=Q.payload?.session,X=(Z?.sessionId??j?.sessionId)?.trim();if(!X)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(X!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(X,$,J.handlers);return{sessionId:X,manifest:Z?z7(Z,f):O7(X,f,j),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.start)throw Error("start is required when restore.messages is true");let W=f.start,H=W?this.resolveCapabilities(W):void 0,Q=W?L7(W.localRuntime,H??{}):{manifest:[],handlers:new Map},Z=W?W.config.sessionId?.trim()||T7():void 0;if(Z&&H)this.sessionCapabilities.set(Z,H);if(Z&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(Z,Q.handlers),this.ensureSessionSubscription(Z);let j;try{j=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...W?{workspaceRoot:W.config.workspaceRoot?.trim()||W.config.cwd,cwd:W.config.cwd??f.cwd,sessionConfig:p$({...W.config,sessionId:Z}),metadata:{...W.sessionMetadata??{},source:W.source??Rf.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:p$(W.toolPolicies)}:{}},$)}catch(V){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw V}if(!j.ok){let V=typeof j.payload?.error==="string"?j.payload.error:"session.restore failed";if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error(V)}let X=A$(j.payload?.snapshot),A=j.payload?.session,P=(X?.sessionId??A?.sessionId)?.trim();if(J&&!P){if(Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);throw Error("Hub checkpoint restore returned no session id")}if(P&&Z&&P!==Z)this.sessionCapabilities.delete(Z),this.sessionClientContributionHandlers.delete(Z),this.disposeSessionSubscription(Z);if(P&&H)this.sessionCapabilities.set(P,H);if(P&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(P,Q.handlers);if(P)this.ensureSessionSubscription(P);let B=Array.isArray(j.payload?.messages)?j.payload.messages:void 0,Y=j.payload?.checkpoint;if(!Y)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:P,startResult:P?{sessionId:P,manifest:X?z7(X,W??{}):O7(P,W??{},A),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:B,checkpoint:Y}}async runTurn(f){return this.ensureSessionSubscription(f.sessionId),(await this.client.command("run.start",{sessionId:f.sessionId,input:f.prompt,attachments:(f.userImages?.length??0)>0||(f.userFiles?.length??0)>0?{...f.userImages?.length?{userImages:f.userImages}:{},...f.userFiles?.length?{userFiles:f.userFiles}:{}}:void 0,delivery:f.delivery,timeoutMs:f.timeoutMs},f.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.pending_prompts",{sessionId:f.sessionId},f.sessionId);return Array.isArray($.payload?.prompts)?$.payload.prompts:[]}async requestPendingPromptUpdate(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.update_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,updated:$.payload?.updated===!0}}async requestPendingPromptDelete(f){this.ensureSessionSubscription(f.sessionId);let $=await this.client.command("session.remove_pending_prompt",{...f},f.sessionId);return{sessionId:f.sessionId,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[],prompt:$.payload?.prompt,removed:$.payload?.removed===!0}}async getAccumulatedUsage(f){let $=await this.client.command("session.get",{includeSnapshot:!0},f),J=A$($.payload?.snapshot);if(J){let Z=J.usage?{...J.usage}:void 0,j=J.aggregateUsage?{...J.aggregateUsage}:void 0;return Z||j?{usage:Z,aggregateUsage:j}:void 0}let W=$.payload?.session,H=h7(W?.usage),Q=h7(W?.aggregateUsage);return H||Q?{usage:H,aggregateUsage:Q}:void 0}async abort(f,$){await this.client.command("run.abort",{sessionId:f,reason:typeof $==="string"?$:void 0},f)}async stopSession(f){this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),await this.client.command("session.detach",{sessionId:f},f)}async dispose(){for(let[f,$]of this.sessionSubscriptions){$();try{await this.client.command("session.detach",{sessionId:f},f)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let f of this.activeCapabilityAbortControllers.values())f.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession(f){let $=await this.client.command("session.get",void 0,f);return vy($.payload)}async listSessions(f=100){let $=await this.client.command("session.list",{limit:f}),J=Array.isArray($.payload?.snapshots)?$.payload.snapshots.flatMap((H)=>{let Q=A$(H);return Q?[K5(Q)]:[]}):[];if(J.length>0)return J;return($.payload?.sessions??[]).map(N7)}async listSettings(f){let $=await this.client.command("settings.list",_7(f));if(!$.ok)throw Error(y5($,"settings.list"));return $.payload?.snapshot}async toggleSetting(f){let $=await this.client.command("settings.toggle",_7(f));if(!$.ok)throw Error(y5($,"settings.toggle"));return{snapshot:$.payload?.snapshot,changedTypes:Array.isArray($.payload?.changedTypes)?$.payload.changedTypes:[]}}async deleteSession(f){return this.sessionCapabilities.delete(f),this.disposeSessionSubscription(f),(await this.client.command("session.delete",{sessionId:f})).payload?.deleted===!0}async updateSession(f,$){let J={...$.metadata??{}};if(typeof $.prompt==="string")J.prompt=$.prompt;if(typeof $.title==="string")J.title=$.title;return{updated:(await this.client.command("session.update",{sessionId:f,metadata:J})).ok}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(y5(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async dispatchHookEvent(f){await this.client.command("session.hook",{payload:f})}subscribe(f,$){return this.events.subscribe(f,$)}ensureSessionSubscription(f){let $=f.trim();if(!$||this.sessionSubscriptions.has($))return;let J=this.client.subscribe((W)=>{this.handleHubEvent(W)},{sessionId:$});this.sessionSubscriptions.set($,typeof J==="function"?J:()=>{})}disposeSessionSubscription(f){let $=f.trim();if(!$)return;this.sessionSubscriptions.get($)?.(),this.sessionSubscriptions.delete($),this.agentDoneEmittedForCurrentRunBySession.delete($)}resolveCapabilities(f){return Ff(this.defaultCapabilities,f.capabilities)??{}}emitToolCallContentStart(f){this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:f.toolCallId,toolName:f.toolName,input:f.toolInput}}})}emitAgentDoneIfNeeded(f){if(this.agentDoneEmittedForCurrentRunBySession.has(f.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add(f.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:f.sessionId,event:gy(f.payload)}})}handleHubEvent(f){let $=f.sessionId?.trim();if(f.event==="capability.requested"){this.handleCapabilityRequest(f);return}if(f.event==="capability.resolved"){this.handleCapabilityResolved(f);return}if(f.event==="approval.requested"){this.handleApprovalRequested(f);return}if(!$)return;switch(f.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete($);let J=A$(f.payload?.snapshot),W=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:W?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_start",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"iteration_end",iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,hadToolCalls:f.payload?.hadToolCalls===!0,toolCallCount:typeof f.payload?.toolCallCount==="number"?f.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"text",text:typeof f.payload?.text==="string"?f.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof f.payload?.text==="string"?f.payload.text:"",W=f.payload?.redacted===!0;if(!J&&!W)return;this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:W}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"reasoning",reasoning:typeof f.payload?.reasoning==="string"?f.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:$,payload:f.payload});return}case"usage.updated":{let J=xy(f.payload);this.events.emit({type:"agent_event",payload:{sessionId:$,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:$,toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,toolInput:f.payload?.input});return}case"tool.finished":{let J=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:$,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof f.payload?.toolName==="string"?f.payload.toolName:void 0,output:f.payload?.output,error:typeof f.payload?.error==="string"?f.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=A$(f.payload?.snapshot),W=f.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:$,status:W?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:$,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=f.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:$,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=typeof f.payload?.reason==="string"?f.payload.reason:f.event==="run.aborted"?"aborted":f.event==="run.failed"?"error":"completed";this.emitAgentDoneIfNeeded({sessionId:$,payload:{...f.payload,reason:J}}),this.events.emit({type:"ended",payload:{sessionId:$,reason:J,ts:f.timestamp??Date.now()}});return}default:return}}async handleCapabilityRequest(f){let $=f.sessionId?.trim();if(!$)return;let J=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let W=typeof f.payload?.requestId==="string"?f.payload.requestId:"",H=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName:"";if(!W)return;let Q=this.sessionClientContributionHandlers.get($)?.get(H);if(!Q){await this.client.command("capability.respond",{requestId:W,ok:!1,error:`No client contribution handler registered for capability ${H} in session ${$}.`},$).catch(()=>{});return}let Z=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=new AbortController;this.activeCapabilityAbortControllers.set(W,j);let X=(A)=>{this.client.command("capability.progress",{requestId:W,payload:A},$)};try{let A=await Q({payload:Z,abortSignal:j.signal,progress:X});if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!0,payload:A},$)}catch(A){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:A instanceof Error?A.message:String(A)},$)}finally{this.activeCapabilityAbortControllers.delete(W)}}handleCapabilityResolved(f){if(f.payload?.cancelled!==!0)return;let $=typeof f.payload.requestId==="string"?f.payload.requestId.trim():"";if(!$)return;let J=this.activeCapabilityAbortControllers.get($);if(!J)return;J.abort(Sy(f.payload.error))}async handleApprovalRequested(f){let $=f.sessionId?.trim();if(!$)return;let J=this.sessionCapabilities.get($)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let W=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"",H=typeof f.payload?.toolCallId==="string"?f.payload.toolCallId:"",Q=typeof f.payload?.toolName==="string"?f.payload.toolName:"";if(!W||!H||!Q)return;let Z=f.payload?.policy&&typeof f.payload.policy==="object"&&!Array.isArray(f.payload.policy)?f.payload.policy:{autoApprove:!1},j=ky(f.payload?.inputJson);this.pendingApprovalToolCallIds.add(H),this.emitToolCallContentStart({sessionId:$,toolCallId:H,toolName:Q,toolInput:j});let X=await Promise.resolve(J({sessionId:$,agentId:typeof f.payload?.agentId==="string"?f.payload.agentId:"",conversationId:typeof f.payload?.conversationId==="string"?f.payload.conversationId:$,iteration:typeof f.payload?.iteration==="number"?f.payload.iteration:0,toolCallId:H,toolName:Q,input:j,policy:Z})).catch((A)=>({approved:!1,reason:A instanceof Error?A.message:`Tool approval request failed: ${String(A)}`}));await this.client.command("approval.respond",{approvalId:W,approved:X.approved,reason:X.reason},$).catch(()=>{})}}class E8 extends P${constructor(f){super({url:l$(f.endpoint),authToken:f.authToken,clientType:f.clientType??"core-remote-runtime",displayName:f.displayName??"core remote runtime",capabilities:f.capabilities},{workspaceRoot:f.workspaceRoot,cwd:f.cwd})}}import{existsSync as uy,mkdirSync as cy}from"node:fs";import{join as dy}from"node:path";import{asBool as l1,asOptionalString as nf,asString as j0,ensureSessionSchema as ry,loadSqliteDb as ly,nowIso as S8,toBoolInt as p1}from"@cline/shared/db";import{resolveDbDataDir as py}from"@cline/shared/storage";class E0{sessionsDirPath;db;constructor(f={}){this.sessionsDirPath=f.sessionsDir??py()}init(){this.getRawDb()}ensureSessionsDir(){if(!uy(this.sessionsDirPath))cy(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return dy(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let f=ly(this.sessionDbPath());return ry(f,{includeLegacyMigrations:!0}),this.db=f,f}close(){this.db?.close?.(),this.db=void 0}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}create(f){let $=S8();this.run(`INSERT OR REPLACE INTO sessions (
|
|
432
432
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
433
433
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
434
434
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
435
435
|
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
436
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,0,
|
|
436
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,0,p1(f.interactive),f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,p1(f.enableTools),p1(f.enableSpawn),p1(f.enableTeams),f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,p1(f.isSubagent),f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"",f.hookPath??"",f.messagesPath??null,$])}update(f){let $=[],J=[];if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(f.metadata?JSON.stringify(f.metadata):null);if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId);if($.length===0)return;$.push("updated_at = ?"),J.push(S8()),J.push(f.sessionId),this.run(`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`,J)}updateStatus(f,$,J){this.update({sessionId:f,status:$,endedAt:$==="running"?null:S8(),exitCode:$==="running"?null:J??($==="failed"?1:0)})}get(f){let $=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
|
|
437
437
|
provider, model, cwd, workspace_root, team_name,
|
|
438
438
|
enable_tools, enable_spawn, enable_teams,
|
|
439
439
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
|
|
440
440
|
prompt, metadata_json, hook_path, messages_path, updated_at
|
|
441
|
-
FROM sessions WHERE session_id = ?`,[f]);if(!$)return;return{sessionId:
|
|
442
|
-
`).filter(Boolean);await Promise.allSettled(
|
|
443
|
-
`,"utf8")}readSessionManifest(f){return this.readManifestFile(f).manifest}readManifestFile(f){let $=this.artifacts.sessionManifestPath(f,!1);if(!
|
|
444
|
-
`;if(
|
|
445
|
-
`,"utf8")}}import{appendFileSync as
|
|
446
|
-
`,"utf8")}}import{formatUserInputBlock as
|
|
447
|
-
|
|
448
|
-
${f.message}`}class
|
|
441
|
+
FROM sessions WHERE session_id = ?`,[f]);if(!$)return;return{sessionId:j0($.session_id),source:j0($.source),pid:Number($.pid??0),startedAt:j0($.started_at),endedAt:$.ended_at??null,exitCode:$.exit_code??null,status:j0($.status),interactive:l1($.interactive),provider:j0($.provider),model:j0($.model),cwd:j0($.cwd),workspaceRoot:j0($.workspace_root),teamName:nf($.team_name),enableTools:l1($.enable_tools),enableSpawn:l1($.enable_spawn),enableTeams:l1($.enable_teams),parentSessionId:nf($.parent_session_id),parentAgentId:nf($.parent_agent_id),agentId:nf($.agent_id),conversationId:nf($.conversation_id),isSubagent:l1($.is_subagent),prompt:nf($.prompt),metadata:(()=>{let J=nf($.metadata_json);if(!J)return;try{let W=JSON.parse(J);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return})(),hookPath:nf($.hook_path),messagesPath:nf($.messages_path),updatedAt:nf($.updated_at)??S8()}}list(f=200){let $=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[f]),J=[];for(let W of $){let H=this.get(j0(W.session_id));if(H)J.push(H)}return J}delete(f,$=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}}k8();import{existsSync as E5,mkdirSync as SU,readFileSync as v7,renameSync as kU,writeFileSync as IU}from"node:fs";import{join as u7}from"node:path";import{resolveSessionDataDir as mU}from"@cline/shared/storage";import{dirname as CU}from"node:path";import{nanoid as EU}from"nanoid";import{execFile as QU}from"node:child_process";import{promisify as ZU}from"node:util";var jU=ZU(QU);function G5(f,$){f?.log($,{severity:"warn"})}function XU(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!J.latest||!Array.isArray(J.history))return;let W=J.latest,H=J.history.filter((Q)=>!!Q&&typeof Q==="object"&&typeof Q.ref==="string"&&typeof Q.createdAt==="number"&&typeof Q.runCount==="number");if(typeof W.ref!=="string"||typeof W.createdAt!=="number"||typeof W.runCount!=="number")return;return{latest:W,history:H}}async function Y$(f,$){let J=await jU("git",["-C",f,...$],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function T5(f,$){if(!f)return;let J=`refs/cline/checkpoints/${$}/`;try{let{stdout:W}=await Y$(f,["for-each-ref","--format=%(refname)",J]),H=W.trim().split(`
|
|
442
|
+
`).filter(Boolean);await Promise.allSettled(H.map((Q)=>Y$(f,["update-ref","-d",Q])))}catch{}}async function q7(f,$,J){if(!f||J.length===0)return;await Promise.allSettled(J.map((W)=>Y$(f,["update-ref",`refs/cline/checkpoints/${$}/${W.runCount}`,W.ref])))}function AU(f,$){let J=f.findIndex((W)=>W.runCount===$.runCount);if(J<0)return[...f,$];return f.map((W,H)=>H===J?$:W)}function w7(f){let $=f.initialRunCount??0,J,W=async()=>{if(J!==void 0)return J;try{J=(await Y$(f.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},H=async()=>{if(f.createCheckpoint)return await f.createCheckpoint({cwd:f.cwd,sessionId:f.sessionId,runCount:$});if(!await W())return;let Q=async(A)=>{try{let B=(await Y$(f.cwd,["rev-parse","HEAD"])).stdout.trim();if(!B)return;return{ref:B,createdAt:Date.now(),runCount:$,kind:"commit"}}catch(P){G5(f.logger,`${A}: ${P instanceof Error?P.message:String(P)}`);return}},Z=`cline checkpoint session=${f.sessionId} run=${$}`,j="";try{j=(await Y$(f.cwd,["stash","create",Z])).stdout.trim()}catch(A){return G5(f.logger,`Checkpoint snapshot failed: ${A instanceof Error?A.message:String(A)}`),Q("Checkpoint HEAD fallback failed")}if(!j)return Q("Checkpoint HEAD fallback failed");let X=`refs/cline/checkpoints/${f.sessionId}/${$}`;try{await Y$(f.cwd,["update-ref",X,j])}catch(A){G5(f.logger,`Checkpoint store failed: ${A instanceof Error?A.message:String(A)}`);return}return{ref:j,createdAt:Date.now(),runCount:$,kind:"stash"}};return{beforeRun:async({snapshot:Q})=>{if(Q.parentAgentId!=null)return;$+=1;return},beforeModel:async({snapshot:Q})=>{if(Q.parentAgentId!=null||Q.iteration!==1||$<1)return;let Z=await H();if(!Z)return;let j=await f.readSessionMetadata(),X=XU(j);if(X?.latest.ref===Z.ref)return;let A=AU(X?.history??[],Z);await f.writeSessionMetadata({...j??{},checkpoint:{latest:Z,history:A}});return}}}import{existsSync as m8,mkdirSync as PU,readdirSync as BU,rmdirSync as YU,rmSync as VU,unlinkSync as RU}from"node:fs";import{dirname as b7,join as I8}from"node:path";function n(){return new Date().toISOString()}function i1(f){if(!f||!m8(f))return;try{RU(f)}catch{}}function FU(f){let $=m1(f);if($)return{rootSessionId:$.rootSessionId,fileStem:`${$.agentId}__${$.teamTaskId}`};let J=h8(f);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:f,fileStem:f}}class D5{ensureSessionsDir;constructor(f){this.ensureSessionsDir=f}sessionArtifactsDir(f){return I8(this.ensureSessionsDir(),f)}ensureSessionArtifactsDir(f){let $=this.sessionArtifactsDir(f);if(!m8($))PU($,{recursive:!0});return $}sessionMessagesPath(f){return I8(this.sessionArtifactsDir(f),`${f}.messages.json`)}sessionManifestPath(f,$=!1){let J=$?this.ensureSessionArtifactsDir(f):this.sessionArtifactsDir(f);return I8(J,`${f}.json`)}removeSessionDirIfEmpty(f){let $=this.sessionArtifactsDir(f),J=this.ensureSessionsDir();while($.startsWith(J)&&$!==J){if(!m8($)){$=b7($);continue}try{if(BU($).length>0)break;YU($)}catch{break}$=b7($)}}removeSessionDir(f){this.removeDir(this.sessionArtifactsDir(f))}removeDir(f){if(!m8(f))return;try{VU(f,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths(f,$,J){let{rootSessionId:W,fileStem:H}=FU(f),Q=this.sessionArtifactsDir(W);return{messagesPath:I8(Q,`${H}.messages.json`)}}}import{appendFileSync as KU,existsSync as yU,mkdirSync as C7,readFileSync as UU,writeFileSync as E7}from"node:fs";import{dirname as S7,join as GU}from"node:path";import{ensureHookLogDir as TU}from"@cline/shared/storage";class _5{adapter;messagesArtifactUploader;artifacts;constructor(f,$){this.adapter=f;this.messagesArtifactUploader=$;this.artifacts=new D5(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile(f,$,J){vQ($,J,eJ(f))}writeSessionManifest(f,$){C7(S7(f),{recursive:!0}),E7(f,`${JSON.stringify(Df.parse($),null,2)}
|
|
443
|
+
`,"utf8")}readSessionManifest(f){return this.readManifestFile(f).manifest}readManifestFile(f){let $=this.artifacts.sessionManifestPath(f,!1);if(!yU($))return{path:$};try{return{path:$,manifest:Df.parse(JSON.parse(UU($,"utf8")))}}catch{return{path:$}}}async resolveArtifactPath(f,$,J){let H=(await this.adapter.getSession(f))?.[$];return typeof H==="string"&&H.trim().length>0?H:J(f)}async persistSessionMessages(f,$,J){let W=await this.resolveArtifactPath(f,"messagesPath",(Z)=>this.artifacts.sessionMessagesPath(Z)),H=f5({updatedAt:n(),context:eJ(f),messages:$,systemPrompt:J}),Q=`${JSON.stringify(H,null,2)}
|
|
444
|
+
`;if(C7(S7(W),{recursive:!0}),E7(W,Q,"utf8"),!this.messagesArtifactUploader)return;try{let Z=await this.adapter.getSession(f);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:f,path:W,contents:Q,row:Z})}catch(Z){console.warn(`Failed to upload persisted session messages for ${f}`,Z)}}appendStaleSessionHookLog(f,$,J,W,H){let Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??GU(TU(),"hooks.jsonl");KU(Z,`${JSON.stringify({ts:f,hookName:"session_shutdown",reason:W,sessionId:$,pid:J,source:H})}
|
|
445
|
+
`,"utf8")}}import{appendFileSync as DU}from"node:fs";import{join as _U}from"node:path";import{resolveRootSessionId as k7}from"@cline/shared";import{ensureHookLogDir as MU}from"@cline/shared/storage";import{z as M5}from"zod";var LU="subagent",hU=M5.looseObject({task:M5.string().optional(),systemPrompt:M5.string().optional()});class x8{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor(f,$,J,W){this.adapter=f;this.manifestStore=$;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=W}teamTaskQueueKey(f,$){return`${f}::${$}`}activeTeamTaskSessionId(f,$){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey(f,$))?.at(-1)}buildSubsessionRow(f,$){return{sessionId:$.sessionId,source:LU,pid:process.ppid,startedAt:$.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:$.parentSessionId,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId??null,isSubagent:!0,prompt:$.prompt,metadata:g1({prompt:$.prompt}),hookPath:"",messagesPath:$.messagesPath,updatedAt:$.startedAt}}async queueSpawnRequest(f){if(f.hookName!=="tool_call"||f.parent_agent_id!==null)return;if(f.tool_call?.name!=="spawn_agent")return;let $=k7(f.sessionContext);if(!$)return;let J=hU.safeParse(f.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:$,parentAgentId:f.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession(f){let $=f.rootSessionId;if(!$)return;let J=await this.adapter.getSession($);if(!J)return;let W=L8($,f.agentId),H=await this.adapter.getSession(W),Q=n(),Z=this.manifestStore.artifacts.subagentArtifactPaths(W,f.agentId,this.activeTeamTaskSessionId($,f.parentAgentId)),j=f.prompt??H?.prompt??void 0;if(!j)j=await this.adapter.claimSpawnRequest($,f.parentAgentId)??`Subagent run by ${f.parentAgentId}`;if(!H)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:W,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:j,startedAt:Q,...Z})),this.manifestStore.initializeMessagesFile(W,Z.messagesPath,Q),W;return await this.adapter.updateSession({sessionId:W,setRunning:!0,parentSessionId:$,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId,prompt:H.prompt??j??null,metadata:g1({metadata:H.metadata??void 0,prompt:H.prompt??j??null}),expectedStatusLock:H.statusLock}),W}async upsertSubagentSessionFromHook(f){if(!f.parent_agent_id)return;let $=k7(f.sessionContext);if(!$)return;if(f.hookName==="session_shutdown"){let J=L8($,f.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:f.agent_id,parentAgentId:f.parent_agent_id,conversationId:f.taskId,rootSessionId:$})}async applySubagentStatus(f,$){await this.applySubagentStatusBySessionId(f,aJ($))}async applySubagentStatusBySessionId(f,$){let J=await this.adapter.getSession(f);if(!J)return;let W=$==="running"?null:n(),H=$==="running"?null:$==="failed"?1:0;await this.adapter.updateSession({sessionId:f,status:$,endedAt:W,exitCode:H,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions(f,$){if(!f)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:f,status:"running"});for(let W of J)await this.applySubagentStatusBySessionId(W.sessionId,$)}async onTeamTaskStart(f,$,J){let W=await this.adapter.getSession(f);if(!W)return;let H=nJ(f,$),Q=n(),{messagesPath:Z}=this.manifestStore.artifacts.subagentArtifactPaths(H,$);await this.adapter.upsertSession(this.buildSubsessionRow(W,{sessionId:H,parentSessionId:f,parentAgentId:"lead",agentId:$,prompt:J||`Team task for ${$}`,startedAt:Q,messagesPath:Z})),this.manifestStore.initializeMessagesFile(H,Z,Q);let j=this.teamTaskQueueKey(f,$),X=this.teamTaskSessionsByAgent.get(j)??[];X.push(H),this.teamTaskSessionsByAgent.set(j,X)}async onTeamTaskEnd(f,$,J,W,H,Q){let Z=this.teamTaskQueueKey(f,$),j=this.teamTaskSessionsByAgent.get(Z);if(!j||j.length===0)return;let X=j.shift();if(j.length===0)this.teamTaskSessionsByAgent.delete(Z);if(!X)return;let A=H?.messages??Q,P=this.toPersistedMessages(A,H,Q);if(P)await this.manifestStore.persistSessionMessages(X,P);await this.applySubagentStatusBySessionId(X,J),this.teamTaskLastHeartbeatBySession.delete(X),this.teamTaskLastProgressLineBySession.delete(X)}async onTeamTaskProgress(f,$,J,W){let H=this.teamTaskQueueKey(f,$),Q=this.teamTaskSessionsByAgent.get(H)?.[0];if(!Q)return;let Z=J.trim();if(!Z)return;let j=W?.kind??"progress";if(j==="heartbeat"){let A=Date.now(),P=this.teamTaskLastHeartbeatBySession.get(Q)??0;if(A-P<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(Q,A)}let X=j==="heartbeat"?"[progress] heartbeat":j==="text"?`[progress] text: ${Z}`:`[progress] ${Z}`;if(this.teamTaskLastProgressLineBySession.get(Q)===X)return;this.teamTaskLastProgressLineBySession.set(Q,X)}async handleSubAgentStart(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd(f,$){let J=await this.upsertSubagentSession({agentId:$.subAgentId,parentAgentId:$.parentAgentId,conversationId:$.conversationId,prompt:$.input.task,rootSessionId:f});if(!J)return;if($.error){await this.applySubagentStatusBySessionId(J,"failed");return}let W=this.toPersistedMessages($.agentResult?.messages,$.agentResult);if(W)await this.manifestStore.persistSessionMessages(J,W);let H=$.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,H==="aborted"?"cancelled":"completed")}appendSubagentHookAudit(f){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??_U(MU(),"hooks.jsonl");DU(J,`${JSON.stringify({ts:n(),...f})}
|
|
446
|
+
`,"utf8")}}import{formatUserInputBlock as bU}from"@cline/shared";function af(){return new Date().toISOString()}function I7(f,$){if($<=0)return 0;return Math.round(f/$*100)}function OU(f,$){let J=new Set;for(let H of $)if(H.status==="reviewed")J.add(`${H.outcomeId}:${H.section}`);let W=new Set;for(let H of f){if(H.status==="finalized")continue;for(let Q of H.requiredSections)if(!J.has(`${H.id}:${Q}`))W.add(`${H.id}:${Q}`)}return[...W].sort((H,Q)=>H.localeCompare(Q))}function g8(f,$){let J={idle:0,running:0,stopped:0},W={pending:0,in_progress:0,blocked:0,completed:0},H={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},Q={draft:0,in_review:0,finalized:0},Z={draft:0,reviewed:0,rejected:0},j=0,X=0;for(let K of $.members)if(J[K.status]+=1,K.role==="lead")j+=1;else X+=1;let A=[],P=[],B=$.tasks.filter((K)=>K.status==="completed").length,Y=new Map($.tasks.map((K)=>[K.id,K]));for(let K of $.tasks){if(W[K.status]+=1,K.status==="blocked"){A.push(K.id);continue}if(K.status!=="pending")continue;if(K.dependsOn.every((y)=>{return Y.get(y)?.status==="completed"}))P.push(K.id)}let V=[],R,U=0;for(let K of $.runs){if(H[K.status]+=1,K.status==="queued"||K.status==="running")V.push(K.id);let F=K.startedAt.getTime();if(F>=U)U=F,R=K.id}for(let K of $.outcomes)Q[K.status]+=1;for(let K of $.outcomeFragments)Z[K.status]+=1;return{teamName:f,updatedAt:af(),members:{total:$.members.length,byStatus:J,leadCount:j,teammateCount:X},tasks:{total:$.tasks.length,byStatus:W,blockedTaskIds:A,readyTaskIds:P,completionPct:I7(B,$.tasks.length)},runs:{total:$.runs.length,byStatus:H,activeRunIds:V,latestRunId:R},outcomes:{total:$.outcomes.length,byStatus:Q,finalizedPct:I7(Q.finalized,$.outcomes.length),missingRequiredSections:OU($.outcomes,$.outcomeFragments)},fragments:{total:$.outcomeFragments.length,byStatus:Z}}}function v8(f){let{event:$}=f;switch($.type){case"team_task_updated":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:af(),taskId:$.task.id,agentId:$.task.assignee??$.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:af(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.run.error};case"run_progress":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:af(),runId:$.run.id,taskId:$.run.taskId,agentId:$.run.agentId,message:$.message};case"outcome_created":case"outcome_finalized":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:af(),outcomeId:$.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:af(),outcomeId:$.fragment.outcomeId,fragmentId:$.fragment.id,agentId:$.fragment.sourceAgentId};case"team_message":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:af(),taskId:$.message.taskId,agentId:$.message.fromAgentId,message:$.message.subject};case"team_mission_log":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:af(),taskId:$.entry.taskId,agentId:$.entry.agentId,message:$.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:af(),agentId:$.agentId}}return{teamName:f.teamName,sessionId:f.sessionId,eventType:$.type,ts:af()}}import{sanitizeFileName as zU,TeamMessageType as q}from"@cline/shared";import{nanoid as NU}from"nanoid";import{TeamMessageType as LC}from"@cline/shared";function L5(f){if(typeof DOMException<"u"&&f instanceof DOMException&&f.name==="AbortError")return!0;if(!(f instanceof Error))return!1;return f.name==="AbortError"||f.message.toLowerCase().includes("aborted")}function m7(f,$){return f?.status==="stopped"&&L5($)}var qU=600000,x7="recovered_queued";function wU(f){return`This is an automatic recovery of interrupted team run ${f.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
|
|
447
|
+
|
|
448
|
+
${f.message}`}class h5{agents=new Map;configs=new Map;onTeamEvent;constructor(f,$){if(this.onTeamEvent=$,f)for(let[J,W]of Object.entries(f))this.addAgent(J,W)}addAgent(f,$){if(this.agents.has(f))throw Error(`Agent with id "${f}" already exists in the team`);let J={...$,onEvent:(H)=>{$.onEvent?.(H),this.emitEvent({type:q.AgentEvent,agentId:f,event:H})}},W=new L0(J);if(J.onEvent)W.subscribeEvents(J.onEvent);this.agents.set(f,W),this.configs.set(f,$)}removeAgent(f){return this.configs.delete(f),this.agents.delete(f)}getAgent(f){return this.agents.get(f)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:q.TaskStart,agentId:f,message:$});try{let W=await J.run($);return this.emitEvent({type:q.TaskEnd,agentId:f,result:W}),W}catch(W){let H=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:q.TaskEnd,agentId:f,error:H,messages:J.getMessages()}),W}}async continueTo(f,$){let J=this.agents.get(f);if(!J)throw Error(`Agent "${f}" not found in team`);this.emitEvent({type:q.TaskStart,agentId:f,message:$});try{let W=await J.continue($);return this.emitEvent({type:q.TaskEnd,agentId:f,result:W}),W}catch(W){let H=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:q.TaskEnd,agentId:f,error:H,messages:J.getMessages()}),W}}async runParallel(f){let $=f.map(async(J)=>{let W=this.agents.get(J.agentId);if(!W)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:q.TaskStart,agentId:J.agentId,message:J.message});try{let H=await W.run(J.message);return this.emitEvent({type:q.TaskEnd,agentId:J.agentId,result:H}),{agentId:J.agentId,result:H,metadata:J.metadata}}catch(H){let Q=H instanceof Error?H:Error(String(H));return this.emitEvent({type:q.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),{agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata}}});return Promise.all($)}async runSequential(f){let $=[];for(let J of f){let W=this.agents.get(J.agentId);if(!W){$.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:q.TaskStart,agentId:J.agentId,message:J.message});try{let H=await W.run(J.message);this.emitEvent({type:q.TaskEnd,agentId:J.agentId,result:H}),$.push({agentId:J.agentId,result:H,metadata:J.metadata})}catch(H){let Q=H instanceof Error?H:Error(String(H));this.emitEvent({type:q.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),$.push({agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata})}}return $}async runPipeline(f,$,J){let W=[],H=$;for(let Q of f){let Z=this.agents.get(Q);if(!Z){W.push({agentId:Q,result:void 0,error:Error(`Agent "${Q}" not found in team`)});break}this.emitEvent({type:q.TaskStart,agentId:Q,message:H});try{let j=await Z.run(H);this.emitEvent({type:q.TaskEnd,agentId:Q,result:j}),W.push({agentId:Q,result:j});let X=f.indexOf(Q)+1;if(X<f.length){let A=f[X];H=J?J(j,A):`Previous agent output:
|
|
449
449
|
${j.text}
|
|
450
450
|
|
|
451
|
-
Please continue from here.`}}catch(j){let
|
|
451
|
+
Please continue from here.`}}catch(j){let X=j instanceof Error?j:Error(String(j));this.emitEvent({type:q.TaskEnd,agentId:Q,error:X,messages:Z.getMessages()}),W.push({agentId:Q,result:void 0,error:X});break}}return W}abortAll(){for(let f of this.agents.values())f.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}class n1{teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor(f){this.teamName=f.teamName,this.teamId=`t_${zU(NU(10))}`,this.onTeamEvent=f.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,f.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,f.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,f.maxConcurrentRuns??2);let $=f.leadAgentId??"lead";this.members.set($,{agentId:$,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole(f){return this.members.get(f)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter((f)=>f.role==="teammate").map((f)=>f.agentId)}getTask(f){return this.tasks.get(f)}listTasks(){return Array.from(this.tasks.values())}listTaskItems(f){return Array.from(this.tasks.values()).map(($)=>{let J=this.getUnresolvedDependencies($);return{...$,blockedBy:J,isReady:$.status==="pending"&&!$.assignee&&J.length===0}}).filter(($)=>{if(f?.status&&$.status!==f.status)return!1;if(f?.assignee&&$.assignee!==f.assignee)return!1;return!0})}listMissionLog(f){if(!f||f<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-f))}listMailbox(f,$){let J=$?.unreadOnly??!0,W=$?.markRead??!0,H=$?.limit,Q=this.mailbox.filter((j)=>j.toAgentId===f&&(!J||!j.readAt)),Z=typeof H==="number"&&H>0?Q.slice(Math.max(0,Q.length-H)):Q;if(W){let j=new Date;for(let X of Z)if(!X.readAt)X.readAt=j}return Z.map((j)=>({...j}))}getSnapshot(){let f={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())f[J.status]++;let $={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())$[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:f,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:$}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((f)=>({agentId:f.agentId,role:f.role,description:f.description,status:f.status})),tasks:Array.from(this.tasks.values()).map((f)=>({...f})),mailbox:this.mailbox.map((f)=>({...f})),missionLog:this.missionLog.map((f)=>({...f})),runs:Array.from(this.runs.values()).map((f)=>({...f})),outcomes:Array.from(this.outcomes.values()).map((f)=>({...f})),outcomeFragments:Array.from(this.outcomeFragments.values()).map((f)=>({...f}))}}hydrateState(f){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of f.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...f.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...f.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of f.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of f.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of f.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let $=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of $)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of f.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,i$(f.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,i$(f.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,i$(f.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,i$((f.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,i$((f.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,i$((f.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive(f){let $=this.members.get(f);return!!$&&$.role==="teammate"&&!!$.agent}spawnTeammate({agentId:f,config:$}){let J=this.members.get(f);if(J&&J.role!=="teammate")throw Error(`Team member "${f}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${f}" is currently running and cannot be respawned`);let W={...$,apiTimeoutMs:qU,consumePendingUserMessage:()=>{let Z=this.members.get(f);if(!Z||!Z.pendingSteerMessage)return;let j=Z.pendingSteerMessage;return Z.pendingSteerMessage=void 0,j},onEvent:(Z)=>{$.onEvent?.(Z),this.emitEvent({type:q.AgentEvent,agentId:f,event:Z}),this.trackMeaningfulEvent(f,Z)}},H=new L0(W);if(W.onEvent)H.subscribeEvents(W.onEvent);let Q={agentId:f,role:"teammate",description:$.role,status:"idle",agent:H,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set(f,Q),this.emitEvent({type:q.TeammateSpawned,agentId:f,role:$.role,teammate:{rolePrompt:$.systemPrompt,modelId:$.modelId,maxIterations:$.maxIterations,runtimeAgentId:H.getAgentId(),conversationId:H.getConversationId(),parentAgentId:null}}),{agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status}}shutdownTeammate(f,$){let J=this.members.get(f);if(!J||J.role!=="teammate")throw Error(`Teammate "${f}" was not found`);try{J.agent?.abort()}catch(W){if(!L5(W))throw W}J.status="stopped",this.emitEvent({type:q.TeammateShutdown,agentId:f,reason:$})}updateTeammateConnections(f){for(let $ of this.members.values()){if($.role!=="teammate"||!$.agent)continue;$.agent.updateConnection(f)}}createTask(f){let $=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,W={id:$,title:f.title,description:f.description,status:f.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:f.createdBy,assignee:f.assignee,dependsOn:f.dependsOn??[]};return this.tasks.set($,W),this.emitEvent({type:q.TeamTaskUpdated,task:{...W}}),{...W}}claimTask(f,$){let J=this.requireTask(f);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=$,J.updatedAt=new Date,this.emitEvent({type:q.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:$,taskId:f,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask(f,$,J){let W=this.requireTask(f);return W.status="blocked",W.updatedAt=new Date,W.summary=J,this.emitEvent({type:q.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:$,taskId:f,kind:"blocked",summary:J}),{...W}}completeTask(f,$,J){let W=this.requireTask(f);if(W.status="completed",W.updatedAt=new Date,W.summary=J,!W.assignee)W.assignee=$;return this.emitEvent({type:q.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:$,taskId:f,kind:"done",summary:J}),{...W}}async routeToTeammate(f,$,J){let W=this.members.get(f);if(!W||W.role!=="teammate"||!W.agent)throw Error(`Teammate "${f}" was not found`);if(!W.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");W.runningCount++,W.status="running",this.emitEvent({type:q.TaskStart,agentId:f,message:$});try{let H=this.listMailbox(f,{unreadOnly:!0,markRead:!0}),Q=H.length>0?`${this.buildMailboxNotification(H)}
|
|
452
452
|
|
|
453
|
-
${$}`:$,Z=J?.continueConversation?await H.agent.continue(Q):await H.agent.run(Q);return this.emitEvent({type:N.TaskEnd,agentId:f,result:Z}),this.recordProgressStep(f,`Completed a delegated run (${Z.iterations} iterations)`,J?.taskId,!0),Z}catch(W){let Q=W instanceof Error?W:Error(String(W));if(this.emitEvent({type:N.TaskEnd,agentId:f,error:Q,messages:H.agent.getMessages()}),!bQ(H,Q))this.appendMissionLog({agentId:f,taskId:J?.taskId,kind:"error",summary:Q.message});throw Q}finally{if(H.runningCount--,H.runningCount<=0&&this.members.get(f)?.status!=="stopped")H.status="idle"}}startTeammateRun(f,$,J){let H=`run_${String(++this.runCounter).padStart(5,"0")}`,W={id:H,agentId:f,taskId:J?.taskId,status:"queued",message:$,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(H,W),this.runQueue.push(H),this.emitEvent({type:N.RunQueued,run:{...W}}),this.dispatchQueuedRuns(),{...W}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let f;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let $=this.selectNextDispatchableQueuedRun();f=$.nextDelayedAttemptAt;let J=$.index;if(J<0){this.scheduleQueuedRunDispatch(f);return}let[H]=this.runQueue.splice(J,1),W=H?this.runs.get(H):void 0;if(!W||W.status!=="queued")continue;this.executeQueuedRun(W)}this.scheduleQueuedRunDispatch(f)}selectNextDispatchableQueuedRun(){let f=-1,$=Number.NEGATIVE_INFINITY,J,H=Date.now();for(let W=0;W<this.runQueue.length;W++){let Q=this.runs.get(this.runQueue[W]);if(!Q||Q.status!=="queued")continue;if(Q.nextAttemptAt&&Q.nextAttemptAt.getTime()>H){if(!J||Q.nextAttemptAt<J)J=Q.nextAttemptAt;continue}if(Q.priority>$)$=Q.priority,f=W}return{index:f,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch(f){if(!f)return;let $=Math.max(0,f.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},$)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let f=0;for(let $ of this.runs.values())if($.status==="running")f++;return f}async executeQueuedRun(f){let $=f.currentActivity===wQ;f.nextAttemptAt=void 0,f.status="running",f.startedAt=new Date,f.heartbeatAt=new Date,f.currentActivity="run_started",this.emitEvent({type:N.RunStarted,run:{...f}});let J=setInterval(()=>{if(f.status!=="running")return;this.recordRunProgress(f,"heartbeat")},2000);try{let H=$?QU(f):f.message,W=await this.routeToTeammate(f.agentId,H,{taskId:f.taskId,continueConversation:f.continueConversation});f.status="completed",f.result=W,f.endedAt=new Date,f.currentActivity="completed",this.emitEvent({type:N.RunCompleted,run:{...f}})}catch(H){let W=H instanceof Error?H.message:String(H??"Unknown error");f.error=W,f.endedAt=new Date;let Q=this.members.get(f.agentId);if(bQ(Q,H))f.status="cancelled",f.currentActivity="cancelled",this.emitEvent({type:N.RunCancelled,run:{...f},reason:W});else if(f.retryCount<f.maxRetries)f.retryCount++,f.status="queued",f.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**f.retryCount)),this.runQueue.push(f.id),this.recordRunProgress(f,`retry_scheduled_${f.retryCount}`);else f.status="failed",f.currentActivity="failed",this.emitEvent({type:N.RunFailed,run:{...f}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns(f){let $=f?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!$&&!["running","queued"].includes(J.status))return!1;if(f?.status&&J.status!==f.status)return!1;if(f?.agentId&&J.agentId!==f.agentId)return!1;return!0}).map((J)=>({...J}))}getRun(f){let $=this.runs.get(f);return $?{...$}:void 0}async awaitRun(f,$=250){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);while(J.status==="queued"||J.status==="running")await CQ($);return{...J}}async awaitAllRuns(f=250){while(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))await CQ(f);return this.listRuns()}cancelRun(f,$){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=$,J.endedAt=new Date,J.currentActivity="cancelled";let H=this.runQueue.indexOf(f);if(H>=0)this.runQueue.splice(H,1);return this.emitEvent({type:N.RunCancelled,run:{...J},reason:$}),{...J}}recoverActiveRuns(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let H=this.members.get(J.agentId);if(!H||H.role!=="teammate"||!H.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:N.RunInterrupted,run:{...J},reason:J.error});continue}let W=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=W,J.lastProgressAt=W,J.lastProgressMessage=f,J.currentActivity=wQ,!this.runQueue.includes(J.id))this.runQueue.push(J.id);$.push({...J}),this.emitEvent({type:N.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),$}markStaleRunsInterrupted(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=f,J.endedAt=new Date,J.currentActivity="interrupted",$.push({...J}),this.emitEvent({type:N.RunInterrupted,run:{...J},reason:f})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),$}sendMessage(f,$,J,H,W){if(!this.members.has(f))throw Error(`Unknown sender "${f}"`);let Q=this.members.get($);if(!Q)throw Error(`Unknown recipient "${$}"`);let Z={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:f,toAgentId:$,subject:J,body:H,taskId:W,sentAt:new Date};if(this.mailbox.push(Z),this.emitEvent({type:N.TeamMessage,message:{...Z}}),Q.role==="teammate"&&Q.runningCount>0&&Q.agent)Q.pendingSteerMessage=`[MAILBOX] You got a message from ${f}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...Z}}broadcast(f,$,J,H){let W=[];for(let Q of this.members.values()){if(Q.agentId===f)continue;if(Q.role==="lead")continue;W.push(this.sendMessage(f,Q.agentId,$,J,H?.taskId))}return W}appendMissionLog(f){if(!this.members.has(f.agentId))throw Error(`Unknown team member "${f.agentId}"`);let $={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:f.agentId,taskId:f.taskId,kind:f.kind,summary:f.summary,evidence:f.evidence,nextAction:f.nextAction};this.missionLog.push($);let J=this.members.get(f.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:N.TeamMissionLog,entry:{...$}}),{...$}}createOutcome(f){let $={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:f.title,status:"draft",requiredSections:[...new Set(f.requiredSections)],createdBy:f.createdBy,createdAt:new Date};return this.outcomes.set($.id,$),this.emitEvent({type:N.OutcomeCreated,outcome:{...$}}),{...$}}listOutcomes(){return Array.from(this.outcomes.values()).map((f)=>({...f}))}attachOutcomeFragment(f){let $=this.outcomes.get(f.outcomeId);if(!$)throw Error(`Outcome "${f.outcomeId}" was not found`);if(!$.requiredSections.includes(f.section))throw Error(`Section "${f.section}" is not part of outcome "${f.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:f.outcomeId,section:f.section,sourceAgentId:f.sourceAgentId,sourceRunId:f.sourceRunId,content:f.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),$.status==="draft")$.status="in_review";return this.emitEvent({type:N.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment(f){let $=this.outcomeFragments.get(f.fragmentId);if(!$)throw Error(`Fragment "${f.fragmentId}" was not found`);return $.status=f.approved?"reviewed":"rejected",$.reviewedBy=f.reviewedBy,$.reviewedAt=new Date,this.emitEvent({type:N.OutcomeFragmentReviewed,fragment:{...$}}),{...$}}listOutcomeFragments(f){return Array.from(this.outcomeFragments.values()).filter(($)=>$.outcomeId===f).map(($)=>({...$}))}finalizeOutcome(f){let $=this.outcomes.get(f);if(!$)throw Error(`Outcome "${f}" was not found`);let J=this.listOutcomeFragments(f);for(let H of $.requiredSections)if(!J.some((Q)=>Q.section===H&&Q.status==="reviewed"))throw Error(`Outcome "${f}" cannot be finalized. Section "${H}" is missing a reviewed fragment.`);return $.status="finalized",$.finalizedAt=new Date,this.emitEvent({type:N.OutcomeFinalized,outcome:{...$}}),{...$}}cleanup(){for(let f of this.members.values())if(f.role==="teammate"&&f.runningCount>0)throw Error(`Cannot cleanup team while teammate "${f.agentId}" is still running`);if(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let f of this.members.values())if(f.role==="teammate")try{f.agent?.abort()}catch($){if(!AH($))throw $}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[f,$]of this.members.entries())if($.role==="teammate")this.members.delete(f)}requireTask(f){let $=this.tasks.get(f);if(!$)throw Error(`Task "${f}" was not found`);return $}assertDependenciesResolved(f){let $=this.getUnresolvedDependencies(f);if($.length>0)throw Error(`Task "${f.id}" is blocked by "${$[0]}"`)}getUnresolvedDependencies(f){return f.dependsOn.filter(($)=>{let J=this.tasks.get($);return!J||J.status!=="completed"})}trackMeaningfulEvent(f,$){if(this.recordRunActivityFromAgentEvent(f,$),$.type==="iteration_end"&&$.hadToolCalls){this.recordProgressStep(f,`Completed iteration ${$.iteration} with ${$.toolCallCount} tool call(s)`);return}if($.type==="content_end"&&$.contentType==="tool"&&!$.error){this.recordProgressStep(f,`Finished tool "${$.toolName??"unknown"}"`);return}if($.type==="done"){this.appendMissionLog({agentId:f,kind:"done",summary:`Completed a delegated run (${$.iterations} iterations)`});return}if($.type==="error")this.appendMissionLog({agentId:f,kind:"error",summary:$.error.message})}recordRunActivityFromAgentEvent(f,$){let J;switch($.type){case"iteration_start":J=`iteration_${$.iteration}_started`;break;case"content_start":if($.contentType==="tool")J=`running_tool_${$.toolName??"unknown"}`;break;case"content_end":if($.contentType==="tool")J=$.error?this.formatProgressErrorActivity(`tool_${$.toolName??"unknown"}_error`,$.error):`finished_tool_${$.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",$.error.message);break;default:break}if(!J)return;for(let H of this.runs.values()){if(H.agentId!==f||H.status!=="running")continue;this.recordRunProgress(H,J)}}recordRunProgress(f,$){let J=new Date;f.heartbeatAt=J,f.lastProgressAt=J,f.lastProgressMessage=$,f.currentActivity=$,this.emitEvent({type:N.RunProgress,run:{...f},message:$})}formatProgressErrorActivity(f,$){let J=$.replace(/\s+/g," ").trim();if(J.length===0)return f;let H=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${f}: ${H}`}recordProgressStep(f,$,J,H=!1){this.missionStepCounter++;let W=this.members.get(f);if(!W)return;let Q=this.missionStepCounter-W.lastMissionStep,Z=Date.now()-W.lastMissionAt;if(!H&&Q<this.missionLogIntervalSteps&&Z<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:f,taskId:J,kind:"progress",summary:$})}buildMailboxNotification(f){if(f.length===0)return"";let $=[`[MAILBOX] You have ${f.length} unread message(s):`];for(let J of f)$.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),$.push(J.body);return $.push("---"),$.join(`
|
|
454
|
-
`)}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}function
|
|
453
|
+
${$}`:$,Z=J?.continueConversation?await W.agent.continue(Q):await W.agent.run(Q);return this.emitEvent({type:q.TaskEnd,agentId:f,result:Z}),this.recordProgressStep(f,`Completed a delegated run (${Z.iterations} iterations)`,J?.taskId,!0),Z}catch(H){let Q=H instanceof Error?H:Error(String(H));if(this.emitEvent({type:q.TaskEnd,agentId:f,error:Q,messages:W.agent.getMessages()}),!m7(W,Q))this.appendMissionLog({agentId:f,taskId:J?.taskId,kind:"error",summary:Q.message});throw Q}finally{if(W.runningCount--,W.runningCount<=0&&this.members.get(f)?.status!=="stopped")W.status="idle"}}startTeammateRun(f,$,J){let W=`run_${String(++this.runCounter).padStart(5,"0")}`,H={id:W,agentId:f,taskId:J?.taskId,status:"queued",message:$,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(W,H),this.runQueue.push(W),this.emitEvent({type:q.RunQueued,run:{...H}}),this.dispatchQueuedRuns(),{...H}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let f;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let $=this.selectNextDispatchableQueuedRun();f=$.nextDelayedAttemptAt;let J=$.index;if(J<0){this.scheduleQueuedRunDispatch(f);return}let[W]=this.runQueue.splice(J,1),H=W?this.runs.get(W):void 0;if(!H||H.status!=="queued")continue;this.executeQueuedRun(H)}this.scheduleQueuedRunDispatch(f)}selectNextDispatchableQueuedRun(){let f=-1,$=Number.NEGATIVE_INFINITY,J,W=Date.now();for(let H=0;H<this.runQueue.length;H++){let Q=this.runs.get(this.runQueue[H]);if(!Q||Q.status!=="queued")continue;if(Q.nextAttemptAt&&Q.nextAttemptAt.getTime()>W){if(!J||Q.nextAttemptAt<J)J=Q.nextAttemptAt;continue}if(Q.priority>$)$=Q.priority,f=H}return{index:f,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch(f){if(!f)return;let $=Math.max(0,f.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},$)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let f=0;for(let $ of this.runs.values())if($.status==="running")f++;return f}async executeQueuedRun(f){let $=f.currentActivity===x7;f.nextAttemptAt=void 0,f.status="running",f.startedAt=new Date,f.heartbeatAt=new Date,f.currentActivity="run_started",this.emitEvent({type:q.RunStarted,run:{...f}});let J=setInterval(()=>{if(f.status!=="running")return;this.recordRunProgress(f,"heartbeat")},2000);try{let W=$?wU(f):f.message,H=await this.routeToTeammate(f.agentId,W,{taskId:f.taskId,continueConversation:f.continueConversation});f.status="completed",f.result=H,f.endedAt=new Date,f.currentActivity="completed",this.emitEvent({type:q.RunCompleted,run:{...f}})}catch(W){let H=W instanceof Error?W.message:String(W??"Unknown error");f.error=H,f.endedAt=new Date;let Q=this.members.get(f.agentId);if(m7(Q,W))f.status="cancelled",f.currentActivity="cancelled",this.emitEvent({type:q.RunCancelled,run:{...f},reason:H});else if(f.retryCount<f.maxRetries)f.retryCount++,f.status="queued",f.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**f.retryCount)),this.runQueue.push(f.id),this.recordRunProgress(f,`retry_scheduled_${f.retryCount}`);else f.status="failed",f.currentActivity="failed",this.emitEvent({type:q.RunFailed,run:{...f}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns(f){let $=f?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!$&&!["running","queued"].includes(J.status))return!1;if(f?.status&&J.status!==f.status)return!1;if(f?.agentId&&J.agentId!==f.agentId)return!1;return!0}).map((J)=>({...J}))}getRun(f){let $=this.runs.get(f);return $?{...$}:void 0}async awaitRun(f,$=250){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);while(J.status==="queued"||J.status==="running")await g7($);return{...J}}async awaitAllRuns(f=250){while(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))await g7(f);return this.listRuns()}cancelRun(f,$){let J=this.runs.get(f);if(!J)throw Error(`Run "${f}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=$,J.endedAt=new Date,J.currentActivity="cancelled";let W=this.runQueue.indexOf(f);if(W>=0)this.runQueue.splice(W,1);return this.emitEvent({type:q.RunCancelled,run:{...J},reason:$}),{...J}}recoverActiveRuns(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let W=this.members.get(J.agentId);if(!W||W.role!=="teammate"||!W.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:q.RunInterrupted,run:{...J},reason:J.error});continue}let H=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=H,J.lastProgressAt=H,J.lastProgressMessage=f,J.currentActivity=x7,!this.runQueue.includes(J.id))this.runQueue.push(J.id);$.push({...J}),this.emitEvent({type:q.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),$}markStaleRunsInterrupted(f="runtime_recovered"){let $=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=f,J.endedAt=new Date,J.currentActivity="interrupted",$.push({...J}),this.emitEvent({type:q.RunInterrupted,run:{...J},reason:f})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),$}sendMessage(f,$,J,W,H){if(!this.members.has(f))throw Error(`Unknown sender "${f}"`);let Q=this.members.get($);if(!Q)throw Error(`Unknown recipient "${$}"`);let Z={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:f,toAgentId:$,subject:J,body:W,taskId:H,sentAt:new Date};if(this.mailbox.push(Z),this.emitEvent({type:q.TeamMessage,message:{...Z}}),Q.role==="teammate"&&Q.runningCount>0&&Q.agent)Q.pendingSteerMessage=`[MAILBOX] You got a message from ${f}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...Z}}broadcast(f,$,J,W){let H=[];for(let Q of this.members.values()){if(Q.agentId===f)continue;if(Q.role==="lead")continue;H.push(this.sendMessage(f,Q.agentId,$,J,W?.taskId))}return H}appendMissionLog(f){if(!this.members.has(f.agentId))throw Error(`Unknown team member "${f.agentId}"`);let $={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:f.agentId,taskId:f.taskId,kind:f.kind,summary:f.summary,evidence:f.evidence,nextAction:f.nextAction};this.missionLog.push($);let J=this.members.get(f.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:q.TeamMissionLog,entry:{...$}}),{...$}}createOutcome(f){let $={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:f.title,status:"draft",requiredSections:[...new Set(f.requiredSections)],createdBy:f.createdBy,createdAt:new Date};return this.outcomes.set($.id,$),this.emitEvent({type:q.OutcomeCreated,outcome:{...$}}),{...$}}listOutcomes(){return Array.from(this.outcomes.values()).map((f)=>({...f}))}attachOutcomeFragment(f){let $=this.outcomes.get(f.outcomeId);if(!$)throw Error(`Outcome "${f.outcomeId}" was not found`);if(!$.requiredSections.includes(f.section))throw Error(`Section "${f.section}" is not part of outcome "${f.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:f.outcomeId,section:f.section,sourceAgentId:f.sourceAgentId,sourceRunId:f.sourceRunId,content:f.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),$.status==="draft")$.status="in_review";return this.emitEvent({type:q.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment(f){let $=this.outcomeFragments.get(f.fragmentId);if(!$)throw Error(`Fragment "${f.fragmentId}" was not found`);return $.status=f.approved?"reviewed":"rejected",$.reviewedBy=f.reviewedBy,$.reviewedAt=new Date,this.emitEvent({type:q.OutcomeFragmentReviewed,fragment:{...$}}),{...$}}listOutcomeFragments(f){return Array.from(this.outcomeFragments.values()).filter(($)=>$.outcomeId===f).map(($)=>({...$}))}finalizeOutcome(f){let $=this.outcomes.get(f);if(!$)throw Error(`Outcome "${f}" was not found`);let J=this.listOutcomeFragments(f);for(let W of $.requiredSections)if(!J.some((Q)=>Q.section===W&&Q.status==="reviewed"))throw Error(`Outcome "${f}" cannot be finalized. Section "${W}" is missing a reviewed fragment.`);return $.status="finalized",$.finalizedAt=new Date,this.emitEvent({type:q.OutcomeFinalized,outcome:{...$}}),{...$}}cleanup(){for(let f of this.members.values())if(f.role==="teammate"&&f.runningCount>0)throw Error(`Cannot cleanup team while teammate "${f.agentId}" is still running`);if(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let f of this.members.values())if(f.role==="teammate")try{f.agent?.abort()}catch($){if(!L5($))throw $}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[f,$]of this.members.entries())if($.role==="teammate")this.members.delete(f)}requireTask(f){let $=this.tasks.get(f);if(!$)throw Error(`Task "${f}" was not found`);return $}assertDependenciesResolved(f){let $=this.getUnresolvedDependencies(f);if($.length>0)throw Error(`Task "${f.id}" is blocked by "${$[0]}"`)}getUnresolvedDependencies(f){return f.dependsOn.filter(($)=>{let J=this.tasks.get($);return!J||J.status!=="completed"})}trackMeaningfulEvent(f,$){if(this.recordRunActivityFromAgentEvent(f,$),$.type==="iteration_end"&&$.hadToolCalls){this.recordProgressStep(f,`Completed iteration ${$.iteration} with ${$.toolCallCount} tool call(s)`);return}if($.type==="content_end"&&$.contentType==="tool"&&!$.error){this.recordProgressStep(f,`Finished tool "${$.toolName??"unknown"}"`);return}if($.type==="done"){this.appendMissionLog({agentId:f,kind:"done",summary:`Completed a delegated run (${$.iterations} iterations)`});return}if($.type==="error")this.appendMissionLog({agentId:f,kind:"error",summary:$.error.message})}recordRunActivityFromAgentEvent(f,$){let J;switch($.type){case"iteration_start":J=`iteration_${$.iteration}_started`;break;case"content_start":if($.contentType==="tool")J=`running_tool_${$.toolName??"unknown"}`;break;case"content_end":if($.contentType==="tool")J=$.error?this.formatProgressErrorActivity(`tool_${$.toolName??"unknown"}_error`,$.error):`finished_tool_${$.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",$.error.message);break;default:break}if(!J)return;for(let W of this.runs.values()){if(W.agentId!==f||W.status!=="running")continue;this.recordRunProgress(W,J)}}recordRunProgress(f,$){let J=new Date;f.heartbeatAt=J,f.lastProgressAt=J,f.lastProgressMessage=$,f.currentActivity=$,this.emitEvent({type:q.RunProgress,run:{...f},message:$})}formatProgressErrorActivity(f,$){let J=$.replace(/\s+/g," ").trim();if(J.length===0)return f;let W=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${f}: ${W}`}recordProgressStep(f,$,J,W=!1){this.missionStepCounter++;let H=this.members.get(f);if(!H)return;let Q=this.missionStepCounter-H.lastMissionStep,Z=Date.now()-H.lastMissionAt;if(!W&&Q<this.missionLogIntervalSteps&&Z<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:f,taskId:J,kind:"progress",summary:$})}buildMailboxNotification(f){if(f.length===0)return"";let $=[`[MAILBOX] You have ${f.length} unread message(s):`];for(let J of f)$.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),$.push(J.body);return $.push("---"),$.join(`
|
|
454
|
+
`)}emitEvent(f){try{this.onTeamEvent?.(f)}catch{}}}function g7(f){return new Promise(($)=>setTimeout($,f))}function i$(f,$){let J=0;for(let W of f){if(!W.startsWith($))continue;let H=Number.parseInt(W.slice($.length),10);if(Number.isFinite(H))J=Math.max(J,H)}return J}function O5(f,$){switch($.type){case"run_queued":case"run_started":f.activeTeamRunIds.add($.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if($.type==="run_failed")J=$.run.error;else if($.type==="run_cancelled"||$.type==="run_interrupted")J=$.run.error??$.reason;f.activeTeamRunIds.delete($.run.id),f.pendingTeamRunUpdates.push({runId:$.run.id,agentId:$.run.agentId,taskId:$.run.taskId,status:$.type.replace("run_",""),error:J,iterations:$.run.result?.iterations}),u8(f);break}default:break}}async function z5(f,$,J){switch($.type){case"run_progress":await J("onTeamTaskProgress",f,$.run.agentId,$.message,{kind:$.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if($.event.type==="content_start"&&$.event.contentType==="text"&&typeof $.event.text==="string"){let W=$.event.text.replace(/\s+/g," ").trim().slice(0,120);if(W)await J("onTeamTaskProgress",f,$.agentId,W,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",f,$.agentId,$.message);break;case"task_end":{if($.error)await J("onTeamTaskEnd",f,$.agentId,"failed",`[error] ${$.error.message}`,void 0,$.messages);else if($.result?.finishReason==="aborted")await J("onTeamTaskEnd",f,$.agentId,"cancelled","[done] aborted",$.result,$.result.messages);else await J("onTeamTaskEnd",f,$.agentId,"completed",`[done] ${$.result?.finishReason??"completed"}`,$.result,$.result?.messages);break}default:break}}function N5(f,$,J,W){if(!f.runtime.teamRuntime)return;let H=f.runtime.teamRuntime.getTeamName();W({type:"team_progress",payload:{sessionId:$,teamName:H,lifecycle:v8({teamName:H,sessionId:$,event:J}),summary:g8(H,f.runtime.teamRuntime.exportState())}})}function a1(f){return f.activeTeamRunIds.size>0||f.pendingTeamRunUpdates.length>0}function q5(f,$){if(f.aborting)return!1;if(!($==="completed"||$==="max_iterations"))return!1;return f.config.enableAgentTeams===!0&&a1(f)}function u8(f){let $=f.teamRunWaiters.splice(0);for(let J of $)J()}async function w5(f){while(!0){if(f.aborting)return[];if(f.pendingTeamRunUpdates.length>0){let $=[...f.pendingTeamRunUpdates];return f.pendingTeamRunUpdates.length=0,$}if(f.activeTeamRunIds.size===0)return[];await new Promise(($)=>{f.teamRunWaiters.push($)})}}function b5(f,$){let J=$.map((Q)=>{let Z=[`- ${Q.runId} (${Q.agentId}) -> ${Q.status}`];if(Q.taskId)Z.push(` task=${Q.taskId}`);if(typeof Q.iterations==="number")Z.push(` iterations=${Q.iterations}`);if(Q.error)Z.push(` error=${Q.error}`);return Z.join("")}),W=f.activeTeamRunIds.size,H=W>0?`There are still ${W} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return t1(`System-delivered teammate async run updates:
|
|
455
455
|
${J.join(`
|
|
456
456
|
`)}
|
|
457
457
|
|
|
458
|
-
${
|
|
459
|
-
`,"utf8"),
|
|
458
|
+
${H}`,f.config.mode)}function t1(f,$){return bU(f,$==="plan"?"plan":$==="yolo"?"yolo":"act")}var C5=4;class X0{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor(f,$={}){this.adapter=f;this.manifestStore=new _5(f,$.messagesArtifactUploader),this.teamChildren=new x8(f,this.manifestStore,(J,W,H)=>this.toPersistedMessages(J,W,H),X0.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages(f,$,J){if(!f)return;return $?z8($.messages,$,J):O8(f)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest(f,$){this.manifestStore.writeSessionManifest(f,$)}readSessionManifest(f){return this.manifestStore.readSessionManifest(f)}async createRootSessionWithArtifacts(f){let $=f.startedAt??n(),J=f.sessionId.trim(),W=J.length>0?J:`${Date.now()}_${EU(5)}`,H=this.manifestStore.artifacts.sessionMessagesPath(W),Q=this.manifestStore.artifacts.sessionManifestPath(W),Z=g1({metadata:f.metadata,prompt:f.prompt}),j={version:1,session_id:W,source:f.source,pid:f.pid,started_at:$,status:"running",interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspace_root:f.workspaceRoot,team_name:f.teamName,enable_tools:f.enableTools,enable_spawn:f.enableSpawn,enable_teams:f.enableTeams,prompt:f.prompt?.trim()||void 0,metadata:Z,messages_path:H};return await this.adapter.upsertSession({sessionId:W,source:f.source,pid:f.pid,startedAt:$,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:f.interactive,provider:f.provider,model:f.model,cwd:f.cwd,workspaceRoot:f.workspaceRoot,teamName:f.teamName??null,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:j.prompt??null,metadata:z0(j.metadata),hookPath:"",messagesPath:H,updatedAt:n()}),this.manifestStore.initializeMessagesFile(W,H,$),this.manifestStore.writeSessionManifest(Q,j),{manifestPath:Q,messagesPath:H,manifest:j}}async updateSessionStatus(f,$,J){let W;if((await cQ(()=>this.adapter.getSession(f),async(Q)=>{return W=$==="running"?void 0:n(),this.adapter.updateSession({sessionId:f,status:$,endedAt:W??null,exitCode:$==="running"?null:typeof J==="number"?J:null,expectedStatusLock:Q.statusLock})},C5)).updated){if($==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions(f,"cancelled");return{updated:!0,endedAt:W}}return{updated:!1}}async updateSession(f){for(let $=0;$<C5;$++){let J=await this.adapter.getSession(f.sessionId);if(!J)return{updated:!1};let W=J.metadata??void 0,H=f.metadata!==void 0?z0(f.metadata)??{}:z0(W)??{},Q=Z$(typeof W?.title==="string"?W.title:void 0),Z=f.title!==void 0?Z$(f.title):Q??oJ(f.prompt);if(Z)H.title=Z;else delete H.title;let j=f.metadata!==void 0||f.prompt!==void 0||f.title!==void 0;if(!(await this.adapter.updateSession({sessionId:f.sessionId,prompt:f.prompt,metadata:j?Object.keys(H).length>0?H:null:void 0,title:Z,expectedStatusLock:J.statusLock})).updated)continue;let{path:A,manifest:P}=this.manifestStore.readManifestFile(f.sessionId);if(P){if(f.prompt!==void 0)P.prompt=f.prompt??void 0;let B=f.metadata!==void 0?z0(f.metadata)??{}:z0(P.metadata)??{};if(Z)B.title=Z;P.metadata=Object.keys(B).length>0?B:void 0,this.manifestStore.writeSessionManifest(A,P)}return{updated:!0}}return{updated:!1}}queueSpawnRequest(f){return this.teamChildren.queueSpawnRequest(f)}upsertSubagentSession(f){return this.teamChildren.upsertSubagentSession(f)}upsertSubagentSessionFromHook(f){return this.teamChildren.upsertSubagentSessionFromHook(f)}appendSubagentHookAudit(f,$){return this.teamChildren.appendSubagentHookAudit($),Promise.resolve()}persistSessionMessages(f,$,J){let W=O8($);return this.manifestStore.persistSessionMessages(f,W,J)}applySubagentStatus(f,$){return this.teamChildren.applySubagentStatus(f,$)}applySubagentStatusBySessionId(f,$){return this.teamChildren.applySubagentStatusBySessionId(f,$)}applyStatusToRunningChildSessions(f,$){return this.teamChildren.applyStatusToRunningChildSessions(f,$)}onTeamTaskStart(f,$,J){return this.teamChildren.onTeamTaskStart(f,$,J)}onTeamTaskEnd(f,$,J,W,H,Q){return this.teamChildren.onTeamTaskEnd(f,$,J,W,H,Q)}onTeamTaskProgress(f,$,J,W){return this.teamChildren.onTeamTaskProgress(f,$,J,W)}handleSubAgentStart(f,$){return this.teamChildren.handleSubAgentStart(f,$)}handleSubAgentEnd(f,$){return this.teamChildren.handleSubAgentEnd(f,$)}isPidAlive(f){if(!Number.isFinite(f)||f<=0)return!1;try{return process.kill(Math.floor(f),0),!0}catch($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="EPERM"}}async reconcileDeadRunningSession(f){if(f.status!=="running"||this.isPidAlive(f.pid))return f;let $=n(),J=X0.STALE_REASON;for(let W=0;W<C5;W++){let H=await this.adapter.getSession(f.sessionId);if(!H)return;if(H.status!=="running")return H;let Q={...H.metadata??{},terminal_marker:J,terminal_marker_at:$,terminal_marker_pid:H.pid,terminal_marker_source:X0.STALE_SOURCE},Z=await this.adapter.updateSession({sessionId:H.sessionId,status:"failed",endedAt:$,exitCode:1,metadata:Q,expectedStatusLock:H.statusLock});if(!Z.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(H.sessionId,"failed");let j=uQ(H,{status:"failed",endedAt:$,exitCode:1,metadata:Q}),{path:X}=this.manifestStore.readManifestFile(H.sessionId);return this.manifestStore.writeSessionManifest(X,j),this.manifestStore.appendStaleSessionHookLog($,H.sessionId,H.pid,J,X0.STALE_SOURCE),{...H,status:"failed",endedAt:$,exitCode:1,metadata:Q,statusLock:Z.statusLock,updatedAt:$}}return await this.adapter.getSession(f.sessionId)}async listSessions(f=200){let $=Math.max(1,Math.floor(f)),J=Math.min($*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,$).map((H)=>{let Q=z0(H.metadata??void 0),Z=this.manifestStore.readSessionManifest(H.sessionId),j=Z$(typeof Z?.metadata?.title==="string"?Z.metadata.title:void 0),X=j?{...Q??{},title:j}:Q;return{...H,metadata:X}})}async reconcileDeadSessions(f=2000){let $=await this.adapter.listSessions({limit:Math.max(1,Math.floor(f)),status:"running"}),J=0;for(let W of $){let H=await this.reconcileDeadRunningSession(W);if(H&&H.status!==W.status)J++}return J}async deleteSession(f){let $=f.trim();if(!$)throw Error("session id is required");let J=await this.adapter.getSession($);if(!J)return{deleted:!1};if(await this.adapter.deleteSession($,!1),!J.isSubagent){let W=await this.adapter.listSessions({limit:2000,parentSessionId:$});await this.adapter.deleteSession($,!0),await Promise.allSettled(W.map(async(H)=>{await T5(H.cwd,H.sessionId),i1(H.messagesPath),i1(this.manifestStore.artifacts.sessionManifestPath(H.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(H.sessionId)}))}if(await T5(J.cwd,$),i1(J.messagesPath),i1(this.manifestStore.artifacts.sessionManifestPath($,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty($);else{let W=new Set([this.manifestStore.artifacts.sessionArtifactsDir($)]);for(let H of[J.messagesPath])if(typeof H==="string"&&H.trim().length>0)W.add(CU(H));for(let H of W)this.manifestStore.artifacts.removeDir(H)}return{deleted:!0}}}function S5(){return new Date().toISOString()}function c7(f,$){let J=`${f}.tmp`;IU(J,`${JSON.stringify($,null,2)}
|
|
459
|
+
`,"utf8"),kU(J,f)}class d7{sessionsDirPath;constructor(f=mU()){this.sessionsDirPath=f}ensureSessionsDir(){if(!E5(this.sessionsDirPath))SU(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return u7(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return u7(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let f=this.indexPath();if(!E5(f))return{version:1,sessions:{}};try{let $=JSON.parse(v7(f,"utf8"));if($?.version===1&&$.sessions)return $}catch{}return{version:1,sessions:{}}}writeIndex(f){c7(this.indexPath(),f)}readQueue(){let f=this.spawnQueuePath();if(!E5(f))return{version:1,nextId:1,requests:[]};try{let $=JSON.parse(v7(f,"utf8"));if($?.version===1&&typeof $.nextId==="number"&&Array.isArray($.requests))return $}catch{}return{version:1,nextId:1,requests:[]}}writeQueue(f){c7(this.spawnQueuePath(),f)}async upsertSession(f){let $=this.readIndex();$.sessions[f.sessionId]=f,this.writeIndex($)}async getSession(f){return this.readIndex().sessions[f]}async listSessions(f){return Object.values(this.readIndex().sessions).filter(($)=>f.parentSessionId!==void 0?$.parentSessionId===f.parentSessionId:!0).filter(($)=>f.status!==void 0?$.status===f.status:!0).sort(($,J)=>J.startedAt.localeCompare($.startedAt)).slice(0,f.limit)}async updateSession(f){let $=this.readIndex(),J=$.sessions[f.sessionId];if(!J)return{updated:!1,statusLock:0};if(f.expectedStatusLock!==void 0&&J.statusLock!==f.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let W=f.expectedStatusLock!==void 0?f.expectedStatusLock+1:J.statusLock,H={...J,status:f.status??J.status,endedAt:f.endedAt!==void 0?f.endedAt:J.endedAt??null,exitCode:f.exitCode!==void 0?f.exitCode:J.exitCode??null,prompt:f.prompt!==void 0?f.prompt:J.prompt??null,metadata:f.metadata!==void 0?f.metadata??null:J.metadata??null,parentSessionId:f.parentSessionId!==void 0?f.parentSessionId??null:J.parentSessionId??null,parentAgentId:f.parentAgentId!==void 0?f.parentAgentId??null:J.parentAgentId??null,agentId:f.agentId!==void 0?f.agentId??null:J.agentId??null,conversationId:f.conversationId!==void 0?f.conversationId??null:J.conversationId??null,statusLock:W,isSubagent:f.setRunning||f.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:S5()};if(f.setRunning)H.status="running",H.endedAt=null,H.exitCode=null;return $.sessions[f.sessionId]=H,this.writeIndex($),{updated:!0,statusLock:H.statusLock}}async deleteSession(f,$){let J=this.readIndex();if(!J.sessions[f])return!1;if(delete J.sessions[f],$){for(let H of Object.values(J.sessions))if(H.parentSessionId===f)delete J.sessions[H.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest(f){let $=this.readQueue();$.requests.push({id:$.nextId,rootSessionId:f.rootSessionId,parentAgentId:f.parentAgentId,task:f.task,systemPrompt:f.systemPrompt,createdAt:S5()}),$.nextId+=1,this.writeQueue($)}async claimSpawnRequest(f,$){let J=this.readQueue(),W=J.requests.find((H)=>H.rootSessionId===f&&H.parentAgentId===$&&!H.consumedAt);if(!W)return;return W.consumedAt=S5(),this.writeQueue(J),W.task}}class k5 extends X0{constructor(f,$={}){super(new d7(f),$)}ensureSessionsDir(){return super.ensureSessionsDir()}}import{existsSync as xU,mkdirSync as gU}from"node:fs";import{resolveSessionDataDir as vU}from"@cline/shared/storage";var I5=`
|
|
460
460
|
session_id AS sessionId,
|
|
461
461
|
source,
|
|
462
462
|
pid,
|
|
@@ -483,43 +483,43 @@ ${W}`,f.config.mode)}function d1(f,$){return ZU(f,$==="plan"?"plan":$==="yolo"?"
|
|
|
483
483
|
metadata_json AS metadata,
|
|
484
484
|
hook_path AS hookPath,
|
|
485
485
|
messages_path AS messagesPath,
|
|
486
|
-
updated_at AS updatedAt`;function
|
|
486
|
+
updated_at AS updatedAt`;function m5(f){f.interactive=f.interactive===1,f.enableTools=f.enableTools===1,f.enableSpawn=f.enableSpawn===1,f.enableTeams=f.enableTeams===1,f.isSubagent=f.isSubagent===1;let $=f.metadata;if(typeof $==="string"&&$.trim())try{let J=JSON.parse($);f.metadata=J&&typeof J==="object"&&!Array.isArray(J)?J:null}catch{f.metadata=null}else f.metadata=null;return f}function x5(f){if(!f||Object.keys(f).length===0)return null;return JSON.stringify(f)}function r7(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class l7{store;sessionsDirPath;constructor(f,$=vU()){this.store=f;this.sessionsDirPath=$}ensureSessionsDir(){if(!xU(this.sessionsDirPath))gU(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession(f){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
487
487
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
488
488
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
489
489
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
490
490
|
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
491
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,f.statusLock,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.isSubagent?1:0,f.prompt??null,
|
|
491
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,f.endedAt??null,f.exitCode??null,f.status,f.statusLock,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.isSubagent?1:0,f.prompt??null,x5(f.metadata),"",f.hookPath??"",f.messagesPath??null,f.updatedAt])}async getSession(f){let $=this.store.queryOne(`SELECT ${I5} FROM sessions WHERE session_id = ?`,[f]);return $?m5($):void 0}async listSessions(f){let $=[],J=[];if(f.parentSessionId)$.push("parent_session_id = ?"),J.push(f.parentSessionId);if(f.status)$.push("status = ?"),J.push(f.status);let W=$.length>0?`WHERE ${$.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${I5}
|
|
492
492
|
FROM sessions
|
|
493
|
-
${
|
|
493
|
+
${W}
|
|
494
494
|
ORDER BY started_at DESC
|
|
495
|
-
LIMIT ?`,[...J,f.limit]).map(
|
|
495
|
+
LIMIT ?`,[...J,f.limit]).map(m5)}async updateSession(f){if(f.setRunning){if(f.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
|
|
496
496
|
SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
|
|
497
497
|
parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
|
|
498
498
|
prompt = COALESCE(prompt, ?)
|
|
499
|
-
WHERE session_id = ? AND status_lock = ?`,[n(),f.expectedStatusLock+1,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.prompt??null,f.sessionId,f.expectedStatusLock]).changes??0)>0,statusLock:f.expectedStatusLock+1}}let $=[],J=[];if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt??null);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(
|
|
499
|
+
WHERE session_id = ? AND status_lock = ?`,[n(),f.expectedStatusLock+1,f.parentSessionId??null,f.parentAgentId??null,f.agentId??null,f.conversationId??null,f.prompt??null,f.sessionId,f.expectedStatusLock]).changes??0)>0,statusLock:f.expectedStatusLock+1}}let $=[],J=[];if(f.status!==void 0)$.push("status = ?"),J.push(f.status);if(f.endedAt!==void 0)$.push("ended_at = ?"),J.push(f.endedAt);if(f.exitCode!==void 0)$.push("exit_code = ?"),J.push(f.exitCode);if(f.prompt!==void 0)$.push("prompt = ?"),J.push(f.prompt??null);if(f.metadata!==void 0)$.push("metadata_json = ?"),J.push(x5(f.metadata));if(f.parentSessionId!==void 0)$.push("parent_session_id = ?"),J.push(f.parentSessionId??null);if(f.parentAgentId!==void 0)$.push("parent_agent_id = ?"),J.push(f.parentAgentId??null);if(f.agentId!==void 0)$.push("agent_id = ?"),J.push(f.agentId??null);if(f.conversationId!==void 0)$.push("conversation_id = ?"),J.push(f.conversationId??null);if($.length===0){let Z=await this.getSession(f.sessionId);return{updated:!!Z,statusLock:Z?.statusLock??0}}let W=0;if(f.expectedStatusLock!==void 0)W=f.expectedStatusLock+1,$.push("status_lock = ?"),J.push(W);$.push("updated_at = ?"),J.push(n());let H=`UPDATE sessions SET ${$.join(", ")} WHERE session_id = ?`;if(J.push(f.sessionId),f.expectedStatusLock!==void 0)H+=" AND status_lock = ?",J.push(f.expectedStatusLock);if((this.store.run(H,J).changes??0)===0)return{updated:!1,statusLock:0};if(f.expectedStatusLock===void 0)W=(await this.getSession(f.sessionId))?.statusLock??0;return{updated:!0,statusLock:W}}async deleteSession(f,$){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[f]).changes??0;if($)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[f]);return J>0}async enqueueSpawnRequest(f){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
|
|
500
500
|
VALUES (?, ?, ?, ?, ?, NULL)`,[f.rootSessionId,f.parentAgentId,f.task??null,f.systemPrompt??null,n()])}async claimSpawnRequest(f,$){let J=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
|
|
501
501
|
WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
|
|
502
|
-
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 = ?",[n(),J.id]),J.task??void 0}}class
|
|
502
|
+
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 = ?",[n(),J.id]),J.task??void 0}}class S0 extends X0{store;constructor(f,$={}){super(new l7(f,$.sessionArtifactsDir),$);this.store=f}createRootSession(f){this.store.run(`INSERT OR REPLACE INTO sessions (
|
|
503
503
|
session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
|
|
504
504
|
provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
|
|
505
505
|
parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
|
|
506
506
|
metadata_json, transcript_path, hook_path, messages_path, updated_at
|
|
507
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,null,null,"running",0,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,null,null,null,null,0,f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"","",f.messagesPath,n()])}}import{homedir as
|
|
508
|
-
...[truncated ${f.length-$} chars]`}function
|
|
509
|
-
${
|
|
507
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[f.sessionId,f.source,f.pid,f.startedAt,null,null,"running",0,f.interactive?1:0,f.provider,f.model,f.cwd,f.workspaceRoot,f.teamName??null,f.enableTools?1:0,f.enableSpawn?1:0,f.enableTeams?1:0,null,null,null,null,0,f.prompt??null,f.metadata?JSON.stringify(f.metadata):null,"","",f.messagesPath,n()])}}import{readdirSync as rD}from"node:fs";import{homedir as lD}from"node:os";import{isAbsolute as pD,join as OW,resolve as zW}from"node:path";import{createSessionId as iD,isLikelyAuthError as nD,normalizeUserInput as aD}from"@cline/shared";import{setHomeDirIfUnset as tD}from"@cline/shared/storage";import{createHandler as pU}from"@cline/llms";var p7=200000,i7=0.95;var g5=20000;var n7=8;function uU(f){return Math.max(1,Math.ceil(f.length/4))}function V$(f,$){if(f.length<=$)return f;return`${f.slice(0,$)}
|
|
508
|
+
...[truncated ${f.length-$} chars]`}function cU(f){if(typeof f==="string")return V$(f,2000);return f.map(($)=>{switch($.type){case"text":return $.text;case"file":return`<file path="${$.path}">
|
|
509
|
+
${V$($.content,2000)}
|
|
510
510
|
</file>`;case"image":return`[image:${$.mediaType}]`;default:return""}}).join(`
|
|
511
|
-
`)}function
|
|
512
|
-
`)}function
|
|
511
|
+
`)}function dU(f){return Object.entries(f).map(([$,J])=>`${$}=${JSON.stringify(J)}`).join(", ")}function a7(f){if(typeof f.content==="string")return`[${f.role==="user"?"User":"Bot"}]: ${f.content}`;let $=[];for(let J of f.content)switch(J.type){case"text":$.push(`[${f.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":$.push(`[Bot thinking]: ${V$(J.thinking,2000)}`);break;case"redacted_thinking":$.push("[Bot thinking]: [redacted]");break;case"tool_use":$.push(`[Bot tool calls]: ${J.name}(${dU(J.input)})`);break;case"tool_result":$.push(`[Tool result]: ${cU(J.content)}`);break;case"file":$.push(`[${f.role==="user"?"User":"Bot"} file ${J.path}]: ${V$(J.content,2000)}`);break;case"image":$.push(`[${f.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return $.join(`
|
|
512
|
+
`)}function t7(f){return f.map(a7).join(`
|
|
513
513
|
|
|
514
|
-
`).trim()}function
|
|
515
|
-
`):"- none",J=f.modifiedFiles.length>0?f.modifiedFiles.map((
|
|
514
|
+
`).trim()}function s7(){let f=new WeakMap;return($)=>{let J=$,W=f.get(J);if(typeof W==="number")return W;let H=uU(a7($));return f.set(J,H),H}}function e1(f){return f.metadata?.kind==="compaction_summary"}function v5(f){if(!e1(f))return;let $=f.metadata;if(!$)return;let J=$.details;return{kind:"compaction_summary",summary:String($.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[]},tokensBefore:Number($.tokensBefore??0),generatedAt:Number($.generatedAt??0)}}function rU(f){if(f.role!=="user"||!Array.isArray(f.content))return!1;return f.content.length>0&&f.content.every(($)=>$.type==="tool_result")}function o7(f){return f.role==="user"&&!rU(f)&&!e1(f)}function e7(f){for(let $=0;$<f.length;$+=1)if(o7(f[$]))return $;return-1}function u5(f){for(let $=f.length-1;$>=0;$-=1)if(o7(f[$]))return $;return 0}function fZ(f){for(let $=f.length-1;$>=0;$-=1)if(f[$].role==="assistant")return $;return-1}function $Z(f){for(let $=f.length-1;$>=0;$-=1)if(e1(f[$]))return $;return-1}function JZ(f,$,J){let W=u5(f);if(W<=0)return 0;let H=0,Q=f.length;for(let Z=f.length-1;Z>=0;Z-=1)if(H+=J(f[Z]),Q=Z,H>=$)break;if(Q<=0)return 0;return Math.min(Q,W)}function o1(f){if(typeof f==="string"&&f.trim().length>0)return[f];if(Array.isArray(f))return f.flatMap(($)=>o1($));if(f&&typeof f==="object"){let $=f,J=[];for(let W of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...o1($[W]));if(Array.isArray($.files)){for(let W of $.files)if(W&&typeof W==="object")J.push(...o1(W.path))}if(Array.isArray($.file_paths))J.push(...o1($.file_paths));return J}return[]}function s1(f,$){let J=new Set(f);for(let W of $){let H=W.trim();if(!H)continue;J.add(H)}return[...J].sort((W,H)=>W.localeCompare(H))}function WZ(f){let $=[],J=[];for(let W of f){let H=v5(W);if(H){$=s1($,H.details.readFiles),J=s1(J,H.details.modifiedFiles);continue}if(!Array.isArray(W.content))continue;for(let Q of W.content){if(Q.type==="file"){$=s1($,[Q.path]);continue}if(Q.type!=="tool_use")continue;let Z=o1(Q.input);if(Q.name==="read_files"){$=s1($,Z);continue}if(Q.name==="editor"||Q.name==="apply_patch")J=s1(J,Z)}}return{readFiles:$,modifiedFiles:J}}function lU(f){let $=f.readFiles.length>0?f.readFiles.map((W)=>`- ${W}`).join(`
|
|
515
|
+
`):"- none",J=f.modifiedFiles.length>0?f.modifiedFiles.map((W)=>`- ${W}`).join(`
|
|
516
516
|
`):"- none";return`## Files
|
|
517
517
|
Read:
|
|
518
518
|
${$}
|
|
519
519
|
Modified:
|
|
520
|
-
${J}`}function
|
|
520
|
+
${J}`}function HZ(f,$){if(/^## Files$/im.test(f))return f.trim();return`${f.trim()}
|
|
521
521
|
|
|
522
|
-
${
|
|
522
|
+
${lU($)}`.trim()}function QZ(f){let $=[`Summarize this session for continuation. Be concise and factual.
|
|
523
523
|
|
|
524
524
|
## Goal
|
|
525
525
|
One sentence: what is being built or fixed.
|
|
@@ -541,24 +541,24 @@ Edited: ${f.fileOps.modifiedFiles.join(", ")||"none"}`];if(f.previousSummary?.tr
|
|
|
541
541
|
${f.previousSummary.trim()}`);return $.push(`Conversation:
|
|
542
542
|
${f.conversationText||"(empty)"}`),$.join(`
|
|
543
543
|
|
|
544
|
-
`)}function
|
|
544
|
+
`)}function ZZ(f){let $=f.summarizer;if(!$)return{...f.activeProviderConfig,maxOutputTokens:1024,thinking:!1};let J=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0;return{...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:$.knownModels??J?.knownModels,maxOutputTokens:$.maxOutputTokens??1024,thinking:!1}}function jZ(f){return{role:"user",content:`Context summary:
|
|
545
545
|
|
|
546
|
-
${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fileOps,tokensBefore:f.tokensBefore,generatedAt:Date.now()}}}async function DU(f){let $=TU(f.providerConfig),J="";for await(let H of $.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:f.request}])){if(H.type==="text"){J+=H.text;continue}if(H.type==="done"&&!H.success&&H.error)throw Error(H.error)}return f.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:f.providerConfig.modelId,providerId:f.providerConfig.providerId}),J.trim()}async function $Z(f){let $=f.context.messages;if($.length<2)return;let J=aQ($,f.preserveRecentTokens,f.estimateMessageTokens);if(J<=0||J>=$.length)return;let H=$.slice(0,J),W=nQ(H),Q=W>=0?qH(H[W])?.summary:void 0,Z=W>=0?H.slice(W+1):H;if(Z.length===0)return;let j=tQ(H),P=dQ(Z),X=await DU({providerConfig:eQ({activeProviderConfig:f.providerConfig,summarizer:f.summarizer}),request:oQ({previousSummary:Q,conversationText:P,fileOps:j}),logger:f.logger});if(!X.trim())return;let V=sQ(X,j),Y=$.reduce((R,U)=>R+f.estimateMessageTokens(U),0),B=[fZ({summary:V,fileOps:j,tokensBefore:Y}),...$.slice(J)],A=B.reduce((R,U)=>R+f.estimateMessageTokens(U),0);return f.logger?.debug("Performed agentic compaction",{messagesBefore:$.length,messagesAfter:B.length,messagesSummarized:J,messagesPreserved:$.length-J,tokensBefore:Y,tokensAfter:A,contextWindowTokens:f.context.contextWindowTokens}),{messages:B}}function WZ(f){if(p1(f))return;if(typeof f.content==="string"){let J=f.content.trim();return J?{...f,content:J}:void 0}let $=f.content.filter((J)=>J.type!=="text"||J.text.trim());if($.length===0)return;return{...f,content:$.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J)}}function i1(f,$){return f.reduce((J,H)=>J+$(H),0)}function JZ(f,$){let J=Math.max(1,$),H=Math.max(16,J*4);if(typeof f.content==="string"){let Z=X$(f.content,H).trim();return{...f,content:Z||"..."}}let W=H,Q=f.content.map((Z)=>{if(Z.type!=="text"||W<=0)return Z;let j=X$(Z.text,W).trim();return W-=j.length,{...Z,text:j||"..."}});return{...f,content:Q}}function MU(f,$){let J=pQ(f),H=bH(f),W=iQ(f),Q=[];for(let Z=0;Z<f.length;Z+=1){let j=WZ(f[Z]);if(!j)continue;Q.push({index:Z,message:j,estimatedTokens:$(j),isFirstUser:Z===J,isLastUser:Z===H,isLastAssistant:Z===W})}return Q}function HZ(f,$,J,H){let W=f[$];W.message=J,W.estimatedTokens=H(J)}function g8(f,$,J,H){let W=i1(f.map((Q)=>Q.message),H);for(let Q=0;Q<f.length&&W>J;){if(!$(f[Q])){Q+=1;continue}W-=f[Q].estimatedTokens,f.splice(Q,1)}}function _U(f,$,J){let H=i1(f.map((Q)=>Q.message),J);if(H<=$)return;for(let Q=f.length-1;Q>=0&&H>$;Q-=1){let Z=f[Q];if(Z.isFirstUser)continue;let j=Math.max(uQ,Z.estimatedTokens-(H-$));if(j>=Z.estimatedTokens)continue;HZ(f,Q,JZ(Z.message,j),J),H=i1(f.map((P)=>P.message),J)}if(H<=$)return;let W=f.findIndex((Q)=>Q.isFirstUser);if(W>=0){let Q=Math.max(1,f[W].estimatedTokens-(H-$));HZ(f,W,JZ(f[W].message,Q),J)}}function LU(f,$){return JSON.stringify(f)!==JSON.stringify($)}function QZ(f){let $=Math.max(1,Math.min(f.context.triggerTokens,f.context.contextWindowTokens)),J=MU(f.context.messages,f.estimateMessageTokens);if(J.length===0)return;g8(J,(Z)=>Z.message.role==="assistant"&&!Z.isLastAssistant,$,f.estimateMessageTokens),g8(J,(Z)=>Z.message.role==="user"&&!Z.isFirstUser&&!Z.isLastUser,$,f.estimateMessageTokens),g8(J,(Z)=>Z.message.role==="assistant"&&Z.isLastAssistant,$,f.estimateMessageTokens),g8(J,(Z)=>Z.message.role==="user"&&Z.isLastUser&&!Z.isFirstUser,$,f.estimateMessageTokens),_U(J,$,f.estimateMessageTokens);let H=J.map((Z)=>Z.message);if(!LU(f.context.messages,H))return;let W=i1(f.context.messages.map((Z)=>WZ(Z)??Z),f.estimateMessageTokens),Q=i1(H,f.estimateMessageTokens);return f.logger?.debug("Performed basic compaction",{messagesBefore:f.context.messages.length,messagesAfter:H.length,messagesRemoved:f.context.messages.length-H.length,tokensBefore:W,tokensAfter:Q,targetTokens:$,contextWindowTokens:f.context.contextWindowTokens}),{messages:H}}var zU={basic:({context:f,estimateMessageTokens:$,logger:J})=>QZ({context:f,estimateMessageTokens:$,logger:J}),agentic:({context:f,providerConfig:$,compaction:J,mode:H,estimateMessageTokens:W,logger:Q})=>$Z({context:f,providerConfig:$,summarizer:J?.summarizer,preserveRecentTokens:H==="manual"?Math.min(J?.preserveRecentTokens??NH,f.triggerTokens):J?.preserveRecentTokens??NH,estimateMessageTokens:W,logger:Q})};function OU(f){if(typeof f.config.reserveTokens==="number"){let H=Math.max(0,f.config.reserveTokens),W=Math.max(0,f.contextWindowTokens-H);return{shouldCompact:f.inputTokens>W,triggerTokens:W,thresholdRatio:f.contextWindowTokens>0?W/f.contextWindowTokens:0}}let $=f.config.thresholdRatio??vQ,J=f.contextWindowTokens*$;return{shouldCompact:f.inputTokens>J,triggerTokens:J,thresholdRatio:$}}function NU(f){let $=typeof f.manualTargetRatio==="number"&&Number.isFinite(f.manualTargetRatio)?f.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,$)),H=Math.max(1,Math.floor(Math.min(f.autoTriggerTokens,f.inputTokens*J)));return{triggerTokens:H,thresholdRatio:f.contextWindowTokens>0?H/f.contextWindowTokens:0}}function wH(f,$={}){let J=f.compaction;if(J?.enabled!==!0)return;let H=f.providerConfig??{providerId:f.providerId,modelId:f.modelId},W=rQ(),Q=J?.strategy??"basic",Z=zU[Q],j=$.mode??"auto";return async(P)=>{let X=P.apiMessages.reduce((F,K)=>F+W(K),0),V=J?.contextWindowTokens??P.model.info?.contextWindow??gQ;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let Y=OU({inputTokens:X,contextWindowTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if(j==="auto"&&!Y.shouldCompact)return;let B=j==="manual"?NU({inputTokens:X,contextWindowTokens:V,autoTriggerTokens:Y.triggerTokens,manualTargetRatio:$.manualTargetRatio}):Y,A={agentId:P.agentId,conversationId:P.conversationId,parentAgentId:P.parentAgentId,iteration:P.iteration,messages:P.messages,model:P.model,contextWindowTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,utilizationRatio:V>0?X/V:0},R=j==="manual"?"manual_compaction":"auto_compaction";P.emitStatusNotice?.(j==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:P.iteration,triggerTokens:B.triggerTokens,contextWindowTokens:V});let U=P.messages.length,y=J?.compact?await J.compact(A):await Z({context:A,providerConfig:{...H,abortSignal:P.abortSignal},compaction:J,mode:j,estimateMessageTokens:W,logger:f.logger});if(y?.messages){let F=y.messages.reduce((K,M)=>K+W(M),0);f.logger?.log("Context compaction completed",{severity:"info",strategy:Q,contextWindowTokens:V,inputTokens:X,afterTokens:F,tokensSaved:X-F,utilizationBefore:`${(X/V*100).toFixed(1)}%`,utilizationAfter:`${(F/V*100).toFixed(1)}%`,thresholdTrigger:`${(B.thresholdRatio*100).toFixed(1)}%`,messagesBefore:U,messagesAfter:y.messages.length,messagesRemoved:U-y.messages.length})}return y}}Af();function c$(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function d$(f,$){return{inputTokens:f.inputTokens+Math.max(0,$.inputTokens??0),outputTokens:f.outputTokens+Math.max(0,$.outputTokens??0),cacheReadTokens:f.cacheReadTokens+Math.max(0,$.cacheReadTokens??0),cacheWriteTokens:f.cacheWriteTokens+Math.max(0,$.cacheWriteTokens??0),totalCost:f.totalCost+Math.max(0,$.totalCost??0)}}function u$(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function CH(f){let $=c$();for(let J of f){let H=J.metrics;if(!H)continue;$=d$($,{inputTokens:u$(H.inputTokens),outputTokens:u$(H.outputTokens),cacheReadTokens:u$(H.cacheReadTokens),cacheWriteTokens:u$(H.cacheWriteTokens),totalCost:u$(H.cost)})}return $}function qU(f){for(let $=f.length-1;$>=0;$-=1){let J=f[$];if(J?.role!=="assistant")continue;let H=u$(J.metrics?.inputTokens);return H>0?H:void 0}return}function bU(f){if(!f||typeof f!=="object")return;let $=f,J=$.skill??$.skill_name??$.skillName;if(typeof J!=="string")return;let H=J.trim();return H.length>0?H:void 0}function EH(f){if(!f||typeof f!=="object")return{};let $=f;return{agentId:typeof $.agentId==="string"?$.agentId:void 0,conversationId:typeof $.conversationId==="string"?$.conversationId:void 0,parentAgentId:typeof $.parentAgentId==="string"?$.parentAgentId:void 0}}function Q0(f){let $=f.agentId?.trim();if(!$)return;let J=f.parentAgentId?.trim()||void 0,H=f.teamRole,W="root";if(H==="teammate")W="team_teammate";else if(H==="lead")W="team_lead";else if(J)W="subagent";return{agentId:$,agentKind:W,conversationId:f.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:f.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:f.teamId?.trim()||void 0,teamName:f.teamName?.trim()||void 0,teamRole:H,teamAgentId:f.teamAgentId?.trim()||void 0}}function SH(f,$,J){let{sessionId:H,config:W,liveSession:Q,emit:Z}=f,j=W.telemetry,P=Q?.runtime.teamRuntime,X=J?.isPrimaryAgentEvent??!0,V=EH($),Y=Q0({agentId:J?.agentId??V.agentId,conversationId:J?.conversationId??V.conversationId,parentAgentId:J?.parentAgentId??V.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??P?.getTeamId(),teamName:J?.teamName??P?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if($.type==="content_start"&&$.contentType==="tool"&&$.toolName==="skills"){let B=bU($.input);if(B)I4(j,{ulid:H,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:W.providerId,modelId:W.modelId,...Y})}if($.type==="content_end"&&$.contentType==="tool"){let B=$.toolName??"unknown",A=!$.error;if(m4(j,{ulid:H,tool:B,autoApproved:void 0,success:A,modelId:W.modelId,provider:W.providerId,...Y}),!A&&(B==="editor"||B==="apply_patch"))x4(j,{ulid:H,modelId:W.modelId,provider:W.providerId,errorType:$.error,...Y})}if($.type==="notice"&&$.reason==="api_error")V2(j,{ulid:H,model:W.modelId,provider:W.providerId,errorMessage:$.message,...Y});if($.type==="error")V2(j,{ulid:H,model:W.modelId,provider:W.providerId,errorMessage:$.error?.message??"unknown error",...Y});if($.type==="usage"&&X&&Q?.turnUsageBaseline)f.usageBySession.set(H,d$(Q.turnUsageBaseline,{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost})),$1(j,{ulid:H,provider:W.providerId,model:W.modelId,source:"assistant",mode:W.mode,...Y}),S4(j,{ulid:H,tokensIn:$.inputTokens,tokensOut:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost,model:W.modelId,...Y});if($.type==="iteration_end"&&X)f.persistMessages(H,Q?.agent.getMessages()??[],Q?.config.systemPrompt);Z({type:"agent_event",payload:{sessionId:H,event:$,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(X?"lead":void 0):void 0}}),Z({type:"chunk",payload:{sessionId:H,stream:"agent",chunk:C7($),ts:Date.now()}})}function q0(f){return f.workspaceRoot??f.cwd}import{hasRuntimeConfigExtension as WG}from"@cline/shared";import{spawn as gU}from"node:child_process";import{appendFileSync as vU,readFileSync as uU}from"node:fs";import{join as cU}from"node:path";import{augmentNodeCommandForDebug as XZ,withResolvedClineBuildEnv as vH}from"@cline/shared";import{ensureHookLogDir as jZ}from"@cline/shared/storage";function v8(f,$){if(!$)return;return{name:f,manifest:{capabilities:["hooks"]},hooks:$}}import{existsSync as wU,readdirSync as CU}from"node:fs";import{basename as EU,extname as SU,join as kU}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as ZZ,resolveHooksConfigSearchPaths as mU}from"@cline/shared/storage";function kH(f){return mU(f)}var u8;((V)=>{V.TaskStart="TaskStart";V.TaskResume="TaskResume";V.TaskCancel="TaskCancel";V.TaskComplete="TaskComplete";V.TaskError="TaskError";V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.UserPromptSubmit="UserPromptSubmit";V.PreCompact="PreCompact";V.SessionShutdown="SessionShutdown"})(u8||={});var mH={["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"},IU=new Map(Object.values(u8).map((f)=>[f.toLowerCase(),f])),xU=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function IH(f){let $=SU(f).toLowerCase();if(!xU.has($))return;let J=EU(f,$).trim().toLowerCase();return IU.get(J)}function r$(f){let $=[],J=new Set,H=kH(f).filter((W)=>wU(W));for(let W of H)try{for(let Q of CU(W,{withFileTypes:!0})){if(!Q.isFile())continue;let Z=IH(Q.name);if(!Z)continue;let j=kU(W,Q.name);if(J.has(j))continue;J.add(j),$.push({fileName:Z,hookEventName:mH[Z],path:j})}}catch{}return $.sort((W,Q)=>W.path.localeCompare(Q.path))}function d8(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,H]of Object.entries(f))$[J]=typeof H==="string"?H:JSON.stringify(H);return $}function c8(f,$,J){let H=J instanceof Error?`: ${J.message}`:"",W=`${$}${H}`;if(f){try{f.log(W,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(W)}function dU(f,$){if(!$)return f;if(!f)return{...$};let J=[f.context,$.context].filter((W)=>typeof W==="string"&&W.length>0).join(`
|
|
547
|
-
`),
|
|
548
|
-
`).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),W
|
|
549
|
-
`,Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??cU(jZ(),"hooks.jsonl");jZ(Z),vU(Z,W,"utf8")};return{beforeRun:async(H)=>{let W=gH(H,"");J({...Wf(W,$),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(H)=>{let W=BZ(H);J({...Wf(W,$),hookName:"tool_call",iteration:W.iteration,tool_call:{id:W.call.id,name:W.call.name,input:W.call.input},preToolUse:{toolName:W.call.name,parameters:d8(W.call.input)}});return},afterTool:async(H)=>{let W=AZ(H);J({...Wf(W,$),hookName:"tool_result",iteration:W.iteration,tool_result:W.record,postToolUse:{toolName:W.record.name,parameters:d8(W.record.input),result:typeof W.record.output==="string"?W.record.output:JSON.stringify(W.record.output),success:!W.record.error,executionTimeMs:W.record.durationMs}});return},afterRun:async({snapshot:H,result:W})=>{let Q=b0(H);if(W.status==="completed"){J({...Wf(Q,$),hookName:"agent_end",iteration:W.iterations,turn:{outputText:W.outputText,status:W.status},taskComplete:{taskMetadata:{}}});return}if(W.status==="aborted"||xH(W.error?.message)){J({...Wf(Q,$),hookName:"agent_abort",reason:W.error?.message,taskCancel:{taskMetadata:{}}});return}if(W.error)J({...Wf(Q,$),hookName:"agent_error",iteration:W.iterations,error:{name:W.error.name,message:W.error.message,stack:W.error.stack}})},onEvent:async(H)=>{if(H.type!=="message-added"||H.message.role!=="user")return;let W=gH({snapshot:H.snapshot},RZ(H.message.content));J({...Wf(W,$),hookName:"prompt_submit",userPromptSubmit:{prompt:W.userMessage,attachments:[]}})}}}function uH(f){let $=sU(f.workspacePath);if(!Object.values($).some((Y)=>Y.length>0))return;let H=async(Y,B)=>{let A=$[B]??[];if(A.length===0)return;V$({commands:A,cwd:f.cwd,logger:f.logger,payload:B==="agent_resume"?{...Wf(Y,f),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...Wf(Y,f),hookName:B,taskStart:{taskMetadata:{}}}})},W=async(Y)=>{let B=$.prompt_submit??[];if(B.length>0)V$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Wf(Y,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Y.userMessage,attachments:[]}}})},Q=async(Y)=>{let B=$.tool_call??[];if(B.length===0)return;return oU({commands:B,cwd:f.cwd,logger:f.logger,timeoutMs:f.toolCallTimeoutMs??120000,payload:{...Wf(Y,f),hookName:"tool_call",iteration:Y.iteration,tool_call:{id:Y.call.id,name:Y.call.name,input:Y.call.input},preToolUse:{toolName:Y.call.name,parameters:d8(Y.call.input)}}})},Z=async(Y)=>{let B=$.tool_result??[];if(B.length===0)return;V$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Wf(Y,f),hookName:"tool_result",iteration:Y.iteration,tool_result:Y.record,postToolUse:{toolName:Y.record.name,parameters:d8(Y.record.input),result:typeof Y.record.output==="string"?Y.record.output:JSON.stringify(Y.record.output),success:!Y.record.error,executionTimeMs:Y.record.durationMs}}})},j=async(Y)=>{let B=$.agent_end??[];if(B.length===0)return;V$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Wf(Y,f),hookName:"agent_end",iteration:Y.iteration,turn:Y.turn,taskComplete:{taskMetadata:{}}}})},P=async(Y)=>{let B=$.agent_error??[];if(B.length===0)return;V$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Wf(Y,f),hookName:"agent_error",iteration:Y.iteration,error:{name:Y.error.name,message:Y.error.message,stack:Y.error.stack}}})},X=async(Y)=>{if(xH(Y.reason)){let A=$.agent_abort??[];if(A.length>0)V$({commands:A,cwd:f.cwd,logger:f.logger,payload:{...Wf(Y,f),hookName:"agent_abort",reason:Y.reason,taskCancel:{taskMetadata:{}}}})}let B=$.session_shutdown??[];if(B.length===0)return;V$({commands:B,cwd:f.cwd,logger:f.logger,payload:{...Wf(Y,f),hookName:"session_shutdown",reason:Y.reason}})},V={};if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0||($.prompt_submit?.length??0)>0){if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0)V.beforeRun=async(Y)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await H(b0(Y.snapshot),B);return};if(($.prompt_submit?.length??0)>0)V.onEvent=async(Y)=>{if(Y.type!=="message-added"||Y.message.role!=="user")return;await W(gH({snapshot:Y.snapshot},RZ(Y.message.content)))}}if(($.tool_call?.length??0)>0)V.beforeTool=async(Y)=>{let B=await Q(BZ(Y));return eU(B)};if(($.tool_result?.length??0)>0)V.afterTool=async(Y)=>{await Z(AZ(Y));return};if(($.agent_end?.length??0)>0)V.afterRun=async({snapshot:Y,result:B})=>{if(B.status!=="completed")return;await j({...b0(Y),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if(($.agent_error?.length??0)>0||($.agent_abort?.length??0)>0||($.session_shutdown?.length??0)>0){let Y=V.afterRun;V.afterRun=async(B)=>{await Y?.(B);let{snapshot:A,result:R}=B;if(R.status==="aborted"||xH(R.error?.message)){await X({...b0(A),reason:R.error?.message});return}if(R.error)await P({...b0(A),iteration:R.iterations,error:R.error})}}return V}function l8(f){return v8("core.hook_config_files",uH(f))}function Y$(f,$){let J=f.map((H)=>H[$]).filter((H)=>typeof H==="function");if(J.length===0)return;return async(H)=>{let W;for(let Q of J){let Z=await Q(H);if(!Z||typeof Z!=="object")continue;let j=Z;W={...W??{},...j,stop:W?.stop===!0||j.stop===!0?!0:j.stop,options:W?.options||j.options?{...W?.options??{},...j.options??{}}:void 0}}return W}}function n1(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return;return{beforeRun:Y$($,"beforeRun"),afterRun:Y$($,"afterRun"),beforeModel:Y$($,"beforeModel"),afterModel:Y$($,"afterModel"),beforeTool:Y$($,"beforeTool"),afterTool:Y$($,"afterTool"),onEvent:Y$($,"onEvent")}}import{z as w0}from"zod";var p8=_$;var FZ=w0.object({settings:_$,updatedAt:w0.string().datetime(),tokenSource:w0.enum(["manual","oauth","migration"]).default("manual")}),i8=w0.object({version:w0.literal(1),lastUsedProvider:w0.string().min(1).optional(),providers:w0.record(w0.string(),FZ)});function l$(){return{version:1,providers:{}}}ef();import{upsertWorkspaceInfo as fG,WorkspaceManifestSchema as cH}from"@cline/shared";class n8{manifest;listeners=new Set;constructor(f){this.manifest=cH.parse(f??{workspaces:{}})}async addWorkspacePath(f){let $=await G8(f);return this.manifest=fG(this.manifest,$),this.emit({type:"workspace_added",workspace:$}),$}async switchWorkspace(f){let $=s0(f),J=this.manifest.workspaces[$];if(J)return this.manifest=cH.parse({...this.manifest,currentWorkspacePath:$}),this.emit({type:"workspace_switched",workspace:J}),J;let H=await this.addWorkspacePath($);return this.manifest=cH.parse({...this.manifest,currentWorkspacePath:H.rootPath}),this.emit({type:"workspace_switched",workspace:H}),H}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}getCurrentWorkspace(){let f=this.manifest.currentWorkspacePath;if(!f)return;return this.manifest.workspaces[f]}getWorkspace(f){let $=s0(f);return this.manifest.workspaces[$]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(f){for(let $ of this.listeners)$(f)}}Af();import{createHash as $G}from"node:crypto";var yZ=new Set,KZ=new Set;function JG(f){return $G("sha256").update(f).digest("hex")}function HG(f){if(f.vcsTypes&&f.vcsTypes.length>0)return f.vcsTypes;return[f.vcsType==="git"?"git":"none"]}function UZ(f){if(!f.telemetry)return;let $=JG(f.rootPath),J=f.rootCount??1;if(!yZ.has($))yZ.add($),b4(f.telemetry,{root_count:J,vcs_types:HG(f),init_duration_ms:f.durationMs,feature_flag_enabled:f.featureFlagEnabled??!0,is_remote_workspace:f.isRemoteWorkspace});if(f.initError&&!KZ.has($)){KZ.add($);let H=Error(f.initError.message);H.name=f.initError.errorType||"Error",w4(f.telemetry,H,{fallback_to_single_root:!0,workspace_count:J})}}function QG(f){return`${f.pluginName??f.pluginPath}: ${f.message}`}function ZG(f,$,J){if($.length>0)for(let Q of $)J?.log(Q.message,{severity:"warn"});if(f.length===0)return;let H=f.slice(0,3).map(QG).join("; "),W=f.length>3?`; and ${f.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${H}${W}. Use --verbose for more details.`,{severity:"warn"});for(let Q of f)J?.log(`Plugin initialization failed (${Q.phase}) for ${Q.pluginPath}`,{severity:"warn",stack:Q.stack,pluginPath:Q.pluginPath,pluginName:Q.pluginName})}function jG(f,$){let J=typeof f.thinking==="boolean",H=typeof f.reasoningEffort==="string";if(!J&&!H)return $;return{...$??{},...J?{enabled:f.thinking}:{},...H?{effort:f.reasoningEffort}:{}}}function PG(f,$){return WG(f,$)}function XG(f){let $=0;for(let J of f??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;$+=1}return $}function VG(f){let $={...f.storedHeaders??{},...f.configHeaders??{}},J=f.accountId?.trim()||YG(f.accessToken);if($.originator="cline",$.session_id=f.sessionId,$["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)$["ChatGPT-Account-Id"]=J;return $}function YG(f){let $=f?.trim();if(!$)return;let J=jf($),H=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof H==="string"&&H.length>0)return H;let W=J?.organizations?.[0]?.id;if(typeof W==="string"&&W.length>0)return W;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}function BG(f,$,J,H,W){let Q=J.getProviderSettings(f.providerId),Z=H||Q?.modelCatalog?{...H??{},...Q?.modelCatalog??{}}:void 0,j={...Q??{},provider:f.providerId,model:f.modelId,apiKey:f.apiKey??Q?.apiKey,baseUrl:f.baseUrl??Q?.baseUrl,headers:f.providerId==="openai-codex"?VG({sessionId:$,configHeaders:f.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:f.apiKey??Q?.auth?.accessToken??Q?.apiKey}):f.headers??Q?.headers,reasoning:jG(f,Q?.reasoning),modelCatalog:Z},P=tf(j);if(f.knownModels)P.knownModels=f.knownModels;if(f.extensionContext)P.extensionContext=f.extensionContext;let V=f.fetch??P.fetch??W;if(V)P.fetch=V;return P}async function GZ(f){let{input:$,sessionId:J,providerSettingsManager:H,defaultTelemetry:W,defaultCapabilities:Q,defaultToolPolicies:Z,defaultFetch:j,onPluginEvent:P,onTeamEvent:X,createSpawnTool:V,localRuntime:Y,readSessionMetadata:B,writeSessionMetadata:A}=f,R=q0($.config),{modelCatalogDefaults:U,userInstructionService:y,configExtensions:F,onTeamRestored:K,...M}=Y??{},T=Object.keys(M).length>0?M:void 0,{workspaceInfo:G,workspaceMetadata:h,durationMs:L,vcsType:x,initError:Cf}=await R7(R),p=T?.extensionContext,g={...p??{},workspace:{...G,...p?.workspace??{}},session:{...p?.session??{},sessionId:J},logger:p?.logger??T?.logger,telemetry:p?.telemetry??T?.telemetry??W};UZ({telemetry:g.telemetry,rootPath:G.rootPath,workspaceInfo:G,rootCount:1,vcsType:x,durationMs:L,initError:Cf,featureFlagEnabled:!0});let v=l8({cwd:$.config.cwd,workspacePath:R,rootSessionId:J,logger:T?.logger,workspaceInfo:G}),i=w7(T?.hooks)?void 0:r8({rootSessionId:J,workspacePath:R,workspaceInfo:G}),If=n1([T?.hooks,i]),q;if(PG(F,"plugins"))try{q=await F8({pluginPaths:T?.pluginPaths,workspacePath:R,cwd:$.config.cwd,onEvent:P,providerId:$.config.providerId,modelId:$.config.modelId,workspaceInfo:G,session:g.session,client:g.client,user:g.user,logger:g.logger,telemetry:g.telemetry,automation:g.automation}),ZG(q.failures,q.warnings,T?.logger)}catch(f1){let u=f1 instanceof Error?f1.message:String(f1);T?.logger?.log?.(`plugin loading failed; continuing without plugins (${u})`)}let Ef=cJ(v?[v]:void 0,cJ(T?.extensions,HJ(q?.extensions))),s={...$.config,...T??{},sessionId:J,hooks:If,extensions:Ef,extensionContext:g,telemetry:g.telemetry},o$=BG(s,J,H,U,j),k0=n1([s.hooks,s.checkpoint?.enabled===!0?MQ({cwd:s.cwd,sessionId:J,logger:s.logger,createCheckpoint:s.checkpoint?.createCheckpoint,initialRunCount:XG($.initialMessages),readSessionMetadata:B,writeSessionMetadata:A}):void 0]),m0={...s,providerConfig:o$,workspaceMetadata:h,hooks:k0},K$=$.toolPolicies??s.toolPolicies??Z,e$=Vf(Q,$.capabilities),j2=e$?.requestToolApproval,L4=e$?.toolExecutors,U$=new n8({currentWorkspacePath:G.rootPath,workspaces:{[G.rootPath]:G}});return{effectiveInput:$,config:m0,providerConfig:o$,workspaceMetadata:h,workspaceInfo:G,extensions:Ef,hooks:k0,toolPolicies:K$,requestToolApproval:j2,pluginSandboxShutdown:q?.shutdown,runtimeBuilderInput:{config:m0,hooks:k0,extensions:Ef,onTeamEvent:X,createSpawnTool:V,onTeamRestored:K,userInstructionService:y,configExtensions:F,toolExecutors:L4,workspaceManager:U$,logger:m0.logger,telemetry:m0.telemetry}}}import{resolveDocumentsExtensionPath as AG}from"@cline/shared/storage";Af();function hZ(f,$,J,H,W){if(J)E4(f.telemetry,{ulid:$,apiProvider:f.providerId,...W});else C4(f.telemetry,{ulid:$,apiProvider:f.providerId,...W});RG(f.telemetry,{workspacePath:H})}function RG(f,$){let J=AG("Hooks"),H=r$($.workspacePath),W=new Map;for(let Q of H){let Z=Q.hookEventName??"unknown",j=W.get(Z)??{global:0,workspace:0};if(Q.path===J||Q.path.startsWith(`${J}/`))j.global+=1;else j.workspace+=1;W.set(Z,j)}for(let[Q,Z]of W.entries())d4(f,Q,Z.global,Z.workspace)}function TZ(f,$){for(let J of $.mentions)u4(f,J,$.matchedFiles.includes(J)?1:0,"file",!$.matchedFiles.includes(J));for(let J of $.matchedFiles)g4(f,"file",J.length);for(let J of $.ignoredMentions)v4(f,"file","not_found",J)}import{chmodSync as IZ,existsSync as nH,mkdirSync as sG,readFileSync as oG,writeFileSync as eG}from"node:fs";import{basename as xZ,dirname as aH}from"node:path";import{resolveProviderSettingsPath as fh}from"@cline/shared/storage";import{existsSync as FG,mkdirSync as yG,readFileSync as KG,writeFileSync as UG}from"node:fs";import{mkdir as GG,readFile as hG,writeFile as TG}from"node:fs/promises";import{dirname as dH,join as DG}from"node:path";import*as Kf from"@cline/llms";import{ModelCapabilitySchema as MG,ProviderCapabilitySchema as _G,ProviderClientSchema as LG,ProviderProtocolSchema as zG}from"@cline/shared";import{z as d}from"zod";var OG=d.object({id:d.string().optional(),name:d.string().optional(),capabilities:d.array(MG).optional(),supportsVision:d.boolean().optional(),supportsAttachments:d.boolean().optional(),supportsReasoning:d.boolean().optional()}).passthrough(),NG=d.object({name:d.string(),baseUrl:d.string(),defaultModelId:d.string().optional(),protocol:zG.optional(),client:LG.optional(),capabilities:d.array(_G).optional(),modelsSourceUrl:d.string().optional()}).passthrough(),DZ=d.object({provider:NG.optional(),models:d.record(d.string(),OG).optional()}).passthrough(),MZ=d.object({version:d.literal(1),providers:d.record(d.string(),DZ)}),qG=d.object({version:d.literal(1),providers:d.record(d.string(),d.unknown())}),a8=new Set;function _Z(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function B$(f){return DG(dH(f.getFilePath()),"models.json")}function t8(){return{version:1,providers:{}}}function LZ(f){let $=qG.safeParse(f);if(!$.success)return t8();let J={};for(let[H,W]of Object.entries($.data.providers)){let Q=DZ.safeParse(W);if(Q.success)J[H]=Q.data}return{version:1,providers:J}}function rH(f){if(!FG(f))return t8();try{let $=KG(f,"utf8");return LZ(JSON.parse($))}catch{}return t8()}async function p$(f){try{let $=await hG(f,"utf8");return LZ(JSON.parse($))}catch{}return t8()}function zZ(f,$){yG(dH(f),{recursive:!0});let J=MZ.parse($);UG(f,`${JSON.stringify(J,null,2)}
|
|
550
|
-
`,"utf8")}async function
|
|
551
|
-
`,"utf8")}function OZ(f,$){return{id:f,name:$.name??f,supportsAttachments:$.capabilities?.includes("files"),supportsVision:$.capabilities?.includes("images"),supportsReasoning:$.capabilities?.includes("reasoning")||$.thinkingConfig!=null}}function NZ(f){if(!f||f.length===0)return;let $=new Set;if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("tools"))$.add("tools");return $.size>0?[...$]:void 0}function qZ(f){let $=new Set;if(!f||f.length===0)return[...$];if(f.includes("streaming"))$.add("streaming");if(f.includes("tools"))$.add("tools");if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("vision"))$.add("images"),$.add("files");return[...$]}function bG(f){return f!=null&&typeof f.name==="string"&&typeof f.baseUrl==="string"}function bZ(f,$){return f??$??"openai-chat"}function wZ(f,$,J){return f??J??($==="openai-responses"?"openai":"openai-compatible")}function wG(f,$){let J=new Set($?.capabilities??[]);if($?.supportsVision)J.add("images");if($?.supportsAttachments)J.add("files");if($?.supportsReasoning)J.add("reasoning");return{id:f,name:$?.name??f,capabilities:J.size>0?[...J]:void 0}}function CG(f,$){for(let[J,H]of Object.entries($??{})){let W=H.id?.trim()||J.trim();if(!W)continue;Kf.registerModel(f,W,wG(W,H))}}function EG(f,$,J){return{...$??{},id:f,name:$?.name??f,capabilities:$?.capabilities??J}}function SG(f){return Object.assign({},...Kf.resolveProviderModelCatalogKeys(f).map((J)=>Kf.getGeneratedModelsForProvider(J)))}function kG(f){let $=f.provider.trim();if(!$||Kf.isBuiltInProviderId($))return;let J=f.baseUrl?.trim();if(!J)return;let H=Kf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=SG($),Q=qZ(f.capabilities),Z=Q.length>0?Q:void 0,j=f.model?.trim(),P={...W,...H?.models??{}};if(j)P[j]=EG(j,P[j],Z);let X=Object.keys(P).filter(Boolean),V=j||X[0];if(!V)return;let Y=bZ(f.protocol,H?.provider.protocol),B=wZ(f.client,Y,H?.provider.client);Kf.registerProvider({provider:{id:$,name:H?.provider.name??_Z($),description:H?.provider.description,protocol:Y,client:B,baseUrl:J,modelsSourceUrl:H?.provider.modelsSourceUrl,defaultModelId:V,capabilities:NZ(f.capabilities)??H?.provider.capabilities,source:"file"},models:P})}function o8(f){for(let $ of Object.values(f.providers))kG($.settings)}function a1(f,$){let J=$.models??{};if(!bG($.provider)){CG(f,J);return}let H=qZ($.provider.capabilities),W=Object.entries(J).map(([X,V])=>({id:V.id?.trim()||X.trim(),model:V})).filter(({id:X})=>X.length>0),Q=$.provider.defaultModelId?.trim()||W[0]?.id||"default",Z=bZ($.provider.protocol,void 0),j=wZ($.provider.client,Z,void 0),P=Object.fromEntries(W.map(({id:X,model:V})=>[X,{id:X,name:V.name??X,capabilities:H.length>0?H:void 0,status:"active"}]));Kf.registerProvider({provider:{id:f,name:$.provider.name.trim()||_Z(f),protocol:Z,client:j,baseUrl:$.provider.baseUrl,modelsSourceUrl:$.provider.modelsSourceUrl,defaultModelId:Q,capabilities:NZ($.provider.capabilities),source:"file"},models:P})}function CZ(f){let $=B$(f);if(a8.has($))return;let J=rH($);for(let[H,W]of Object.entries(J.providers))a1(H,W);a8.add($)}async function EZ(f){let $=B$(f);if(a8.has($))return;let J=await p$($);for(let[H,W]of Object.entries(J.providers))a1(H,W);a8.add($)}import{existsSync as mG,readFileSync as IG}from"node:fs";import{dirname as xG,join as lH}from"node:path";import*as kZ from"@cline/llms";import{resolveClineDataDir as gG}from"@cline/shared/storage";var mZ="openai";function vG(f){let $=f?.trim();if(!$)return;try{let J=JSON.parse($);if(!J)return;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:J.expiresAt,accountId:J.userInfo?.id}}catch{return}}function b(f){let $=f?.trim();return $?$:void 0}function SZ(f){if(!mG(f))return;try{let $=IG(f,"utf8"),J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function uG(f){let $=f.dataDir??gG(),J=f.globalStatePath??lH($,"globalState.json"),H=f.secretsPath??lH($,"secrets.json"),W=SZ(J),Q=SZ(H);if(!W&&!Q)return;return{globalState:W??{},secrets:Q??{}}}function cG(f){try{let J=new URL(f).hostname.toLowerCase();return J==="api.openai.com"||J.endsWith(".openai.azure.com")||J.endsWith(".services.ai.azure.com")}catch{return!1}}function dG(f){let $=b(f.openAiBaseUrl);if(!$)return!1;if(f.azureApiVersion||f.azureIdentity)return!1;return!cG($)}function pH(f,$){if(f==="openai"&&dG($))return mZ;return f}function rG(f,$,J,H){let W=J==="plan"?"planMode":"actMode",Q=$===H?b(J==="plan"?f.planModeApiModelId:f.actModeApiModelId):void 0,j={openrouter:`${W}OpenRouterModelId`,cline:`${W}ClineModelId`,openai:`${W}OpenAiModelId`,ollama:`${W}OllamaModelId`,lmstudio:`${W}LmStudioModelId`,litellm:`${W}LiteLlmModelId`,requesty:`${W}RequestyModelId`,together:`${W}TogetherModelId`,fireworks:`${W}FireworksModelId`,sapaicore:`${W}SapAiCoreModelId`,groq:`${W}GroqModelId`,baseten:`${W}BasetenModelId`,huggingface:`${W}HuggingFaceModelId`,"huawei-cloud-maas":`${W}HuaweiCloudMaasModelId`,oca:`${W}OcaModelId`,aihubmix:`${W}AihubmixModelId`,hicap:`${W}HicapModelId`,nousResearch:`${W}NousResearchModelId`,"vercel-ai-gateway":`${W}VercelAiGatewayModelId`}[$];return(j?b(typeof f[j]==="string"?f[j]:void 0):void 0)??Q}function lG(f,$,J){let H=J==="plan"?f.planModeReasoningEffort:f.actModeReasoningEffort,W=J==="plan"?f.geminiPlanModeThinkingLevel:f.geminiActModeThinkingLevel,Q=J==="plan"?f.planModeThinkingBudgetTokens:f.actModeThinkingBudgetTokens,Z=($==="gemini"?W:void 0)??H,j=Z==="none"||Z==="low"||Z==="medium"||Z==="high"?Z:void 0,P=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!j&&P===void 0)return;return{...j?{effort:j}:{},...P!==void 0?{budgetTokens:P}:{}}}function pG(f){let $=f["openai-codex-oauth-credentials"];if(!$)return;try{let J=JSON.parse($),H=b(J.access_token),W=b(J.refresh_token),Q=b(J.accountId);if(!H&&!W&&!Q)return;return{...H?{apiKey:H}:{},auth:{...H?{accessToken:H}:{},...W?{refreshToken:W}:{},...Q?{accountId:Q}:{}}}}catch{return}}function iG(f){let $=kZ.getGeneratedModelsForProvider(f);return Object.keys($)[0]??void 0}function nG(f,$,J,H){let W=pH(f,$),Q=b(H==="plan"?$.planModeApiProvider:$.actModeApiProvider),Z=rG($,f,H,Q)??iG(W),j=lG($,W,H),P=typeof $.requestTimeoutMs==="number"&&Number.isInteger($.requestTimeoutMs)&&$.requestTimeoutMs>0?$.requestTimeoutMs:void 0,X={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey,sapaicore:J.sapAiCoreClientId},V={};if(f==="openai-codex")Object.assign(V,pG(J));if(f==="cline")try{let F=b(J["cline:clineAccountId"]);if(F)V.auth={...V.auth??{},...vG(F)}}catch{}if(f==="openai"&&$.openAiHeaders)V.headers=$.openAiHeaders;if(f==="bedrock")V.aws={accessKey:b(J.awsAccessKey),secretKey:b(J.awsSecretKey),sessionToken:b(J.awsSessionToken),region:b($.awsRegion),authentication:$.awsAuthentication,profile:$.awsUseProfile?b($.awsProfile):void 0,usePromptCache:$.awsBedrockUsePromptCache,useCrossRegionInference:$.awsUseCrossRegionInference,useGlobalInference:$.awsUseGlobalInference,endpoint:b($.awsBedrockEndpoint),customModelBaseId:b(H==="plan"?$.planModeAwsBedrockCustomModelBaseId:$.actModeAwsBedrockCustomModelBaseId)};if(f==="vertex")V.gcp={projectId:b($.vertexProjectId),region:b($.vertexRegion)};if(f==="openai"&&($.azureApiVersion||$.azureIdentity!==void 0))V.azure={apiVersion:b($.azureApiVersion),useIdentity:$.azureIdentity};if(f==="sapaicore")V.sap={clientId:b(J.sapAiCoreClientId),clientSecret:b(J.sapAiCoreClientSecret),tokenUrl:b($.sapAiCoreTokenUrl),resourceGroup:b($.sapAiResourceGroup),deploymentId:b(H==="plan"?$.planModeSapAiCoreDeploymentId:$.actModeSapAiCoreDeploymentId),useOrchestrationMode:$.sapAiCoreUseOrchestrationMode};if(f==="oca"){V.oca={mode:$.ocaMode};let F=b(J.ocaRefreshToken);if(F)V.auth={...V.auth??{},refreshToken:F}}if(f==="qwen")V.apiLine=$.qwenApiLine;if(f==="moonshot")V.apiLine=$.moonshotApiLine;if(f==="zai")V.apiLine=$.zaiApiLine;if(f==="minimax")V.apiLine=$.minimaxApiLine;let Y={anthropic:$.anthropicBaseUrl,openai:$.openAiBaseUrl,ollama:$.ollamaBaseUrl,lmstudio:$.lmStudioBaseUrl,litellm:$.liteLlmBaseUrl,gemini:$.geminiBaseUrl,requesty:$.requestyBaseUrl,asksage:$.asksageApiUrl,dify:$.difyBaseUrl,oca:$.ocaBaseUrl,aihubmix:$.aihubmixBaseUrl,sapaicore:$.sapAiCoreBaseUrl},B=b(X[f]),A=b(Y[f]),R={provider:W,...B?{apiKey:B}:{},...Z?{model:Z}:{},...A?{baseUrl:A}:{},...j?{reasoning:j}:{},...P?{timeout:P}:{},...V},U=p8.safeParse(R);if(!U.success)return;return Object.keys(R).filter((F)=>F!=="provider").length>0?U.data:void 0}function aG(f,$){if(f!==mZ)return;if(!$.baseUrl||!$.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:$.baseUrl,defaultModelId:$.model},models:{[$.model]:{id:$.model,name:$.model}}}}function tG(f,$){let J=new Set;for(let H of[f.actModeApiProvider,f.planModeApiProvider]){let W=b(H);if(W)J.add(W)}if(b($.apiKey))J.add("anthropic");if(b($.openRouterApiKey))J.add("openrouter");if(b($.openAiApiKey))J.add("openai");if(b($.openAiNativeApiKey))J.add("openai-native");if(b($["openai-codex-oauth-credentials"]))J.add("openai-codex");if(b($.geminiApiKey))J.add("gemini");if(b($.ollamaApiKey))J.add("ollama");if(b($.awsAccessKey)||b($.awsBedrockApiKey))J.add("bedrock");if(b(f.vertexProjectId)||b(f.vertexRegion))J.add("vertex");if(b($.clineApiKey))J.add("cline");if(b($.ocaApiKey))J.add("oca");return J}function iH(f){let $=f.providerSettingsManager.read(),J=uG(f);if(!J)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let{globalState:H,secrets:W}=J,Q=H.mode==="plan"?"plan":"act",Z=tG(H,W),j=l$();j.providers={...$.providers},j.lastUsedProvider=$.lastUsedProvider;let P=new Date().toISOString(),X=0,V=lH(xG(f.providerSettingsManager.getFilePath()),"models.json"),Y=rH(V),B=0;for(let U of Z){let y=pH(U,H);if(j.providers[y])continue;let F=nG(U,H,W,Q);if(!F)continue;j.providers[y]={settings:F,updatedAt:P,tokenSource:"migration"},X+=1;let K=aG(y,F);if(K&&!Y.providers[y])Y.providers[y]=K,B+=1}if(X===0&&B===0)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let A=b(Q==="plan"?H.planModeApiProvider:H.actModeApiProvider),R=A?pH(A,H):void 0;if(j.lastUsedProvider=$.lastUsedProvider??(R&&j.providers[R]?R:Object.keys(j.providers)[0]),f.providerSettingsManager.write(j),B>0)zZ(V,Y);return{migrated:X>0||B>0,providerCount:Object.keys(j.providers).length,lastUsedProvider:j.lastUsedProvider}}function $h(){return new Date().toISOString()}function Jh(f){if(xZ(f)!=="providers.json")return;let $=aH(f);if(xZ($)!=="settings")return;return aH($)}class C0{filePath;dataDir;constructor(f={}){if(this.filePath=f.filePath??fh(),this.dataDir=f.dataDir??Jh(this.filePath),this.dataDir||!f.filePath)iH({providerSettingsManager:this,dataDir:this.dataDir});if(CZ(this),o8(this.read()),nH(this.filePath))try{IZ(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!nH(this.filePath))return l$();try{let f=oG(this.filePath,"utf8"),$=JSON.parse(f),J=i8.safeParse($);if(J.success)return o8(J.data),J.data}catch{}return l$()}write(f){let $=i8.parse(f),J=aH(this.filePath);if(!nH(J))sG(J,{recursive:!0,mode:448});eG(this.filePath,`${JSON.stringify($,null,2)}
|
|
552
|
-
`,"utf8");try{
|
|
546
|
+
${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fileOps,tokensBefore:f.tokensBefore,generatedAt:Date.now()}}}async function iU(f){let $=pU(f.providerConfig),J="";for await(let W of $.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:f.request}])){if(W.type==="text"){J+=W.text;continue}if(W.type==="done"&&!W.success&&W.error)throw Error(W.error)}return f.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:f.providerConfig.modelId,providerId:f.providerConfig.providerId}),J.trim()}async function XZ(f){let $=f.context.messages;if($.length<2)return;let J=JZ($,f.preserveRecentTokens,f.estimateMessageTokens);if(J<=0||J>=$.length)return;let W=$.slice(0,J),H=$Z(W),Q=H>=0?v5(W[H])?.summary:void 0,Z=H>=0?W.slice(H+1):W;if(Z.length===0)return;let j=WZ(W),X=t7(Z),A=await iU({providerConfig:ZZ({activeProviderConfig:f.providerConfig,summarizer:f.summarizer}),request:QZ({previousSummary:Q,conversationText:X,fileOps:j}),logger:f.logger});if(!A.trim())return;let P=HZ(A,j),B=$.reduce((R,U)=>R+f.estimateMessageTokens(U),0),Y=[jZ({summary:P,fileOps:j,tokensBefore:B}),...$.slice(J)],V=Y.reduce((R,U)=>R+f.estimateMessageTokens(U),0);return f.logger?.debug("Performed agentic compaction",{messagesBefore:$.length,messagesAfter:Y.length,messagesSummarized:J,messagesPreserved:$.length-J,tokensBefore:B,tokensAfter:V,contextWindowTokens:f.context.contextWindowTokens}),{messages:Y}}function BZ(f){if(e1(f))return;if(typeof f.content==="string"){let J=f.content.trim();return J?{...f,content:J}:void 0}let $=f.content.filter((J)=>J.type!=="text"||J.text.trim());if($.length===0)return;return{...f,content:$.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J)}}function f2(f,$){return f.reduce((J,W)=>J+$(W),0)}function AZ(f,$){let J=Math.max(1,$),W=Math.max(16,J*4);if(typeof f.content==="string"){let Z=V$(f.content,W).trim();return{...f,content:Z||"..."}}let H=W,Q=f.content.map((Z)=>{if(Z.type!=="text"||H<=0)return Z;let j=V$(Z.text,H).trim();return H-=j.length,{...Z,text:j||"..."}});return{...f,content:Q}}function nU(f,$){let J=e7(f),W=u5(f),H=fZ(f),Q=[];for(let Z=0;Z<f.length;Z+=1){let j=BZ(f[Z]);if(!j)continue;Q.push({index:Z,message:j,estimatedTokens:$(j),isFirstUser:Z===J,isLastUser:Z===W,isLastAssistant:Z===H})}return Q}function PZ(f,$,J,W){let H=f[$];H.message=J,H.estimatedTokens=W(J)}function c8(f,$,J,W){let H=f2(f.map((Q)=>Q.message),W);for(let Q=0;Q<f.length&&H>J;){if(!$(f[Q])){Q+=1;continue}H-=f[Q].estimatedTokens,f.splice(Q,1)}}function aU(f,$,J){let W=f2(f.map((Q)=>Q.message),J);if(W<=$)return;for(let Q=f.length-1;Q>=0&&W>$;Q-=1){let Z=f[Q];if(Z.isFirstUser)continue;let j=Math.max(n7,Z.estimatedTokens-(W-$));if(j>=Z.estimatedTokens)continue;PZ(f,Q,AZ(Z.message,j),J),W=f2(f.map((X)=>X.message),J)}if(W<=$)return;let H=f.findIndex((Q)=>Q.isFirstUser);if(H>=0){let Q=Math.max(1,f[H].estimatedTokens-(W-$));PZ(f,H,AZ(f[H].message,Q),J)}}function tU(f,$){return JSON.stringify(f)!==JSON.stringify($)}function YZ(f){let $=Math.max(1,Math.min(f.context.triggerTokens,f.context.contextWindowTokens)),J=nU(f.context.messages,f.estimateMessageTokens);if(J.length===0)return;c8(J,(Z)=>Z.message.role==="assistant"&&!Z.isLastAssistant,$,f.estimateMessageTokens),c8(J,(Z)=>Z.message.role==="user"&&!Z.isFirstUser&&!Z.isLastUser,$,f.estimateMessageTokens),c8(J,(Z)=>Z.message.role==="assistant"&&Z.isLastAssistant,$,f.estimateMessageTokens),c8(J,(Z)=>Z.message.role==="user"&&Z.isLastUser&&!Z.isFirstUser,$,f.estimateMessageTokens),aU(J,$,f.estimateMessageTokens);let W=J.map((Z)=>Z.message);if(!tU(f.context.messages,W))return;let H=f2(f.context.messages.map((Z)=>BZ(Z)??Z),f.estimateMessageTokens),Q=f2(W,f.estimateMessageTokens);return f.logger?.debug("Performed basic compaction",{messagesBefore:f.context.messages.length,messagesAfter:W.length,messagesRemoved:f.context.messages.length-W.length,tokensBefore:H,tokensAfter:Q,targetTokens:$,contextWindowTokens:f.context.contextWindowTokens}),{messages:W}}var sU={basic:({context:f,estimateMessageTokens:$,logger:J})=>YZ({context:f,estimateMessageTokens:$,logger:J}),agentic:({context:f,providerConfig:$,compaction:J,mode:W,estimateMessageTokens:H,logger:Q})=>XZ({context:f,providerConfig:$,summarizer:J?.summarizer,preserveRecentTokens:W==="manual"?Math.min(J?.preserveRecentTokens??g5,f.triggerTokens):J?.preserveRecentTokens??g5,estimateMessageTokens:H,logger:Q})};function oU(f){if(typeof f.config.reserveTokens==="number"){let W=Math.max(0,f.config.reserveTokens),H=Math.max(0,f.contextWindowTokens-W);return{shouldCompact:f.inputTokens>H,triggerTokens:H,thresholdRatio:f.contextWindowTokens>0?H/f.contextWindowTokens:0}}let $=f.config.thresholdRatio??i7,J=f.contextWindowTokens*$;return{shouldCompact:f.inputTokens>J,triggerTokens:J,thresholdRatio:$}}function eU(f){let $=typeof f.manualTargetRatio==="number"&&Number.isFinite(f.manualTargetRatio)?f.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,$)),W=Math.max(1,Math.floor(Math.min(f.autoTriggerTokens,f.inputTokens*J)));return{triggerTokens:W,thresholdRatio:f.contextWindowTokens>0?W/f.contextWindowTokens:0}}function c5(f,$={}){let J=f.compaction;if(J?.enabled!==!0)return;let W=f.providerConfig??{providerId:f.providerId,modelId:f.modelId},H=s7(),Q=J?.strategy??"basic",Z=sU[Q],j=$.mode??"auto";return async(X)=>{let A=X.apiMessages.reduce((F,y)=>F+H(y),0),P=J?.contextWindowTokens??X.model.info?.contextWindow??p7;if(typeof P!=="number"||!Number.isFinite(P)||P<=0)return;let B=oU({inputTokens:A,contextWindowTokens:P,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if(j==="auto"&&!B.shouldCompact)return;let Y=j==="manual"?eU({inputTokens:A,contextWindowTokens:P,autoTriggerTokens:B.triggerTokens,manualTargetRatio:$.manualTargetRatio}):B,V={agentId:X.agentId,conversationId:X.conversationId,parentAgentId:X.parentAgentId,iteration:X.iteration,messages:X.messages,model:X.model,contextWindowTokens:P,triggerTokens:Y.triggerTokens,thresholdRatio:Y.thresholdRatio,utilizationRatio:P>0?A/P:0},R=j==="manual"?"manual_compaction":"auto_compaction";X.emitStatusNotice?.(j==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:X.iteration,triggerTokens:Y.triggerTokens,contextWindowTokens:P});let U=X.messages.length,K=J?.compact?await J.compact(V):await Z({context:V,providerConfig:{...W,abortSignal:X.abortSignal},compaction:J,mode:j,estimateMessageTokens:H,logger:f.logger});if(K?.messages){let F=K.messages.reduce((y,D)=>y+H(D),0);f.logger?.log("Context compaction completed",{severity:"info",strategy:Q,contextWindowTokens:P,inputTokens:A,afterTokens:F,tokensSaved:A-F,utilizationBefore:`${(A/P*100).toFixed(1)}%`,utilizationAfter:`${(F/P*100).toFixed(1)}%`,thresholdTrigger:`${(Y.thresholdRatio*100).toFixed(1)}%`,messagesBefore:U,messagesAfter:K.messages.length,messagesRemoved:U-K.messages.length})}return K}}Uf();function Vf(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function Xf(f,$){return{inputTokens:f.inputTokens+Math.max(0,$.inputTokens??0),outputTokens:f.outputTokens+Math.max(0,$.outputTokens??0),cacheReadTokens:f.cacheReadTokens+Math.max(0,$.cacheReadTokens??0),cacheWriteTokens:f.cacheWriteTokens+Math.max(0,$.cacheWriteTokens??0),totalCost:f.totalCost+Math.max(0,$.totalCost??0)}}function d8(f){let $=Vf();for(let J of f)$=Xf($,J);return $}function n$(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function r8(f){let $=Vf();for(let J of f){let W=J.metrics;if(!W)continue;$=Xf($,{inputTokens:n$(W.inputTokens),outputTokens:n$(W.outputTokens),cacheReadTokens:n$(W.cacheReadTokens),cacheWriteTokens:n$(W.cacheWriteTokens),totalCost:n$(W.cost)})}return $}function fG(f){for(let $=f.length-1;$>=0;$-=1){let J=f[$];if(J?.role!=="assistant")continue;let W=n$(J.metrics?.inputTokens);return W>0?W:void 0}return}function $G(f){if(!f||typeof f!=="object")return;let $=f,J=$.skill??$.skill_name??$.skillName;if(typeof J!=="string")return;let W=J.trim();return W.length>0?W:void 0}function d5(f){if(!f||typeof f!=="object")return{};let $=f;return{agentId:typeof $.agentId==="string"?$.agentId:void 0,conversationId:typeof $.conversationId==="string"?$.conversationId:void 0,parentAgentId:typeof $.parentAgentId==="string"?$.parentAgentId:void 0}}function A0(f){let $=f.agentId?.trim();if(!$)return;let J=f.parentAgentId?.trim()||void 0,W=f.teamRole,H="root";if(W==="teammate")H="team_teammate";else if(W==="lead")H="team_lead";else if(J)H="subagent";return{agentId:$,agentKind:H,conversationId:f.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:f.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:f.teamId?.trim()||void 0,teamName:f.teamName?.trim()||void 0,teamRole:W,teamAgentId:f.teamAgentId?.trim()||void 0}}function JG(f){return{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost}}function WG(f){let $=f.isPrimaryAgentEvent?[f.overrides?.agentId,f.eventMetadata.agentId,f.overrides?.teamAgentId]:[f.overrides?.teamAgentId,f.overrides?.agentId,f.eventMetadata.agentId,f.eventMetadata.conversationId];for(let J of $){let W=J?.trim();if(W)return W}return f.isPrimaryAgentEvent?"root":"unknown"}function r5(f,$,J){let{sessionId:W,config:H,liveSession:Q,emit:Z}=f,j=H.telemetry,X=Q?.runtime.teamRuntime,A=J?.isPrimaryAgentEvent??!0,P=d5($),B=A0({agentId:J?.agentId??P.agentId,conversationId:J?.conversationId??P.conversationId,parentAgentId:J?.parentAgentId??P.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??X?.getTeamId(),teamName:J?.teamName??X?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if($.type==="content_start"&&$.contentType==="tool"&&$.toolName==="skills"){let Y=$G($.input);if(Y)c4(j,{ulid:W,skillName:Y,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:H.providerId,modelId:H.modelId,...B})}if($.type==="content_end"&&$.contentType==="tool"){let Y=$.toolName??"unknown",V=!$.error;if(u4(j,{ulid:W,tool:Y,autoApproved:void 0,success:V,modelId:H.modelId,provider:H.providerId,...B}),!V&&(Y==="editor"||Y==="apply_patch"))d4(j,{ulid:W,modelId:H.modelId,provider:H.providerId,errorType:$.error,...B})}if($.type==="notice"&&$.reason==="api_error")y2(j,{ulid:W,model:H.modelId,provider:H.providerId,errorMessage:$.message,...B});if($.type==="error")y2(j,{ulid:W,model:H.modelId,provider:H.providerId,errorMessage:$.error?.message??"unknown error",...B});if($.type==="usage"&&Q?.turnUsageBaseline){let Y=JG($);if(A){Q.turnPrimaryUsage=Xf(Q.turnPrimaryUsage??Vf(),Y);let R=Xf(Q.turnUsageBaseline,Q.turnPrimaryUsage);f.usageBySession.set(W,R),Q1(j,{ulid:W,provider:H.providerId,model:H.modelId,source:"assistant",mode:H.mode,...B}),g4(j,{ulid:W,tokensIn:$.inputTokens,tokensOut:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost,model:H.modelId,...B})}else{let R=WG({isPrimaryAgentEvent:A,overrides:J,eventMetadata:P}),U=Q.turnUsageByAgent??new Map;Q.turnUsageByAgent=U,U.set(R,Xf(U.get(R)??Vf(),Y))}let V=Xf(Q.turnPrimaryUsage??Vf(),d8(Q.turnUsageByAgent?.values()??[]));f.aggregateUsageBySession.set(W,Xf(Q.turnAggregateUsageBaseline??Q.turnUsageBaseline,V))}if($.type==="iteration_end"&&A)f.persistMessages(W,Q?.agent.getMessages()??[],Q?.config.systemPrompt);Z({type:"agent_event",payload:{sessionId:W,event:$,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(A?"lead":void 0):void 0}}),Z({type:"chunk",payload:{sessionId:W,stream:"agent",chunk:gQ($),ts:Date.now()}})}function k0(f){return f.workspaceRoot??f.cwd}import{hasRuntimeConfigExtension as bG}from"@cline/shared";import{spawn as YG}from"node:child_process";import{appendFileSync as VG,readFileSync as RG}from"node:fs";import{join as FG}from"node:path";import{augmentNodeCommandForDebug as KZ,withResolvedClineBuildEnv as t5}from"@cline/shared";import{ensureHookLogDir as RZ}from"@cline/shared/storage";function l8(f,$){if(!$)return;return{name:f,manifest:{capabilities:["hooks"]},hooks:$}}import{existsSync as HG,readdirSync as QG}from"node:fs";import{basename as ZG,extname as jG,join as XG}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as VZ,resolveHooksConfigSearchPaths as AG}from"@cline/shared/storage";function l5(f){return AG(f)}var p8;((P)=>{P.TaskStart="TaskStart";P.TaskResume="TaskResume";P.TaskCancel="TaskCancel";P.TaskComplete="TaskComplete";P.TaskError="TaskError";P.PreToolUse="PreToolUse";P.PostToolUse="PostToolUse";P.UserPromptSubmit="UserPromptSubmit";P.PreCompact="PreCompact";P.SessionShutdown="SessionShutdown"})(p8||={});var p5={["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"},PG=new Map(Object.values(p8).map((f)=>[f.toLowerCase(),f])),BG=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function i5(f){let $=jG(f).toLowerCase();if(!BG.has($))return;let J=ZG(f,$).trim().toLowerCase();return PG.get(J)}function a$(f){let $=[],J=new Set,W=l5(f).filter((H)=>HG(H));for(let H of W)try{for(let Q of QG(H,{withFileTypes:!0})){if(!Q.isFile())continue;let Z=i5(Q.name);if(!Z)continue;let j=XG(H,Q.name);if(J.has(j))continue;J.add(j),$.push({fileName:Z,hookEventName:p5[Z],path:j})}}catch{}return $.sort((H,Q)=>H.path.localeCompare(Q.path))}function n8(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,W]of Object.entries(f))$[J]=typeof W==="string"?W:JSON.stringify(W);return $}function i8(f,$,J){let W=J instanceof Error?`: ${J.message}`:"",H=`${$}${W}`;if(f){try{f.log(H,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(H)}function KG(f,$){if(!$)return f;if(!f)return{...$};let J=[f.context,$.context].filter((H)=>typeof H==="string"&&H.length>0).join(`
|
|
547
|
+
`),W=[...f.appendMessages??[],...$.appendMessages??[]];return{cancel:f.cancel===!0||$.cancel===!0?!0:void 0,review:f.review===!0||$.review===!0?!0:void 0,context:J||void 0,overrideInput:$.overrideInput!==void 0?$.overrideInput:f.overrideInput,systemPrompt:$.systemPrompt!==void 0?$.systemPrompt:f.systemPrompt,appendMessages:W.length>0?W:void 0}}function yG(f){if(!f||typeof f!=="object")return;let $=f,J=typeof $.context==="string"?$.context:typeof $.contextModification==="string"?$.contextModification:typeof $.errorMessage==="string"?$.errorMessage:void 0;return{cancel:typeof $.cancel==="boolean"?$.cancel:void 0,review:typeof $.review==="boolean"?$.review:void 0,context:J,overrideInput:Object.hasOwn($,"overrideInput")?$.overrideInput:void 0}}function n5(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function Af(f,$){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",W={rootSessionId:$.rootSessionId||f.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:W,workspaceRoots:$.workspacePath?[$.workspacePath]:[],workspaceInfo:$.workspaceInfo,userId:J,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function UG(f){let $=f.trim();if(!$)return{};let W=$.split(`
|
|
548
|
+
`).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),H=W.length>0?W[W.length-1]:$;try{return{parsedJson:JSON.parse(H)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse hook stdout JSON"}}}async function GG(f,$){let J=f.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((W,H)=>{let Q=!1,Z=()=>{J.off("error",X),J.off("finish",A),f.off("close",P)},j=(B)=>{if(Q)return;if(Q=!0,Z(),B){let Y=B.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){W();return}H(B);return}W()},X=(B)=>j(B),A=()=>j(),P=()=>j();J.on("error",X),J.once("finish",A),f.once("close",P);try{J.end($)}catch(B){j(B)}})}async function yZ(f,$){if($.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await FZ(f,$)}catch(J){let W=_G($.command,process.platform,J);if(!W)throw J;return await FZ(f,{...$,command:W})}}async function FZ(f,$){let J=KZ($.command,{env:$.env,debugRole:"hook"}),W=YG(J[0],J.slice(1),{cwd:$.cwd,env:t5($.env),stdio:$.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:$.detached}),H=new Promise((Y)=>{W.once("spawn",()=>Y())}),Q=new Promise((Y,V)=>{W.once("error",(R)=>V(R))}),Z=JSON.stringify(f);if(await Promise.race([H,Q]),await GG(W,Z),$.detached){W.unref();return}if(!W.stdout||!W.stderr)throw Error("hook command failed to create stdout/stderr");let j="",X="",A=!1,P;W.stdout.on("data",(Y)=>{j+=Y.toString()}),W.stderr.on("data",(Y)=>{X+=Y.toString()});let B=new Promise((Y)=>{if(($.timeoutMs??0)>0)P=setTimeout(()=>{A=!0,W.kill("SIGKILL")},$.timeoutMs);W.once("close",(V)=>{if(P)clearTimeout(P);let{parsedJson:R,parseError:U}=UG(j);Y({exitCode:V,stdout:j,stderr:X,parsedJson:R,parseError:U,timedOut:A})})});return await Promise.race([B,Q])}function TG(f){try{let J=RG(f,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let W=J.slice(2).trim();if(!W)return;let H=W.split(/\s+/).filter(Boolean);return H.length>0?H:void 0}catch{return}}function DG(f){return!!(f&&typeof f==="object"&&("code"in f)&&f.code==="ENOENT")}function _G(f,$=process.platform,J){if($!=="win32"||!DG(J))return;if(f[0]!=="py"||f[1]!=="-3")return;return["python",...f.slice(2)]}function UZ(f){if(f.length===0)return;let[$,...J]=f,W=$.replace(/\\/g,"/").toLowerCase(),H=W.split("/").at(-1)??W;if(H==="env")return UZ(J);if(H==="bash"||H==="sh"||H==="zsh")return[H,...J];if(H==="python3"||H==="python")return process.platform==="win32"?["py","-3",...J]:[H,...J];return f}function MG(f){let $=TG(f);if($&&$.length>0)return[...UZ($)??$,f];let J=f.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",f];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return KZ(["node",f],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",f];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",f]:["python3",f];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",f];return["bash",f]}function LG(f){let $={};for(let J of a$(f)){if(!J.hookEventName)continue;let W=J.hookEventName,H=$[W]??[];H.push(MG(J.path)),$[W]=H}return $}async function hG(f){let $;for(let J of f.commands){let W=J.join(" ");try{let H=await yZ(f.payload,{command:J,cwd:f.cwd,env:t5(process.env),detached:!1,timeoutMs:f.timeoutMs});if(H?.timedOut){i8(f.logger,`hook command timed out: ${W}`);continue}if(H?.parseError){i8(f.logger,`hook command returned invalid JSON control output: ${W} (${H.parseError})`);continue}$=KG($,yG(H?.parsedJson))}catch(H){i8(f.logger,`hook command failed: ${W}`,H)}}return $}function R$(f){for(let $ of f.commands){let J=$.join(" ");yZ(f.payload,{command:$,cwd:f.cwd,env:t5(process.env),detached:!0}).catch((W)=>{i8(f.logger,`hook command failed: ${J}`,W)})}}function I0(f){return{agentId:f.agentId,conversationId:f.conversationId??f.runId??f.agentId,parentAgentId:f.parentAgentId??null}}function a5(f,$){return{...I0(f.snapshot),userMessage:$}}function GZ(f){return{...I0(f.snapshot),iteration:f.snapshot.iteration,call:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input}}}function TZ(f){return{...I0(f.snapshot),iteration:f.snapshot.iteration,record:{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}}function DZ(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function OG(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}function a8(f){let $={cwd:f.workspacePath,workspacePath:f.workspacePath,rootSessionId:f.rootSessionId,workspaceInfo:f.workspaceInfo},J=(W)=>{let H=`${JSON.stringify({ts:new Date().toISOString(),...W})}
|
|
549
|
+
`,Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??FG(RZ(),"hooks.jsonl");RZ(Z),VG(Z,H,"utf8")};return{beforeRun:async(W)=>{let H=a5(W,"");J({...Af(H,$),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(W)=>{let H=GZ(W);J({...Af(H,$),hookName:"tool_call",iteration:H.iteration,tool_call:{id:H.call.id,name:H.call.name,input:H.call.input},preToolUse:{toolName:H.call.name,parameters:n8(H.call.input)}});return},afterTool:async(W)=>{let H=TZ(W);J({...Af(H,$),hookName:"tool_result",iteration:H.iteration,tool_result:H.record,postToolUse:{toolName:H.record.name,parameters:n8(H.record.input),result:typeof H.record.output==="string"?H.record.output:JSON.stringify(H.record.output),success:!H.record.error,executionTimeMs:H.record.durationMs}});return},afterRun:async({snapshot:W,result:H})=>{let Q=I0(W);if(H.status==="completed"){J({...Af(Q,$),hookName:"agent_end",iteration:H.iterations,turn:{outputText:H.outputText,status:H.status},taskComplete:{taskMetadata:{}}});return}if(H.status==="aborted"||n5(H.error?.message)){J({...Af(Q,$),hookName:"agent_abort",reason:H.error?.message,taskCancel:{taskMetadata:{}}});return}if(H.error)J({...Af(Q,$),hookName:"agent_error",iteration:H.iterations,error:{name:H.error.name,message:H.error.message,stack:H.error.stack}})},onEvent:async(W)=>{if(W.type!=="message-added"||W.message.role!=="user")return;let H=a5({snapshot:W.snapshot},DZ(W.message.content));J({...Af(H,$),hookName:"prompt_submit",userPromptSubmit:{prompt:H.userMessage,attachments:[]}})}}}function s5(f){let $=LG(f.workspacePath);if(!Object.values($).some((B)=>B.length>0))return;let W=async(B,Y)=>{let V=$[Y]??[];if(V.length===0)return;R$({commands:V,cwd:f.cwd,logger:f.logger,payload:Y==="agent_resume"?{...Af(B,f),hookName:Y,taskResume:{taskMetadata:{},previousState:{}}}:{...Af(B,f),hookName:Y,taskStart:{taskMetadata:{}}}})},H=async(B)=>{let Y=$.prompt_submit??[];if(Y.length>0)R$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...Af(B,f),hookName:"prompt_submit",userPromptSubmit:{prompt:B.userMessage,attachments:[]}}})},Q=async(B)=>{let Y=$.tool_call??[];if(Y.length===0)return;return hG({commands:Y,cwd:f.cwd,logger:f.logger,timeoutMs:f.toolCallTimeoutMs??120000,payload:{...Af(B,f),hookName:"tool_call",iteration:B.iteration,tool_call:{id:B.call.id,name:B.call.name,input:B.call.input},preToolUse:{toolName:B.call.name,parameters:n8(B.call.input)}}})},Z=async(B)=>{let Y=$.tool_result??[];if(Y.length===0)return;R$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...Af(B,f),hookName:"tool_result",iteration:B.iteration,tool_result:B.record,postToolUse:{toolName:B.record.name,parameters:n8(B.record.input),result:typeof B.record.output==="string"?B.record.output:JSON.stringify(B.record.output),success:!B.record.error,executionTimeMs:B.record.durationMs}}})},j=async(B)=>{let Y=$.agent_end??[];if(Y.length===0)return;R$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...Af(B,f),hookName:"agent_end",iteration:B.iteration,turn:B.turn,taskComplete:{taskMetadata:{}}}})},X=async(B)=>{let Y=$.agent_error??[];if(Y.length===0)return;R$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...Af(B,f),hookName:"agent_error",iteration:B.iteration,error:{name:B.error.name,message:B.error.message,stack:B.error.stack}}})},A=async(B)=>{if(n5(B.reason)){let V=$.agent_abort??[];if(V.length>0)R$({commands:V,cwd:f.cwd,logger:f.logger,payload:{...Af(B,f),hookName:"agent_abort",reason:B.reason,taskCancel:{taskMetadata:{}}}})}let Y=$.session_shutdown??[];if(Y.length===0)return;R$({commands:Y,cwd:f.cwd,logger:f.logger,payload:{...Af(B,f),hookName:"session_shutdown",reason:B.reason}})},P={};if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0||($.prompt_submit?.length??0)>0){if(($.agent_start?.length??0)>0||($.agent_resume?.length??0)>0)P.beforeRun=async(B)=>{let Y=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await W(I0(B.snapshot),Y);return};if(($.prompt_submit?.length??0)>0)P.onEvent=async(B)=>{if(B.type!=="message-added"||B.message.role!=="user")return;await H(a5({snapshot:B.snapshot},DZ(B.message.content)))}}if(($.tool_call?.length??0)>0)P.beforeTool=async(B)=>{let Y=await Q(GZ(B));return OG(Y)};if(($.tool_result?.length??0)>0)P.afterTool=async(B)=>{await Z(TZ(B));return};if(($.agent_end?.length??0)>0)P.afterRun=async({snapshot:B,result:Y})=>{if(Y.status!=="completed")return;await j({...I0(B),iteration:Y.iterations,turn:{outputText:Y.outputText,status:Y.status}})};if(($.agent_error?.length??0)>0||($.agent_abort?.length??0)>0||($.session_shutdown?.length??0)>0){let B=P.afterRun;P.afterRun=async(Y)=>{await B?.(Y);let{snapshot:V,result:R}=Y;if(R.status==="aborted"||n5(R.error?.message)){await A({...I0(V),reason:R.error?.message});return}if(R.error)await X({...I0(V),iteration:R.iterations,error:R.error})}}return P}function t8(f){return l8("core.hook_config_files",s5(f))}function F$(f,$){let J=f.map((W)=>W[$]).filter((W)=>typeof W==="function");if(J.length===0)return;return async(W)=>{let H;for(let Q of J){let Z=await Q(W);if(!Z||typeof Z!=="object")continue;let j=Z;H={...H??{},...j,stop:H?.stop===!0||j.stop===!0?!0:j.stop,options:H?.options||j.options?{...H?.options??{},...j.options??{}}:void 0}}return H}}function $2(f){let $=f.filter((J)=>J!==void 0);if($.length===0)return;return{beforeRun:F$($,"beforeRun"),afterRun:F$($,"afterRun"),beforeModel:F$($,"beforeModel"),afterModel:F$($,"afterModel"),beforeTool:F$($,"beforeTool"),afterTool:F$($,"afterTool"),onEvent:F$($,"onEvent")}}import{z as m0}from"zod";var s8=q$;var _Z=m0.object({settings:q$,updatedAt:m0.string().datetime(),tokenSource:m0.enum(["manual","oauth","migration"]).default("manual")}),o8=m0.object({version:m0.literal(1),lastUsedProvider:m0.string().min(1).optional(),providers:m0.record(m0.string(),_Z)});function t$(){return{version:1,providers:{}}}W0();import{upsertWorkspaceInfo as zG,WorkspaceManifestSchema as o5}from"@cline/shared";class e8{manifest;listeners=new Set;constructor(f){this.manifest=o5.parse(f??{workspaces:{}})}async addWorkspacePath(f){let $=await _8(f);return this.manifest=zG(this.manifest,$),this.emit({type:"workspace_added",workspace:$}),$}async switchWorkspace(f){let $=J$(f),J=this.manifest.workspaces[$];if(J)return this.manifest=o5.parse({...this.manifest,currentWorkspacePath:$}),this.emit({type:"workspace_switched",workspace:J}),J;let W=await this.addWorkspacePath($);return this.manifest=o5.parse({...this.manifest,currentWorkspacePath:W.rootPath}),this.emit({type:"workspace_switched",workspace:W}),W}subscribe(f){return this.listeners.add(f),()=>{this.listeners.delete(f)}}getCurrentWorkspace(){let f=this.manifest.currentWorkspacePath;if(!f)return;return this.manifest.workspaces[f]}getWorkspace(f){let $=J$(f);return this.manifest.workspaces[$]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(f){for(let $ of this.listeners)$(f)}}Uf();import{createHash as NG}from"node:crypto";var MZ=new Set,LZ=new Set;function qG(f){return NG("sha256").update(f).digest("hex")}function wG(f){if(f.vcsTypes&&f.vcsTypes.length>0)return f.vcsTypes;return[f.vcsType==="git"?"git":"none"]}function hZ(f){if(!f.telemetry)return;let $=qG(f.rootPath),J=f.rootCount??1;if(!MZ.has($))MZ.add($),k4(f.telemetry,{root_count:J,vcs_types:wG(f),init_duration_ms:f.durationMs,feature_flag_enabled:f.featureFlagEnabled??!0,is_remote_workspace:f.isRemoteWorkspace});if(f.initError&&!LZ.has($)){LZ.add($);let W=Error(f.initError.message);W.name=f.initError.errorType||"Error",I4(f.telemetry,W,{fallback_to_single_root:!0,workspace_count:J})}}function CG(f){return`${f.pluginName??f.pluginPath}: ${f.message}`}function EG(f,$,J){if($.length>0)for(let Q of $)J?.log(Q.message,{severity:"warn"});if(f.length===0)return;let W=f.slice(0,3).map(CG).join("; "),H=f.length>3?`; and ${f.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${W}${H}. Use --verbose for more details.`,{severity:"warn"});for(let Q of f)J?.log(`Plugin initialization failed (${Q.phase}) for ${Q.pluginPath}`,{severity:"warn",stack:Q.stack,pluginPath:Q.pluginPath,pluginName:Q.pluginName})}function SG(f,$){let J=typeof f.thinking==="boolean",W=typeof f.reasoningEffort==="string";if(!J&&!W)return $;return{...$??{},...J?{enabled:f.thinking}:{},...W?{effort:f.reasoningEffort}:{}}}function kG(f,$){return bG(f,$)}function IG(f){let $=0;for(let J of f??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;$+=1}return $}function mG(f){let $={...f.storedHeaders??{},...f.configHeaders??{}},J=f.accountId?.trim()||xG(f.accessToken);if($.originator="cline",$.session_id=f.sessionId,$["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)$["ChatGPT-Account-Id"]=J;return $}function xG(f){let $=f?.trim();if(!$)return;let J=Zf($),W=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let H=J?.organizations?.[0]?.id;if(typeof H==="string"&&H.length>0)return H;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}function gG(f,$,J,W,H){let Q=J.getProviderSettings(f.providerId),Z=W||Q?.modelCatalog?{...W??{},...Q?.modelCatalog??{}}:void 0,j={...Q??{},provider:f.providerId,model:f.modelId,apiKey:f.apiKey??Q?.apiKey,baseUrl:f.baseUrl??Q?.baseUrl,headers:f.providerId==="openai-codex"?mG({sessionId:$,configHeaders:f.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:f.apiKey??Q?.auth?.accessToken??Q?.apiKey}):f.headers??Q?.headers,reasoning:SG(f,Q?.reasoning),modelCatalog:Z},X=f0(j);if(f.knownModels)X.knownModels=f.knownModels;if(f.extensionContext)X.extensionContext=f.extensionContext;let P=f.fetch??X.fetch??H;if(P)X.fetch=P;return X}async function OZ(f){let{input:$,sessionId:J,providerSettingsManager:W,defaultTelemetry:H,defaultCapabilities:Q,defaultToolPolicies:Z,defaultFetch:j,onPluginEvent:X,onTeamEvent:A,createSpawnTool:P,localRuntime:B,readSessionMetadata:Y,writeSessionMetadata:V}=f,R=k0($.config),{modelCatalogDefaults:U,userInstructionService:K,configExtensions:F,onTeamRestored:y,...D}=B??{},M=Object.keys(D).length>0?D:void 0,{workspaceInfo:T,workspaceMetadata:_,durationMs:L,vcsType:O,initError:e}=await DQ(R),ff=M?.extensionContext,a={...ff??{},workspace:{...T,...ff?.workspace??{}},session:{...ff?.session??{},sessionId:J},logger:ff?.logger??M?.logger,telemetry:ff?.telemetry??M?.telemetry??H};hZ({telemetry:a.telemetry,rootPath:T.rootPath,workspaceInfo:T,rootCount:1,vcsType:O,durationMs:L,initError:e,featureFlagEnabled:!0});let g=t8({cwd:$.config.cwd,workspacePath:R,rootSessionId:J,logger:M?.logger,workspaceInfo:T}),Pf=xQ(M?.hooks)?void 0:a8({rootSessionId:J,workspacePath:R,workspaceInfo:T}),B0=$2([M?.hooks,Pf]),r;if(kG(F,"plugins"))try{r=await U8({pluginPaths:M?.pluginPaths,workspacePath:R,cwd:$.config.cwd,onEvent:X,providerId:$.config.providerId,modelId:$.config.modelId,workspaceInfo:T,session:a.session,client:a.client,user:a.user,logger:a.logger,telemetry:a.telemetry,automation:a.automation}),EG(r.failures,r.warnings,M?.logger)}catch(H1){let u=H1 instanceof Error?H1.message:String(H1);M?.logger?.log?.(`plugin loading failed; continuing without plugins (${u})`)}let b=sJ(g?[g]:void 0,sJ(M?.extensions,PJ(r?.extensions))),l={...$.config,...M??{},sessionId:J,hooks:B0,extensions:b,extensionContext:a,telemetry:a.telemetry},sf=gG(l,J,W,U,j),of=$2([l.hooks,l.checkpoint?.enabled===!0?w7({cwd:l.cwd,sessionId:J,logger:l.logger,createCheckpoint:l.checkpoint?.createCheckpoint,initialRunCount:IG($.initialMessages),readSessionMetadata:Y,writeSessionMetadata:V}):void 0]),u0={...l,providerConfig:sf,workspaceMetadata:_,hooks:of},_$=$.toolPolicies??l.toolPolicies??Z,W1=Ff(Q,$.capabilities),R2=W1?.requestToolApproval,w4=W1?.toolExecutors,M$=new e8({currentWorkspacePath:T.rootPath,workspaces:{[T.rootPath]:T}});return{effectiveInput:$,config:u0,providerConfig:sf,workspaceMetadata:_,workspaceInfo:T,extensions:b,hooks:of,toolPolicies:_$,requestToolApproval:R2,pluginSandboxShutdown:r?.shutdown,runtimeBuilderInput:{config:u0,hooks:of,extensions:b,onTeamEvent:A,createSpawnTool:P,onTeamRestored:y,userInstructionService:K,configExtensions:F,toolExecutors:w4,workspaceManager:M$,logger:u0.logger,telemetry:u0.telemetry}}}import{resolveDocumentsExtensionPath as vG}from"@cline/shared/storage";Uf();function zZ(f,$,J,W,H){if(J)x4(f.telemetry,{ulid:$,apiProvider:f.providerId,...H});else m4(f.telemetry,{ulid:$,apiProvider:f.providerId,...H});uG(f.telemetry,{workspacePath:W})}function uG(f,$){let J=vG("Hooks"),W=a$($.workspacePath),H=new Map;for(let Q of W){let Z=Q.hookEventName??"unknown",j=H.get(Z)??{global:0,workspace:0};if(Q.path===J||Q.path.startsWith(`${J}/`))j.global+=1;else j.workspace+=1;H.set(Z,j)}for(let[Q,Z]of H.entries())n4(f,Q,Z.global,Z.workspace)}function NZ(f,$){for(let J of $.mentions)p4(f,J,$.matchedFiles.includes(J)?1:0,"file",!$.matchedFiles.includes(J));for(let J of $.matchedFiles)r4(f,"file",J.length);for(let J of $.ignoredMentions)l4(f,"file","not_found",J)}import{chmodSync as rZ,existsSync as HW,mkdirSync as LT,readFileSync as hT,writeFileSync as OT}from"node:fs";import{basename as lZ,dirname as QW}from"node:path";import{resolveProviderSettingsPath as zT}from"@cline/shared/storage";import{existsSync as cG,mkdirSync as dG,readFileSync as rG,writeFileSync as lG}from"node:fs";import{mkdir as pG,readFile as iG,writeFile as nG}from"node:fs/promises";import{dirname as e5,join as aG}from"node:path";import*as _f from"@cline/llms";import{ModelCapabilitySchema as tG,ProviderCapabilitySchema as sG,ProviderClientSchema as oG,ProviderProtocolSchema as eG}from"@cline/shared";import{z as d}from"zod";var fT=d.object({id:d.string().optional(),name:d.string().optional(),capabilities:d.array(tG).optional(),supportsVision:d.boolean().optional(),supportsAttachments:d.boolean().optional(),supportsReasoning:d.boolean().optional()}).passthrough(),$T=d.object({name:d.string(),baseUrl:d.string(),defaultModelId:d.string().optional(),protocol:eG.optional(),client:oG.optional(),capabilities:d.array(sG).optional(),modelsSourceUrl:d.string().optional()}).passthrough(),qZ=d.object({provider:$T.optional(),models:d.record(d.string(),fT).optional()}).passthrough(),wZ=d.object({version:d.literal(1),providers:d.record(d.string(),qZ)}),JT=d.object({version:d.literal(1),providers:d.record(d.string(),d.unknown())}),f4=new Set;function bZ(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function K$(f){return aG(e5(f.getFilePath()),"models.json")}function $4(){return{version:1,providers:{}}}function CZ(f){let $=JT.safeParse(f);if(!$.success)return $4();let J={};for(let[W,H]of Object.entries($.data.providers)){let Q=qZ.safeParse(H);if(Q.success)J[W]=Q.data}return{version:1,providers:J}}function fW(f){if(!cG(f))return $4();try{let $=rG(f,"utf8");return CZ(JSON.parse($))}catch{}return $4()}async function s$(f){try{let $=await iG(f,"utf8");return CZ(JSON.parse($))}catch{}return $4()}function EZ(f,$){dG(e5(f),{recursive:!0});let J=wZ.parse($);lG(f,`${JSON.stringify(J,null,2)}
|
|
550
|
+
`,"utf8")}async function J4(f,$){await pG(e5(f),{recursive:!0});let J=wZ.parse($);await nG(f,`${JSON.stringify(J,null,2)}
|
|
551
|
+
`,"utf8")}function SZ(f,$){return{id:f,name:$.name??f,supportsAttachments:$.capabilities?.includes("files"),supportsVision:$.capabilities?.includes("images"),supportsReasoning:$.capabilities?.includes("reasoning")||$.thinkingConfig!=null}}function kZ(f){if(!f||f.length===0)return;let $=new Set;if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("tools"))$.add("tools");return $.size>0?[...$]:void 0}function IZ(f){let $=new Set;if(!f||f.length===0)return[...$];if(f.includes("streaming"))$.add("streaming");if(f.includes("tools"))$.add("tools");if(f.includes("reasoning"))$.add("reasoning");if(f.includes("prompt-cache"))$.add("prompt-cache");if(f.includes("vision"))$.add("images"),$.add("files");return[...$]}function WT(f){return f!=null&&typeof f.name==="string"&&typeof f.baseUrl==="string"}function mZ(f,$){return f??$??"openai-chat"}function xZ(f,$,J){return f??J??($==="openai-responses"?"openai":"openai-compatible")}function HT(f,$){let J=new Set($?.capabilities??[]);if($?.supportsVision)J.add("images");if($?.supportsAttachments)J.add("files");if($?.supportsReasoning)J.add("reasoning");return{id:f,name:$?.name??f,capabilities:J.size>0?[...J]:void 0}}function QT(f,$){for(let[J,W]of Object.entries($??{})){let H=W.id?.trim()||J.trim();if(!H)continue;_f.registerModel(f,H,HT(H,W))}}function ZT(f,$,J){return{...$??{},id:f,name:$?.name??f,capabilities:$?.capabilities??J}}function jT(f){return Object.assign({},..._f.resolveProviderModelCatalogKeys(f).map((J)=>_f.getGeneratedModelsForProvider(J)))}function XT(f){let $=f.provider.trim();if(!$||_f.isBuiltInProviderId($))return;let J=f.baseUrl?.trim();if(!J)return;let W=_f.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],H=jT($),Q=IZ(f.capabilities),Z=Q.length>0?Q:void 0,j=f.model?.trim(),X={...H,...W?.models??{}};if(j)X[j]=ZT(j,X[j],Z);let A=Object.keys(X).filter(Boolean),P=j||A[0];if(!P)return;let B=mZ(f.protocol,W?.provider.protocol),Y=xZ(f.client,B,W?.provider.client);_f.registerProvider({provider:{id:$,name:W?.provider.name??bZ($),description:W?.provider.description,protocol:B,client:Y,baseUrl:J,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:P,capabilities:kZ(f.capabilities)??W?.provider.capabilities,source:"file"},models:X})}function W4(f){for(let $ of Object.values(f.providers))XT($.settings)}function J2(f,$){let J=$.models??{};if(!WT($.provider)){QT(f,J);return}let W=IZ($.provider.capabilities),H=Object.entries(J).map(([A,P])=>({id:P.id?.trim()||A.trim(),model:P})).filter(({id:A})=>A.length>0),Q=$.provider.defaultModelId?.trim()||H[0]?.id||"default",Z=mZ($.provider.protocol,void 0),j=xZ($.provider.client,Z,void 0),X=Object.fromEntries(H.map(({id:A,model:P})=>[A,{id:A,name:P.name??A,capabilities:W.length>0?W:void 0,status:"active"}]));_f.registerProvider({provider:{id:f,name:$.provider.name.trim()||bZ(f),protocol:Z,client:j,baseUrl:$.provider.baseUrl,modelsSourceUrl:$.provider.modelsSourceUrl,defaultModelId:Q,capabilities:kZ($.provider.capabilities),source:"file"},models:X})}function gZ(f){let $=K$(f);if(f4.has($))return;let J=fW($);for(let[W,H]of Object.entries(J.providers))J2(W,H);f4.add($)}async function vZ(f){let $=K$(f);if(f4.has($))return;let J=await s$($);for(let[W,H]of Object.entries(J.providers))J2(W,H);f4.add($)}import{existsSync as AT,readFileSync as PT}from"node:fs";import{dirname as BT,join as $W}from"node:path";import*as cZ from"@cline/llms";import{resolveClineDataDir as YT}from"@cline/shared/storage";var dZ="openai";function VT(f){let $=f?.trim();if(!$)return;try{let J=JSON.parse($);if(!J)return;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:J.expiresAt,accountId:J.userInfo?.id}}catch{return}}function w(f){let $=f?.trim();return $?$:void 0}function uZ(f){if(!AT(f))return;try{let $=PT(f,"utf8"),J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function RT(f){let $=f.dataDir??YT(),J=f.globalStatePath??$W($,"globalState.json"),W=f.secretsPath??$W($,"secrets.json"),H=uZ(J),Q=uZ(W);if(!H&&!Q)return;return{globalState:H??{},secrets:Q??{}}}function FT(f){try{let J=new URL(f).hostname.toLowerCase();return J==="api.openai.com"||J.endsWith(".openai.azure.com")||J.endsWith(".services.ai.azure.com")}catch{return!1}}function KT(f){let $=w(f.openAiBaseUrl);if(!$)return!1;if(f.azureApiVersion||f.azureIdentity)return!1;return!FT($)}function JW(f,$){if(f==="openai"&&KT($))return dZ;return f}function yT(f,$,J,W){let H=J==="plan"?"planMode":"actMode",Q=$===W?w(J==="plan"?f.planModeApiModelId:f.actModeApiModelId):void 0,j={openrouter:`${H}OpenRouterModelId`,cline:`${H}ClineModelId`,openai:`${H}OpenAiModelId`,ollama:`${H}OllamaModelId`,lmstudio:`${H}LmStudioModelId`,litellm:`${H}LiteLlmModelId`,requesty:`${H}RequestyModelId`,together:`${H}TogetherModelId`,fireworks:`${H}FireworksModelId`,sapaicore:`${H}SapAiCoreModelId`,groq:`${H}GroqModelId`,baseten:`${H}BasetenModelId`,huggingface:`${H}HuggingFaceModelId`,"huawei-cloud-maas":`${H}HuaweiCloudMaasModelId`,oca:`${H}OcaModelId`,aihubmix:`${H}AihubmixModelId`,hicap:`${H}HicapModelId`,nousResearch:`${H}NousResearchModelId`,"vercel-ai-gateway":`${H}VercelAiGatewayModelId`}[$];return(j?w(typeof f[j]==="string"?f[j]:void 0):void 0)??Q}function UT(f,$,J){let W=J==="plan"?f.planModeReasoningEffort:f.actModeReasoningEffort,H=J==="plan"?f.geminiPlanModeThinkingLevel:f.geminiActModeThinkingLevel,Q=J==="plan"?f.planModeThinkingBudgetTokens:f.actModeThinkingBudgetTokens,Z=($==="gemini"?H:void 0)??W,j=Z==="none"||Z==="low"||Z==="medium"||Z==="high"?Z:void 0,X=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!j&&X===void 0)return;return{...j?{effort:j}:{},...X!==void 0?{budgetTokens:X}:{}}}function GT(f){let $=f["openai-codex-oauth-credentials"];if(!$)return;try{let J=JSON.parse($),W=w(J.access_token),H=w(J.refresh_token),Q=w(J.accountId);if(!W&&!H&&!Q)return;return{...W?{apiKey:W}:{},auth:{...W?{accessToken:W}:{},...H?{refreshToken:H}:{},...Q?{accountId:Q}:{}}}}catch{return}}function TT(f){let $=cZ.getGeneratedModelsForProvider(f);return Object.keys($)[0]??void 0}function DT(f,$,J,W){let H=JW(f,$),Q=w(W==="plan"?$.planModeApiProvider:$.actModeApiProvider),Z=yT($,f,W,Q)??TT(H),j=UT($,H,W),X=typeof $.requestTimeoutMs==="number"&&Number.isInteger($.requestTimeoutMs)&&$.requestTimeoutMs>0?$.requestTimeoutMs:void 0,A={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey,sapaicore:J.sapAiCoreClientId},P={};if(f==="openai-codex")Object.assign(P,GT(J));if(f==="cline")try{let F=w(J["cline:clineAccountId"]);if(F)P.auth={...P.auth??{},...VT(F)}}catch{}if(f==="openai"&&$.openAiHeaders)P.headers=$.openAiHeaders;if(f==="bedrock")P.aws={accessKey:w(J.awsAccessKey),secretKey:w(J.awsSecretKey),sessionToken:w(J.awsSessionToken),region:w($.awsRegion),authentication:$.awsAuthentication,profile:$.awsUseProfile?w($.awsProfile):void 0,usePromptCache:$.awsBedrockUsePromptCache,useCrossRegionInference:$.awsUseCrossRegionInference,useGlobalInference:$.awsUseGlobalInference,endpoint:w($.awsBedrockEndpoint),customModelBaseId:w(W==="plan"?$.planModeAwsBedrockCustomModelBaseId:$.actModeAwsBedrockCustomModelBaseId)};if(f==="vertex")P.gcp={projectId:w($.vertexProjectId),region:w($.vertexRegion)};if(f==="openai"&&($.azureApiVersion||$.azureIdentity!==void 0))P.azure={apiVersion:w($.azureApiVersion),useIdentity:$.azureIdentity};if(f==="sapaicore")P.sap={clientId:w(J.sapAiCoreClientId),clientSecret:w(J.sapAiCoreClientSecret),tokenUrl:w($.sapAiCoreTokenUrl),resourceGroup:w($.sapAiResourceGroup),deploymentId:w(W==="plan"?$.planModeSapAiCoreDeploymentId:$.actModeSapAiCoreDeploymentId),useOrchestrationMode:$.sapAiCoreUseOrchestrationMode};if(f==="oca"){P.oca={mode:$.ocaMode};let F=w(J.ocaRefreshToken);if(F)P.auth={...P.auth??{},refreshToken:F}}if(f==="qwen")P.apiLine=$.qwenApiLine;if(f==="moonshot")P.apiLine=$.moonshotApiLine;if(f==="zai")P.apiLine=$.zaiApiLine;if(f==="minimax")P.apiLine=$.minimaxApiLine;let B={anthropic:$.anthropicBaseUrl,openai:$.openAiBaseUrl,ollama:$.ollamaBaseUrl,lmstudio:$.lmStudioBaseUrl,litellm:$.liteLlmBaseUrl,gemini:$.geminiBaseUrl,requesty:$.requestyBaseUrl,asksage:$.asksageApiUrl,dify:$.difyBaseUrl,oca:$.ocaBaseUrl,aihubmix:$.aihubmixBaseUrl,sapaicore:$.sapAiCoreBaseUrl},Y=w(A[f]),V=w(B[f]),R={provider:H,...Y?{apiKey:Y}:{},...Z?{model:Z}:{},...V?{baseUrl:V}:{},...j?{reasoning:j}:{},...X?{timeout:X}:{},...P},U=s8.safeParse(R);if(!U.success)return;return Object.keys(R).filter((F)=>F!=="provider").length>0?U.data:void 0}function _T(f,$){if(f!==dZ)return;if(!$.baseUrl||!$.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:$.baseUrl,defaultModelId:$.model},models:{[$.model]:{id:$.model,name:$.model}}}}function MT(f,$){let J=new Set;for(let W of[f.actModeApiProvider,f.planModeApiProvider]){let H=w(W);if(H)J.add(H)}if(w($.apiKey))J.add("anthropic");if(w($.openRouterApiKey))J.add("openrouter");if(w($.openAiApiKey))J.add("openai");if(w($.openAiNativeApiKey))J.add("openai-native");if(w($["openai-codex-oauth-credentials"]))J.add("openai-codex");if(w($.geminiApiKey))J.add("gemini");if(w($.ollamaApiKey))J.add("ollama");if(w($.awsAccessKey)||w($.awsBedrockApiKey))J.add("bedrock");if(w(f.vertexProjectId)||w(f.vertexRegion))J.add("vertex");if(w($.clineApiKey))J.add("cline");if(w($.ocaApiKey))J.add("oca");return J}function WW(f){let $=f.providerSettingsManager.read(),J=RT(f);if(!J)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let{globalState:W,secrets:H}=J,Q=W.mode==="plan"?"plan":"act",Z=MT(W,H),j=t$();j.providers={...$.providers},j.lastUsedProvider=$.lastUsedProvider;let X=new Date().toISOString(),A=0,P=$W(BT(f.providerSettingsManager.getFilePath()),"models.json"),B=fW(P),Y=0;for(let U of Z){let K=JW(U,W);if(j.providers[K])continue;let F=DT(U,W,H,Q);if(!F)continue;j.providers[K]={settings:F,updatedAt:X,tokenSource:"migration"},A+=1;let y=_T(K,F);if(y&&!B.providers[K])B.providers[K]=y,Y+=1}if(A===0&&Y===0)return{migrated:!1,providerCount:Object.keys($.providers).length,lastUsedProvider:$.lastUsedProvider};let V=w(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),R=V?JW(V,W):void 0;if(j.lastUsedProvider=$.lastUsedProvider??(R&&j.providers[R]?R:Object.keys(j.providers)[0]),f.providerSettingsManager.write(j),Y>0)EZ(P,B);return{migrated:A>0||Y>0,providerCount:Object.keys(j.providers).length,lastUsedProvider:j.lastUsedProvider}}function NT(){return new Date().toISOString()}function qT(f){if(lZ(f)!=="providers.json")return;let $=QW(f);if(lZ($)!=="settings")return;return QW($)}class x0{filePath;dataDir;constructor(f={}){if(this.filePath=f.filePath??zT(),this.dataDir=f.dataDir??qT(this.filePath),this.dataDir||!f.filePath)WW({providerSettingsManager:this,dataDir:this.dataDir});if(gZ(this),W4(this.read()),HW(this.filePath))try{rZ(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!HW(this.filePath))return t$();try{let f=hT(this.filePath,"utf8"),$=JSON.parse(f),J=o8.safeParse($);if(J.success)return W4(J.data),J.data}catch{}return t$()}write(f){let $=o8.parse(f),J=QW(this.filePath);if(!HW(J))LT(J,{recursive:!0,mode:448});OT(this.filePath,`${JSON.stringify($,null,2)}
|
|
552
|
+
`,"utf8");try{rZ(this.filePath,384)}catch{}W4($)}saveProviderSettings(f,$={}){let J=s8.parse(f),W=this.read(),H=J.provider,Q=$.setLastUsed!==!1,Z=W.providers[H],j=$.tokenSource??Z?.tokenSource??"manual",X={...W,providers:{...W.providers,[H]:{settings:J,updatedAt:NT(),tokenSource:j}},lastUsedProvider:Q?H:W.lastUsedProvider};return this.write(X),X}getProviderSettings(f){return this.read().providers[f]?.settings}getLastUsedProviderSettings(){let f=this.read(),$=f.lastUsedProvider;if(!$)return;return f.providers[$]?.settings}getProviderConfig(f,$){let J=this.getProviderSettings(f);if(!J)return;return f0(J,$)}getLastUsedProviderConfig(f){let $=this.getLastUsedProviderSettings();if(!$)return;return f0($,f)}async refreshCatalog(){try{await b2({})}catch{}}}Uf();k8();import{execFile as wT}from"node:child_process";import{promisify as bT}from"node:util";var o$=bT(wT);function ZW(f){let $=f?.metadata?.checkpoint&&typeof f.metadata.checkpoint==="object"&&!Array.isArray(f.metadata.checkpoint)?f.metadata.checkpoint:void 0;return(Array.isArray($?.history)?$.history:[]).filter((W)=>!!W&&typeof W==="object"&&!Array.isArray(W)).flatMap((W)=>{let H=String(W.ref??"").trim(),Q=Number(W.createdAt??0),Z=Number(W.runCount??0);if(H.length===0||!Number.isFinite(Q)||!Number.isInteger(Z)||Z<1)return[];let j=W.kind==="stash"||W.kind==="commit"?W.kind:void 0;return[{ref:H,createdAt:Q,runCount:Z,...j?{kind:j}:{}}]})}function pZ(f,$){let J=ZW(f).filter((H)=>H.runCount<=$),W=J.at(-1);return W?{latest:W,history:J}:void 0}function CT(f,$){return f.reduce((J,W)=>{if(W.runCount>$)return J;if(!J||W.runCount>J.runCount)return W;return J},void 0)}function iZ(f,$){let J=0;for(let W=0;W<f.length;W+=1){let H=f[W];if(H?.role!=="user")continue;if(("metadata"in H&&H.metadata&&typeof H.metadata==="object"?H.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===$)return W}throw Error(`Could not find user message for checkpoint run ${$}`)}function ET(f,$){let J=iZ(f,$);return f.slice(0,J+1)}function nZ(f,$){let J=iZ(f,$);return f.slice(0,J)}function aZ(f){let $=f.checkpointRunCount;if(!Number.isInteger($)||$<1)throw Error("checkpointRunCount must be a positive integer");let J=CT(ZW(f.session),$);if(!J)throw Error(`No checkpoint found at or before run ${$} in session ${f.session.sessionId}`);let W=(f.cwd?.trim()||f.session.cwd||f.session.workspaceRoot).trim();if(!W)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:W,...f.restoreMessages!==!1?{messages:ET(f.messages??[],$)}:{}}}async function tZ(f,$){if((await o$("git",["-C",f,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${f} is not a git repository`);if(await o$("git",["-C",f,"cat-file","-e",`${$.ref}^{commit}`],{windowsHide:!0}),await o$("git",["-C",f,"reset","--hard"],{windowsHide:!0}),await o$("git",["-C",f,"clean","-fd"],{windowsHide:!0}),$.kind==="commit"){await o$("git",["-C",f,"reset","--hard",$.ref],{windowsHide:!0});return}await o$("git",["-C",f,"stash","apply",$.ref],{windowsHide:!0})}class gf extends Error{code;constructor(f,$){super($);this.code=f;this.name="SessionVersioningError"}}function ST(f){let $=f.sessionId.trim();if(!$)throw new gf("invalid_restore","sessionId is required");if(!f.restoreMessages&&!f.restoreWorkspace)throw new gf("invalid_restore","restore.messages or restore.workspace must be true");if(f.restoreMessages&&f.requiresStart)throw new gf("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger(f.checkpointRunCount)||f.checkpointRunCount<1)throw new gf("invalid_restore","checkpointRunCount must be a positive integer");return $}class e${async restoreCheckpoint(f){let $=f.restore?.messages!==!1,J=f.restore?.workspace!==!1,W=ST({sessionId:f.sessionId,restoreMessages:$,restoreWorkspace:J,requiresStart:f.start===void 0,checkpointRunCount:f.checkpointRunCount}),H=await f.getSession(W);if(!H)throw new gf("session_not_found",`Session ${W} not found`);let Q=$?await f.readMessages(W):void 0;if($&&Q?.length===0)throw new gf("session_messages_not_found",`No messages found for session ${W}`);let Z=aZ({session:H,messages:Q,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restoreMessages:$});if(J)await(f.applyWorkspaceCheckpoint??tZ)(Z.cwd,Z.checkpoint);let j=b0({session:H,messages:Q});if(!$)return{checkpoint:Z.checkpoint,sourceSnapshot:j};let X=pZ(H,f.checkpointRunCount),A=f.restore?.omitCheckpointMessageFromSession?nZ(Q??[],f.checkpointRunCount):Z.messages??[],P={sourceSession:H,sourceMessages:Q,sourceSnapshot:j,plan:Z,restoredCheckpointMetadata:X,initialMessages:A,restoreMessages:$,restoreWorkspace:J,checkpointRunCount:f.checkpointRunCount};if(!f.start||!f.startSession)throw new gf("invalid_restore","start is required when restore.messages is true");let B=f.buildStartInput?await f.buildStartInput(P,f.start):f.start,Y=await f.startSession(B),V=f.getStartedSessionId?.(Y);if(V)await(f.retainCheckpointRefs??q7)(Z.cwd,V,X?.history??[]);let R=V&&f.readRestoredSession?await f.readRestoredSession(V):void 0;return{sessionId:V,startResult:Y,messages:Z.messages,checkpoint:Z.checkpoint,sourceSnapshot:j,...R?{restoredSnapshot:b0({session:R,messages:A})}:{}}}}import{hasRuntimeConfigExtension as TD}from"@cline/shared";import{nanoid as DD}from"nanoid";import{spawn as kT}from"node:child_process";import{StringDecoder as fj}from"node:string_decoder";var IT="2024-11-05",mT=5000,xT=1500;function sZ(f){return f instanceof Error?f.message:String(f)}function oZ(f){let $=Buffer.from(JSON.stringify(f),"utf8"),J=Buffer.from(`Content-Length: ${$.byteLength}\r
|
|
553
553
|
\r
|
|
554
|
-
`,"utf8");return Buffer.concat([J,$])}function
|
|
555
|
-
`,"utf8")}class
|
|
554
|
+
`,"utf8");return Buffer.concat([J,$])}function eZ(f){return Buffer.from(`${JSON.stringify(f)}
|
|
555
|
+
`,"utf8")}class jW{buffer="";decoder=new fj("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];while(!0){let J=this.buffer.indexOf(`\r
|
|
556
556
|
\r
|
|
557
|
-
`);if(J<0)break;let
|
|
558
|
-
`);if(J<0)break;let H=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),H.length>0)$.push(H)}return $}}class nZ{registration;process;nextRequestId=1;pending=new Map;framedParser=new sH;newlineParser=new oH;stderrBuffer="";connected=!1;protocolMode="newline";constructor(f){this.registration=f}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let f=["newline","framed"],$;for(let J of f){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:Xh,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},Yh),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(H){$=H instanceof Error?H:Error(String(H))}}throw $??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let f=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!f)return;f.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter(($)=>typeof $?.name==="string"&&typeof $.inputSchema==="object"&&$.inputSchema!==null).map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}async callTool(f){return this.request("tools/call",{name:f.name,arguments:f.arguments??{}})}spawnProcess(f){let $=this.registration.transport;if($.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${$.type}`);this.framedParser=new sH,this.newlineParser=new oH,this.stderrBuffer="",this.protocolMode=f;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},H=Ph($.command,$.args??[],{cwd:$.cwd,env:{...process.env,...$.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=H,H.stdout.on("data",(W)=>this.handleStdout(W)),H.stderr.on("data",(W)=>{if(this.process!==H)return;if(this.stderrBuffer+=W.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),H.once("error",(W)=>{if(this.process!==H)return;this.failAllPending(Error(`MCP process error: ${rZ(W)}`))}),H.once("exit",(W,Q)=>{if(this.process!==H)return;this.connected=!1,this.process=void 0;let Z=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${W??"null"}, signal=${Q??"null"}).${Z}`))})}handleStdout(f){try{let $=this.protocolMode==="framed"?this.framedParser.push(f):this.newlineParser.push(f);for(let J of $){let H=JSON.parse(J);if(typeof H.id!=="number")continue;let W=this.pending.get(H.id);if(!W)continue;if(this.pending.delete(H.id),clearTimeout(W.timeout),H.error){let Q=H.error.message||`MCP request failed with code ${H.error.code??"unknown"}`;W.reject(Error(Q));continue}W.resolve(H.result)}}catch($){this.handleProtocolFailure($)}}handleProtocolFailure(f){let $=this.process;if(!$)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${rZ(f)}.${J}`)),$.kill()}async request(f,$,J=Vh){let H=this.process;if(!H?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let W=this.nextRequestId++,Q={jsonrpc:"2.0",id:W,method:f,...$?{params:$}:{}},Z=new Promise((j,P)=>{let X=setTimeout(()=>{this.pending.delete(W),P(Error(`MCP request timed out for "${this.registration.name}" (${f}).`))},J);this.pending.set(W,{resolve:j,reject:P,timeout:X})});try{H.stdin.write(this.protocolMode==="framed"?lZ(Q):pZ(Q))}catch(j){let P=this.pending.get(W);if(P)clearTimeout(P.timeout),this.pending.delete(W);throw j}return Z}notify(f,$){let J=this.process;if(!J?.stdin.writable)return;let H={jsonrpc:"2.0",method:f,...$?{params:$}:{}};J.stdin.write(this.protocolMode==="framed"?lZ(H):pZ(H))}failAllPending(f){for(let[$,J]of this.pending)clearTimeout(J.timeout),this.pending.delete($),J.reject(f)}}function e8(){return(f)=>new nZ(f)}import{existsSync as Bh,readFileSync as Ah}from"node:fs";import{resolveMcpSettingsPath as Rh}from"@cline/shared/storage";import{z as C}from"zod";var t1=C.record(C.string(),C.string()),aZ=C.record(C.string(),C.unknown()),Fh=C.object({type:C.literal("stdio"),command:C.string().min(1),args:C.array(C.string()).optional(),cwd:C.string().min(1).optional(),env:t1.optional()}),yh=C.object({type:C.literal("sse"),url:C.string().url(),headers:t1.optional()}),Kh=C.object({type:C.literal("streamableHttp"),url:C.string().url(),headers:t1.optional()}),Uh=C.discriminatedUnion("type",[Fh,yh,Kh]),Gh=C.object({transport:Uh,disabled:C.boolean().optional(),metadata:aZ.optional()}),hh=C.enum(["stdio","sse","http","streamableHttp"]).optional(),tZ=C.object({type:C.enum(["stdio","sse","streamableHttp"]).optional(),transportType:hh,disabled:C.boolean().optional(),metadata:aZ.optional()});function eH(f){if(!f)return;if(f==="http")return"streamableHttp";return f}var Th=tZ.extend({command:C.string().min(1),args:C.array(C.string()).optional(),cwd:C.string().min(1).optional(),env:t1.optional()}).superRefine((f,$)=>{let J=f.type??eH(f.transportType);if(J&&J!=="stdio")$.addIssue({code:C.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform((f)=>({transport:{type:"stdio",command:f.command,args:f.args,cwd:f.cwd,env:f.env},disabled:f.disabled,metadata:f.metadata})),Dh=tZ.extend({url:C.string().url(),headers:t1.optional()}).superRefine((f,$)=>{let J=f.type??eH(f.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")$.addIssue({code:C.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform((f)=>{if((f.type??eH(f.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata};return{transport:{type:"sse",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata}}),Mh=C.union([Gh,Th,Dh]),_h=C.object({mcpServers:C.record(C.string(),Mh)}).strict();function a$(){return Rh()}function fW(f={}){let $=f.filePath??a$(),J=Ah($,"utf8"),H;try{H=JSON.parse(J)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}let W=_h.safeParse(H);if(!W.success){let Q=W.error.issues.map((Z)=>{let j=Z.path.join(".");return j?`${j}: ${Z.message}`:Z.message}).join("; ");throw Error(`Invalid MCP settings at "${$}": ${Q}`)}return W.data}function f4(f={}){let $=f.filePath??a$();return Bh($)}function $W(f={}){let $=fW(f);return Object.entries($.mcpServers).map(([J,H])=>({name:J,transport:H.transport,disabled:H.disabled,metadata:H.metadata}))}async function $4(f,$={}){let J=$W($);for(let H of J)await f.registerServer(H);return J}function Of(){return Date.now()}function Lh(f){return f.map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}class s1{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor(f){this.clientFactory=f.clientFactory,this.toolsCacheTtlMs=f.toolsCacheTtlMs??5000}async registerServer(f){await this.runExclusive(f.name,async()=>{let $=this.servers.get(f.name);if(!$){this.servers.set(f.name,{registration:{...f},status:"disconnected",updatedAt:Of()});return}let J=JSON.stringify($.registration.transport)!==JSON.stringify(f.transport);if($.registration={...f},$.updatedAt=Of(),J)await this.disconnectState($),$.client=void 0,$.toolCache=void 0,$.toolCacheUpdatedAt=void 0})}async unregisterServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($),this.servers.delete(f)})}async connectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.connectState($)})}async disconnectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($)})}async setServerDisabled(f,$){await this.runExclusive(f,async()=>{let J=this.requireServer(f);if(J.registration={...J.registration,disabled:$},J.updatedAt=Of(),$)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map((f)=>({name:f.registration.name,status:f.status,disabled:f.registration.disabled===!0,lastError:f.lastError,toolCount:f.toolCache?.length??0,updatedAt:f.updatedAt,metadata:f.registration.metadata})).sort((f,$)=>f.name.localeCompare($.name))}async listTools(f){let $=this.requireServer(f),J=$.toolCacheUpdatedAt??0;if($.toolCache&&Of()-J<=this.toolsCacheTtlMs)return $.toolCache;return this.refreshTools(f)}async refreshTools(f){return this.runExclusive(f,async()=>{let $=this.requireServer(f),H=await(await this.ensureConnectedClient($)).listTools(),W=Lh(H);return $.toolCache=W,$.toolCacheUpdatedAt=Of(),$.updatedAt=Of(),W})}async callTool(f){return this.runExclusive(f.serverName,async()=>{let $=this.requireServer(f.serverName),J=await this.ensureConnectedClient($);return $.updatedAt=Of(),J.callTool({name:f.toolName,arguments:f.arguments,context:f.context})})}async dispose(){let f=[...this.servers.keys()];for(let $ of f)await this.unregisterServer($)}async ensureConnectedClient(f){if(await this.connectState(f),!f.client)throw Error(`MCP server "${f.registration.name}" does not have an initialized client.`);return f.client}async connectState(f){if(f.registration.disabled)throw Error(`MCP server "${f.registration.name}" is disabled and cannot be connected.`);if(f.status==="connected"&&f.client)return;f.status="connecting",f.updatedAt=Of();try{let $=f.client??await this.clientFactory(f.registration);await $.connect(),f.client=$,f.status="connected",f.lastError=void 0,f.updatedAt=Of()}catch($){throw f.status="disconnected",f.lastError=$ instanceof Error?$.message:String($),f.updatedAt=Of(),$}}async disconnectState(f){if(!f.client){f.status="disconnected",f.updatedAt=Of();return}try{await f.client.disconnect()}finally{f.status="disconnected",f.updatedAt=Of()}}requireServer(f){let $=this.servers.get(f);if(!$)throw Error(`Unknown MCP server: ${f}`);return $}async runExclusive(f,$){let J=this.operationLocks.get(f)??Promise.resolve(),H,W=new Promise((Z)=>{H=Z}),Q=J.catch(()=>{return}).then(()=>W);this.operationLocks.set(f,Q),await J.catch(()=>{return});try{return await $()}finally{if(H?.(),this.operationLocks.get(f)===Q)this.operationLocks.delete(f)}}}import{createHash as zh}from"node:crypto";var sZ=128,Oh=/[^a-zA-Z0-9_-]+/g,oZ=8,Nh=1,qh="mcp_tool";function bh(f){return zh("sha1").update(f).digest("hex").slice(0,oZ)}function wh(f){return f.replace(Oh,"_")}var J4=({serverName:f,toolName:$})=>{let J=`${f}__${$}`,H=wh(J);if(H===J&&J.length<=sZ)return J;let W=bh(J),Q=sZ-Nh-oZ;return`${H.slice(0,Q)||qh}_${W}`};function JW(f){return{[(f.nameTransform??J4)({serverName:f.serverName,toolName:f.toolName})]:{enabled:!1}}}function eZ(f){let $={};for(let J of f.toolNames)Object.assign($,JW({serverName:f.serverName,toolName:J,nameTransform:f.nameTransform}));return $}import{createTool as Ch}from"@cline/shared";function Eh(f,$){let J=$.description?.trim();if(J)return J;return`Execute MCP tool "${$.name}" from server "${f}".`}async function H4(f){let $=await f.provider.listTools(f.serverName),J=f.nameTransform??J4;return $.map((H)=>{let W=J({serverName:f.serverName,toolName:H.name});return Ch({name:W,description:Eh(f.serverName,H),inputSchema:H.inputSchema,timeoutMs:f.timeoutMs,retryable:f.retryable,maxRetries:f.maxRetries,execute:async(Q,Z)=>f.provider.callTool({serverName:f.serverName,toolName:H.name,arguments:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:void 0,context:Z})})})}ef();import{appendFileSync as Sh,existsSync as t$,mkdirSync as fj,readdirSync as kh,readFileSync as $j,renameSync as mh,writeFileSync as Ih}from"node:fs";import{join as HW}from"node:path";import{resolveTeamDataDir as xh}from"@cline/shared/storage";function Jj(){return new Date().toISOString()}function WW(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function Hj(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class W4{teamDirPath;constructor(f={}){this.teamDirPath=f.teamDir??xh()}init(){this.ensureTeamDir()}listTeamNames(){if(!t$(this.teamDirPath))return[];return kh(this.teamDirPath,{withFileTypes:!0}).filter((f)=>f.isDirectory()).filter((f)=>t$(this.statePath(f.name))).map((f)=>f.name).sort()}readState(f){let $=this.readEnvelope(f);return $?.teamState?Hj($.teamState):void 0}readHistory(f,$=200){let J=this.historyPath(f);if(!t$(J))return[];return $j(J,"utf8").split(`
|
|
559
|
-
`).map((
|
|
560
|
-
`,"utf8")}persistRuntime(f,$,J){this.ensureTeamSubdir(f);let
|
|
561
|
-
`,"utf8"),
|
|
557
|
+
`);if(J<0)break;let H=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!H)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let Q=Number.parseInt(H[1],10),Z=J+4,j=Z+Q;if(this.buffer.length<j)break;$.push(this.buffer.slice(Z,j)),this.buffer=this.buffer.slice(j)}return $}}class XW{buffer="";decoder=new fj("utf8");push(f){this.buffer+=this.decoder.write(f);let $=[];while(!0){let J=this.buffer.indexOf(`
|
|
558
|
+
`);if(J<0)break;let W=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),W.length>0)$.push(W)}return $}}class $j{registration;process;nextRequestId=1;pending=new Map;framedParser=new jW;newlineParser=new XW;stderrBuffer="";connected=!1;protocolMode="newline";constructor(f){this.registration=f}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let f=["newline","framed"],$;for(let J of f){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:IT,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},xT),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(W){$=W instanceof Error?W:Error(String(W))}}throw $??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let f=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!f)return;f.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter(($)=>typeof $?.name==="string"&&typeof $.inputSchema==="object"&&$.inputSchema!==null).map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}async callTool(f){return this.request("tools/call",{name:f.name,arguments:f.arguments??{}})}spawnProcess(f){let $=this.registration.transport;if($.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${$.type}`);this.framedParser=new jW,this.newlineParser=new XW,this.stderrBuffer="",this.protocolMode=f;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=kT($.command,$.args??[],{cwd:$.cwd,env:{...process.env,...$.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=W,W.stdout.on("data",(H)=>this.handleStdout(H)),W.stderr.on("data",(H)=>{if(this.process!==W)return;if(this.stderrBuffer+=H.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),W.once("error",(H)=>{if(this.process!==W)return;this.failAllPending(Error(`MCP process error: ${sZ(H)}`))}),W.once("exit",(H,Q)=>{if(this.process!==W)return;this.connected=!1,this.process=void 0;let Z=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${H??"null"}, signal=${Q??"null"}).${Z}`))})}handleStdout(f){try{let $=this.protocolMode==="framed"?this.framedParser.push(f):this.newlineParser.push(f);for(let J of $){let W=JSON.parse(J);if(typeof W.id!=="number")continue;let H=this.pending.get(W.id);if(!H)continue;if(this.pending.delete(W.id),clearTimeout(H.timeout),W.error){let Q=W.error.message||`MCP request failed with code ${W.error.code??"unknown"}`;H.reject(Error(Q));continue}H.resolve(W.result)}}catch($){this.handleProtocolFailure($)}}handleProtocolFailure(f){let $=this.process;if(!$)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${sZ(f)}.${J}`)),$.kill()}async request(f,$,J=mT){let W=this.process;if(!W?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let H=this.nextRequestId++,Q={jsonrpc:"2.0",id:H,method:f,...$?{params:$}:{}},Z=new Promise((j,X)=>{let A=setTimeout(()=>{this.pending.delete(H),X(Error(`MCP request timed out for "${this.registration.name}" (${f}).`))},J);this.pending.set(H,{resolve:j,reject:X,timeout:A})});try{W.stdin.write(this.protocolMode==="framed"?oZ(Q):eZ(Q))}catch(j){let X=this.pending.get(H);if(X)clearTimeout(X.timeout),this.pending.delete(H);throw j}return Z}notify(f,$){let J=this.process;if(!J?.stdin.writable)return;let W={jsonrpc:"2.0",method:f,...$?{params:$}:{}};J.stdin.write(this.protocolMode==="framed"?oZ(W):eZ(W))}failAllPending(f){for(let[$,J]of this.pending)clearTimeout(J.timeout),this.pending.delete($),J.reject(f)}}function H4(){return(f)=>new $j(f)}import{existsSync as gT,readFileSync as vT}from"node:fs";import{resolveMcpSettingsPath as uT}from"@cline/shared/storage";import{z as E}from"zod";var W2=E.record(E.string(),E.string()),Jj=E.record(E.string(),E.unknown()),cT=E.object({type:E.literal("stdio"),command:E.string().min(1),args:E.array(E.string()).optional(),cwd:E.string().min(1).optional(),env:W2.optional()}),dT=E.object({type:E.literal("sse"),url:E.string().url(),headers:W2.optional()}),rT=E.object({type:E.literal("streamableHttp"),url:E.string().url(),headers:W2.optional()}),lT=E.discriminatedUnion("type",[cT,dT,rT]),pT=E.object({transport:lT,disabled:E.boolean().optional(),metadata:Jj.optional()}),iT=E.enum(["stdio","sse","http","streamableHttp"]).optional(),Wj=E.object({type:E.enum(["stdio","sse","streamableHttp"]).optional(),transportType:iT,disabled:E.boolean().optional(),metadata:Jj.optional()});function AW(f){if(!f)return;if(f==="http")return"streamableHttp";return f}var nT=Wj.extend({command:E.string().min(1),args:E.array(E.string()).optional(),cwd:E.string().min(1).optional(),env:W2.optional()}).superRefine((f,$)=>{let J=f.type??AW(f.transportType);if(J&&J!=="stdio")$.addIssue({code:E.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform((f)=>({transport:{type:"stdio",command:f.command,args:f.args,cwd:f.cwd,env:f.env},disabled:f.disabled,metadata:f.metadata})),aT=Wj.extend({url:E.string().url(),headers:W2.optional()}).superRefine((f,$)=>{let J=f.type??AW(f.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")$.addIssue({code:E.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform((f)=>{if((f.type??AW(f.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata};return{transport:{type:"sse",url:f.url,headers:f.headers},disabled:f.disabled,metadata:f.metadata}}),tT=E.union([pT,nT,aT]),sT=E.object({mcpServers:E.record(E.string(),tT)}).strict();function f1(){return uT()}function PW(f={}){let $=f.filePath??f1(),J=vT($,"utf8"),W;try{W=JSON.parse(J)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}let H=sT.safeParse(W);if(!H.success){let Q=H.error.issues.map((Z)=>{let j=Z.path.join(".");return j?`${j}: ${Z.message}`:Z.message}).join("; ");throw Error(`Invalid MCP settings at "${$}": ${Q}`)}return H.data}function Q4(f={}){let $=f.filePath??f1();return gT($)}function BW(f={}){let $=PW(f);return Object.entries($.mcpServers).map(([J,W])=>({name:J,transport:W.transport,disabled:W.disabled,metadata:W.metadata}))}async function Z4(f,$={}){let J=BW($);for(let W of J)await f.registerServer(W);return J}function Cf(){return Date.now()}function oT(f){return f.map(($)=>({name:$.name,description:$.description,inputSchema:$.inputSchema}))}class H2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor(f){this.clientFactory=f.clientFactory,this.toolsCacheTtlMs=f.toolsCacheTtlMs??5000}async registerServer(f){await this.runExclusive(f.name,async()=>{let $=this.servers.get(f.name);if(!$){this.servers.set(f.name,{registration:{...f},status:"disconnected",updatedAt:Cf()});return}let J=JSON.stringify($.registration.transport)!==JSON.stringify(f.transport);if($.registration={...f},$.updatedAt=Cf(),J)await this.disconnectState($),$.client=void 0,$.toolCache=void 0,$.toolCacheUpdatedAt=void 0})}async unregisterServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($),this.servers.delete(f)})}async connectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.connectState($)})}async disconnectServer(f){await this.runExclusive(f,async()=>{let $=this.requireServer(f);await this.disconnectState($)})}async setServerDisabled(f,$){await this.runExclusive(f,async()=>{let J=this.requireServer(f);if(J.registration={...J.registration,disabled:$},J.updatedAt=Cf(),$)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map((f)=>({name:f.registration.name,status:f.status,disabled:f.registration.disabled===!0,lastError:f.lastError,toolCount:f.toolCache?.length??0,updatedAt:f.updatedAt,metadata:f.registration.metadata})).sort((f,$)=>f.name.localeCompare($.name))}async listTools(f){let $=this.requireServer(f),J=$.toolCacheUpdatedAt??0;if($.toolCache&&Cf()-J<=this.toolsCacheTtlMs)return $.toolCache;return this.refreshTools(f)}async refreshTools(f){return this.runExclusive(f,async()=>{let $=this.requireServer(f),W=await(await this.ensureConnectedClient($)).listTools(),H=oT(W);return $.toolCache=H,$.toolCacheUpdatedAt=Cf(),$.updatedAt=Cf(),H})}async callTool(f){return this.runExclusive(f.serverName,async()=>{let $=this.requireServer(f.serverName),J=await this.ensureConnectedClient($);return $.updatedAt=Cf(),J.callTool({name:f.toolName,arguments:f.arguments,context:f.context})})}async dispose(){let f=[...this.servers.keys()];for(let $ of f)await this.unregisterServer($)}async ensureConnectedClient(f){if(await this.connectState(f),!f.client)throw Error(`MCP server "${f.registration.name}" does not have an initialized client.`);return f.client}async connectState(f){if(f.registration.disabled)throw Error(`MCP server "${f.registration.name}" is disabled and cannot be connected.`);if(f.status==="connected"&&f.client)return;f.status="connecting",f.updatedAt=Cf();try{let $=f.client??await this.clientFactory(f.registration);await $.connect(),f.client=$,f.status="connected",f.lastError=void 0,f.updatedAt=Cf()}catch($){throw f.status="disconnected",f.lastError=$ instanceof Error?$.message:String($),f.updatedAt=Cf(),$}}async disconnectState(f){if(!f.client){f.status="disconnected",f.updatedAt=Cf();return}try{await f.client.disconnect()}finally{f.status="disconnected",f.updatedAt=Cf()}}requireServer(f){let $=this.servers.get(f);if(!$)throw Error(`Unknown MCP server: ${f}`);return $}async runExclusive(f,$){let J=this.operationLocks.get(f)??Promise.resolve(),W,H=new Promise((Z)=>{W=Z}),Q=J.catch(()=>{return}).then(()=>H);this.operationLocks.set(f,Q),await J.catch(()=>{return});try{return await $()}finally{if(W?.(),this.operationLocks.get(f)===Q)this.operationLocks.delete(f)}}}import{createHash as eT}from"node:crypto";var Hj=128,fD=/[^a-zA-Z0-9_-]+/g,Qj=8,$D=1,JD="mcp_tool";function WD(f){return eT("sha1").update(f).digest("hex").slice(0,Qj)}function HD(f){return f.replace(fD,"_")}var j4=({serverName:f,toolName:$})=>{let J=`${f}__${$}`,W=HD(J);if(W===J&&J.length<=Hj)return J;let H=WD(J),Q=Hj-$D-Qj;return`${W.slice(0,Q)||JD}_${H}`};function YW(f){return{[(f.nameTransform??j4)({serverName:f.serverName,toolName:f.toolName})]:{enabled:!1}}}function Zj(f){let $={};for(let J of f.toolNames)Object.assign($,YW({serverName:f.serverName,toolName:J,nameTransform:f.nameTransform}));return $}import{createTool as QD}from"@cline/shared";function ZD(f,$){let J=$.description?.trim();if(J)return J;return`Execute MCP tool "${$.name}" from server "${f}".`}async function X4(f){let $=await f.provider.listTools(f.serverName),J=f.nameTransform??j4;return $.map((W)=>{let H=J({serverName:f.serverName,toolName:W.name});return QD({name:H,description:ZD(f.serverName,W),inputSchema:W.inputSchema,timeoutMs:f.timeoutMs,retryable:f.retryable,maxRetries:f.maxRetries,execute:async(Q,Z)=>f.provider.callTool({serverName:f.serverName,toolName:W.name,arguments:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:void 0,context:Z})})})}W0();import{appendFileSync as jD,existsSync as $1,mkdirSync as jj,readdirSync as XD,readFileSync as Xj,renameSync as AD,writeFileSync as PD}from"node:fs";import{join as VW}from"node:path";import{resolveTeamDataDir as BD}from"@cline/shared/storage";function Aj(){return new Date().toISOString()}function RW(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function Pj(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class A4{teamDirPath;constructor(f={}){this.teamDirPath=f.teamDir??BD()}init(){this.ensureTeamDir()}listTeamNames(){if(!$1(this.teamDirPath))return[];return XD(this.teamDirPath,{withFileTypes:!0}).filter((f)=>f.isDirectory()).filter((f)=>$1(this.statePath(f.name))).map((f)=>f.name).sort()}readState(f){let $=this.readEnvelope(f);return $?.teamState?Pj($.teamState):void 0}readHistory(f,$=200){let J=this.historyPath(f);if(!$1(J))return[];return Xj(J,"utf8").split(`
|
|
559
|
+
`).map((W)=>W.trim()).filter(Boolean).map((W)=>{try{return JSON.parse(W)}catch{return}}).filter((W)=>W!==void 0).reverse().slice(0,$)}loadRuntime(f){let $=this.readEnvelope(f);return{state:$?.teamState?Pj($.teamState):void 0,teammates:$?.teammates??[],interruptedRunIds:[]}}handleTeamEvent(f,$){this.ensureTeamSubdir(f),jD(this.historyPath(f),`${JSON.stringify({ts:Aj(),eventType:$.type,payload:$})}
|
|
560
|
+
`,"utf8")}persistRuntime(f,$,J){this.ensureTeamSubdir(f);let W={version:1,updatedAt:Aj(),teamState:$,teammates:J},H=this.statePath(f),Q=`${H}.tmp`;PD(Q,`${JSON.stringify(W,null,2)}
|
|
561
|
+
`,"utf8"),AD(Q,H)}markInProgressRunsInterrupted(f,$){let J=this.readEnvelope(f);if(!J?.teamState?.runs?.length)return[];let W=J.teamState.runs.filter((Q)=>Q.status==="queued"||Q.status==="running").map((Q)=>Q.id);if(W.length===0)return[];let H=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((Q)=>Q.status==="queued"||Q.status==="running"?{...Q,status:"interrupted",error:$,endedAt:H}:Q)},this.persistRuntime(f,J.teamState,J.teammates),W}ensureTeamDir(){if(!$1(this.teamDirPath))jj(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir(f){let $=VW(this.ensureTeamDir(),RW(f));if(!$1($))jj($,{recursive:!0});return $}statePath(f){return VW(this.ensureTeamDir(),RW(f),"state.json")}historyPath(f){return VW(this.ensureTeamDir(),RW(f),"task-history.jsonl")}readEnvelope(f){let $=this.statePath(f);if(!$1($))return;try{let J=JSON.parse(Xj($,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as YD,mkdirSync as VD}from"node:fs";import{join as RD}from"node:path";import{safeJsonParse as Bj}from"@cline/shared";import{loadSqliteDb as FD,nowIso as FW}from"@cline/shared/db";import{resolveDbDataDir as KD}from"@cline/shared/storage";function yD(){return KD()}function J1(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function UD(f){let $=Bj(f);if(!Array.isArray($))return[];let J=[];for(let W of $){if(!W||typeof W!=="object")continue;let H=W,Q=H.agentId,Z=H.rolePrompt;if(typeof Q!=="string"||!Q.trim())continue;if(typeof Z!=="string"||!Z.trim())continue;let j={agentId:Q.trim(),rolePrompt:Z};if(typeof H.modelId==="string"&&H.modelId.trim())j.modelId=H.modelId.trim();if(typeof H.maxIterations==="number"&&Number.isFinite(H.maxIterations))j.maxIterations=Math.max(1,Math.floor(H.maxIterations));J.push(j)}return J}function GD(f){return{...f,tasks:f.tasks.map(($)=>({...$,createdAt:new Date($.createdAt),updatedAt:new Date($.updatedAt)})),mailbox:f.mailbox.map(($)=>({...$,sentAt:new Date($.sentAt),readAt:$.readAt?new Date($.readAt):void 0})),missionLog:f.missionLog.map(($)=>({...$,ts:new Date($.ts)})),runs:(f.runs??[]).map(($)=>({...$,startedAt:new Date($.startedAt),endedAt:$.endedAt?new Date($.endedAt):void 0,nextAttemptAt:$.nextAttemptAt?new Date($.nextAttemptAt):void 0,heartbeatAt:$.heartbeatAt?new Date($.heartbeatAt):void 0})),outcomes:(f.outcomes??[]).map(($)=>({...$,createdAt:new Date($.createdAt),finalizedAt:$.finalizedAt?new Date($.finalizedAt):void 0})),outcomeFragments:(f.outcomeFragments??[]).map(($)=>({...$,createdAt:new Date($.createdAt),reviewedAt:$.reviewedAt?new Date($.reviewedAt):void 0}))}}class Q2{teamDirPath;db;constructor(f={}){this.teamDirPath=f.teamDir??yD()}init(){this.getRawDb()}ensureTeamDir(){if(!YD(this.teamDirPath))VD(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return RD(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let f=FD(this.dbPath());return this.ensureSchema(f),this.db=f,f}ensureSchema(f){if(f.exec("PRAGMA journal_mode = WAL;"),f.exec("PRAGMA busy_timeout = 5000;"),f.exec(`
|
|
562
562
|
CREATE TABLE IF NOT EXISTS team_store_schema_version (
|
|
563
563
|
lock INTEGER PRIMARY KEY CHECK (lock = 1),
|
|
564
564
|
version INTEGER NOT NULL
|
|
@@ -642,13 +642,13 @@ ${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fi
|
|
|
642
642
|
version INTEGER NOT NULL DEFAULT 1,
|
|
643
643
|
PRIMARY KEY(team_name, fragment_id)
|
|
644
644
|
);
|
|
645
|
-
`)}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}withTransaction(f){let $=this.getRawDb();$.exec("BEGIN IMMEDIATE;");try{f(),$.exec("COMMIT;")}catch(J){try{$.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map((f)=>f.team_name)}readState(f){let $=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[
|
|
646
|
-
VALUES (?, ?, ?, ?, NULL, ?)`,[
|
|
645
|
+
`)}run(f,$=[]){return this.getRawDb().prepare(f).run(...$)}queryOne(f,$=[]){return this.getRawDb().prepare(f).get(...$)??void 0}queryAll(f,$=[]){return this.getRawDb().prepare(f).all(...$)}withTransaction(f){let $=this.getRawDb();$.exec("BEGIN IMMEDIATE;");try{f(),$.exec("COMMIT;")}catch(J){try{$.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map((f)=>f.team_name)}readState(f){let $=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[J1(f)]);if(!$)return;let J=Bj($.state_json);if(!J)return;try{return GD(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 ?",[J1(f),$]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime(f){let $=J1(f),J=this.readState($),W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[$]),H=W?UD(W.teammates_json):[];return{state:J,teammates:H,interruptedRunIds:[]}}appendTeamEvent(f,$,J,W){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
|
|
646
|
+
VALUES (?, ?, ?, ?, NULL, ?)`,[J1(f),FW(),$,JSON.stringify(J),W??null])}persistRuntime(f,$,J){let W=J1(f),H=FW();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
|
|
647
647
|
VALUES (?, ?, ?, ?)
|
|
648
648
|
ON CONFLICT(team_name) DO UPDATE SET
|
|
649
649
|
state_json = excluded.state_json,
|
|
650
650
|
teammates_json = excluded.teammates_json,
|
|
651
|
-
updated_at = excluded.updated_at`,[
|
|
651
|
+
updated_at = excluded.updated_at`,[W,JSON.stringify($),JSON.stringify(J),H]);for(let Q of $.tasks)this.run(`INSERT INTO team_tasks (team_name, task_id, title, description, status, assignee, depends_on_json, summary, version, updated_at)
|
|
652
652
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
|
|
653
653
|
ON CONFLICT(team_name, task_id) DO UPDATE SET
|
|
654
654
|
title = excluded.title,
|
|
@@ -658,7 +658,7 @@ ${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fi
|
|
|
658
658
|
depends_on_json = excluded.depends_on_json,
|
|
659
659
|
summary = excluded.summary,
|
|
660
660
|
version = team_tasks.version + 1,
|
|
661
|
-
updated_at = excluded.updated_at`,[
|
|
661
|
+
updated_at = excluded.updated_at`,[W,Q.id,Q.title,Q.description,Q.status,Q.assignee??null,JSON.stringify(Q.dependsOn??[]),Q.summary??null,Q.updatedAt.toISOString()]);for(let Q of $.runs??[])this.run(`INSERT INTO team_runs (team_name, run_id, agent_id, task_id, status, message, started_at, ended_at, error, lease_owner, heartbeat_at, version)
|
|
662
662
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
|
|
663
663
|
ON CONFLICT(team_name, run_id) DO UPDATE SET
|
|
664
664
|
agent_id = excluded.agent_id,
|
|
@@ -670,14 +670,14 @@ ${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fi
|
|
|
670
670
|
error = excluded.error,
|
|
671
671
|
lease_owner = excluded.lease_owner,
|
|
672
672
|
heartbeat_at = excluded.heartbeat_at,
|
|
673
|
-
version = team_runs.version + 1`,[
|
|
673
|
+
version = team_runs.version + 1`,[W,Q.id,Q.agentId,Q.taskId??null,Q.status,Q.message,Q.startedAt?Q.startedAt.toISOString():null,Q.endedAt?Q.endedAt.toISOString():null,Q.error??null,Q.leaseOwner??null,Q.heartbeatAt?Q.heartbeatAt.toISOString():null]);for(let Q of $.outcomes??[])this.run(`INSERT INTO team_outcomes (team_name, outcome_id, title, status, schema_json, finalized_at, version)
|
|
674
674
|
VALUES (?, ?, ?, ?, ?, ?, 1)
|
|
675
675
|
ON CONFLICT(team_name, outcome_id) DO UPDATE SET
|
|
676
676
|
title = excluded.title,
|
|
677
677
|
status = excluded.status,
|
|
678
678
|
schema_json = excluded.schema_json,
|
|
679
679
|
finalized_at = excluded.finalized_at,
|
|
680
|
-
version = team_outcomes.version + 1`,[
|
|
680
|
+
version = team_outcomes.version + 1`,[W,Q.id,Q.title,Q.status,JSON.stringify({requiredSections:Q.requiredSections}),Q.finalizedAt?Q.finalizedAt.toISOString():null]);for(let Q of $.outcomeFragments??[])this.run(`INSERT INTO team_outcome_fragments (team_name, outcome_id, fragment_id, section, source_agent_id, source_run_id, content, status, reviewed_by, reviewed_at, version)
|
|
681
681
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
|
|
682
682
|
ON CONFLICT(team_name, fragment_id) DO UPDATE SET
|
|
683
683
|
outcome_id = excluded.outcome_id,
|
|
@@ -688,28 +688,28 @@ ${f.summary}`,metadata:{kind:"compaction_summary",summary:f.summary,details:f.fi
|
|
|
688
688
|
status = excluded.status,
|
|
689
689
|
reviewed_by = excluded.reviewed_by,
|
|
690
690
|
reviewed_at = excluded.reviewed_at,
|
|
691
|
-
version = team_outcome_fragments.version + 1`,[
|
|
692
|
-
WHERE team_name = ? AND status IN ('queued', 'running')`,[$,W,J]),H.map((Q)=>Q.run_id)}handleTeamEvent(f,$){this.appendTeamEvent(f,$.type,$)}}function Qj(f={}){try{let $=new o1(f);return $.init(),$}catch{let $=new W4({teamDir:f.teamDir});return $.init(),$}}function ZW(f,$){return ih(f,$)}function ah(f,$){let J=$?.["*"]??{},H=$?.[f]??{};return{...J,...H}.enabled!==!1}function th(f,$){return f.filter((J)=>ah(J.name,$))}function Zj(f,$){return S$(th(f,$))}function jj(){return`team-${nh(5)}`}function jW(f,$,J,H,W,Q,Z,j){let P=uf[U0({mode:J})],X=V1($,H,J,W??X1);return Zj(y1({cwd:f,...P,enableSkills:!!Z,...X,executors:{...Z?{skills:Z}:{},...j??{}}}),Q)}function sh(f){return jW(f.cwd,f.providerId,f.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,oh,f.toolExecutors).some(($)=>$.name==="skills")}var oh=async()=>"";async function eh(f){let $=a$();if(!f4({filePath:$}))return{tools:[]};let J=new s1({clientFactory:e8()}),H;try{H=await $4(J,{filePath:$})}catch(j){await J.dispose().catch(()=>{});let P=j instanceof Error?j.message:String(j);return f?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${P}`),{tools:[]}}let W=H.filter((j)=>j.disabled!==!0),Q=await Promise.allSettled(W.map((j)=>H4({serverName:j.name,provider:J}))),Z=[];for(let[j,P]of Q.entries())if(P.status==="fulfilled")Z.push(...P.value);else{let X=P.reason instanceof Error?P.reason.message:String(P.reason);f?.log(`[mcp] Failed to load tools from MCP server "${W[j].name}", skipping: ${X}`)}return{tools:Z,shutdown:async()=>{await J.dispose()}}}function fT(f,$){if(!f)return;for(let J of f.getTeammateIds())try{f.shutdownTeammate(J,$)}catch{}}function $T(f){if(f===void 0)return!0;switch(f){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function JT(f){let $=uf[U0({mode:f.mode})];return{sessionId:f.sessionId||"",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",enableTools:f.enableTools!==!1,enableSpawnAgent:f.enableSpawnAgent??$.enableSpawnAgent??!0,enableAgentTeams:f.enableAgentTeams??$.enableAgentTeams??!0,disableMcpSettingsTools:f.disableMcpSettingsTools===!0,yolo:f.yolo===!0,missionLogIntervalSteps:typeof f.missionLogIntervalSteps==="number"&&Number.isFinite(f.missionLogIntervalSteps)?f.missionLogIntervalSteps:3,missionLogIntervalMs:typeof f.missionLogIntervalMs==="number"&&Number.isFinite(f.missionLogIntervalMs)?f.missionLogIntervalMs:120000}}class Q4{teamRuntimeEntries=new Map;async build(f){let{config:$,hooks:J,extensions:H,logger:W,telemetry:Q,createSpawnTool:Z,onTeamRestored:j,userInstructionService:P,configExtensions:X,toolExecutors:V}=f,Y=f.onTeamEvent??(()=>{}),B=JT($),A=cf(),R=[],U=$.teamName?.trim()||jj(),y=$.sessionId?.trim()||U,F=ZW(X,"rules"),K=ZW(X,"skills"),M=ZW(X,"workflows"),T=F||K||M,G=!1,h=Boolean(P),L=P,x;if(!L&&T)L=C$({skills:{workspacePath:$.cwd},rules:{workspacePath:$.cwd},workflows:{workspacePath:$.cwd}});if(L)await L.start().catch(()=>{});let Cf=B.enableTools&&K&&Boolean(L)&&(h||L?.hasConfiguredSkills($.skills)===!0)&&sh({cwd:$.cwd,providerId:$.providerId,mode:B.mode,modelId:$.modelId,toolRoutingRules:$.toolRoutingRules,toolPolicies:$.toolPolicies,toolExecutors:V}),p=L&&T?L.createExtension({includeRules:F,includeSkills:K,includeWorkflows:M,registerSkillsTool:Cf,allowedSkillNames:$.skills}):void 0,g=p?[...H??$.extensions??[],p]:H??$.extensions;if(B.enableTools){if(R.push(...jW($.cwd,$.providerId,B.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,V)),!B.disableMcpSettingsTools){let u=await eh($.logger);R.push(...u.tools),x=u.shutdown}}let v,i=B.enableAgentTeams?Qj():void 0,If=i?.loadRuntime(y),q=If?.state,xf=If?.teammates??[],Ef=new Map(xf.map((u)=>[u.agentId,u])),s=$.sessionId||U,o$,k0=[],m0=!1,K$=J8({providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey??"",baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:J,extensions:g,logger:W??$.logger,telemetry:f.telemetry??$.telemetry,workspaceMetadata:$.workspaceMetadata});if(!this.teamRuntimeEntries.has(s))this.teamRuntimeEntries.set(s,{delegatedAgentConfigProvider:K$});let e$=()=>{if(!B.enableAgentTeams)return;let u=this.teamRuntimeEntries.get(s)??{delegatedAgentConfigProvider:K$};if(this.teamRuntimeEntries.set(s,u),v=u.runtime,!v){if(v=new u1({teamName:U,leadAgentId:$.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(t)=>{if(Y(t),v&&i){if(t.type==="teammate_spawned"&&t.teammate?.rolePrompt){let af={agentId:t.agentId,rolePrompt:t.teammate.rolePrompt,modelId:t.teammate.modelId,maxIterations:t.teammate.maxIterations};Ef.set(af.agentId,af)}if(t.type==="teammate_shutdown"&&!$T(t.reason))Ef.delete(t.agentId);i.handleTeamEvent(y,t),i.persistRuntime(y,v.exportState(),Array.from(Ef.values()))}}}),q)v.hydrateState(q),m0=!0;u.runtime=v}if(!G){if(!v)return;G=!0;let t=Z8({runtime:v,leadAgentId:$.sessionId||"lead",restoredFromPersistence:Boolean(q),restoredTeammates:xf,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(af)=>{k0=af,o$?.addTools(af)},createBaseTools:B.enableTools?()=>jW($.cwd,$.providerId,B.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,V):void 0,teammateConfigProvider:K$});if(m0)v.recoverActiveRuns("runtime_recovered");if(t.restoredFromPersistence)j?.();R.push(...t.tools)}return v};if(B.enableSpawnAgent&&Z){let u=Z();R.push({...u,execute:async(t,af)=>{return e$(),u.execute(t,af)}})}if(B.enableAgentTeams)e$();let j2=Zj(R,$.toolPolicies),L4=j2.some((u)=>u.name===$f.SUBMIT_AND_EXIT&&u.lifecycle?.completesRun===!0),U$=B.enableAgentTeams?()=>{let u=this.teamRuntimeEntries.get(s)?.runtime;if(!u)return;let t=u.listTasks(),af=t.some((j0)=>j0.status==="in_progress"||j0.status==="pending"),uW=u.listRuns({}),uP=uW.some((j0)=>j0.status==="running"||j0.status==="queued");if(af||uP){let j0=t.filter((Gf)=>Gf.status==="in_progress"||Gf.status==="pending").map((Gf)=>`${Gf.id} (${Gf.status}): ${Gf.title}`).join(", "),cW=uW.filter((Gf)=>Gf.status==="running"||Gf.status==="queued").map((Gf)=>`${Gf.id} (${Gf.status})`).join(", "),z4=[];if(j0)z4.push(`Unfinished tasks: ${j0}`);if(cW)z4.push(`Active runs: ${cW}`);return`[SYSTEM] You still have team obligations. ${z4.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,f1=L4?{requireCompletionTool:!0,...U$?{completionGuard:U$}:{}}:U$?{completionGuard:U$}:void 0;return{tools:j2,logger:W??$.logger,telemetry:Q??$.telemetry,teamRuntime:v,teamRestoredFromPersistence:Boolean(q),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(s)?.delegatedAgentConfigProvider??K$,extensions:g,completionPolicy:f1,registerLeadAgent:(u)=>{if(o$=u,k0.length>0)u.addTools(S$(k0,[...A]))},shutdown:async(u)=>{if(fT(v,u),this.teamRuntimeEntries.delete(s),await x?.(),!h)L?.stop()}}}}import{isOAuthProviderId as HT}from"@cline/shared";var WT="https://api.cline.bot",PW="workos:";function QT(f,$){if(f==="cline")return`${PW}${$}`;return $}function ZT(f,$){if(f==="cline"&&$.toLowerCase().startsWith(PW))return $.slice(PW.length);return $}function jT(f){let J=jf(f)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function PT(f,$){let J=f.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let H=jT($);if(H)return H;return Date.now()-1}function XT(f,$){let J=$.auth?.accessToken?.trim(),H=$.auth?.refreshToken?.trim();if(!J||!H)return null;let W=ZT(f,J);if(!W)return null;return{access:W,refresh:H,expires:PT($,W),accountId:$.auth?.accountId}}function VT(f,$){let J=f?.expiresAt,H=$?.expiresAt;return f?.accessToken===$?.accessToken&&f?.refreshToken===$?.refreshToken&&f?.accountId===$?.accountId&&J===H}class Z4 extends Error{providerId;constructor(f){super(`OAuth credentials for provider "${f}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=f}}class XW{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor(f){this.providerSettingsManager=f?.providerSettingsManager??new C0,this.telemetry=f?.telemetry}async resolveProviderApiKey(f){if(!HT(f.providerId))return null;return this.resolveWithSingleFlight(f.providerId,f.forceRefresh)}async resolveWithSingleFlight(f,$=!1){let J=this.refreshInFlight.get(f);if(J)return J;let H=this.resolveProviderApiKeyInternal(f,$).catch((W)=>{throw W}).finally(()=>{this.refreshInFlight.delete(f)});return this.refreshInFlight.set(f,H),H}async resolveProviderApiKeyInternal(f,$){let J=this.providerSettingsManager.getProviderSettings(f);if(!J)return null;let H=XT(f,J);if(!H)return null;let W=await this.resolveCredentials(f,J,H,$);if(!W)throw new Z4(f);let Q=QT(f,W.access),Z={...J.auth??{},accessToken:Q,refreshToken:W.refresh,accountId:W.accountId};Z.expiresAt=W.expires;let j={...J,auth:Z},P=!VT(J.auth,j.auth);if(P)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:f,apiKey:Q,accountId:W.accountId,refreshed:P}}async resolveCredentials(f,$,J,H){if(f==="cline")return t4(J,{apiBaseUrl:$.baseUrl?.trim()||WT,telemetry:this.telemetry},{forceRefresh:H});if(f==="oca")return J6(J,{forceRefresh:H,telemetry:this.telemetry},{mode:$.oca?.mode,telemetry:this.telemetry});return o4(J,{forceRefresh:H,telemetry:this.telemetry})}}import{normalizeUserInput as YT}from"@cline/shared";import{nanoid as BT}from"nanoid";class Pj{list(f){return f?Nf(f):[]}update(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=$.promptId.trim(),H=f.pendingPrompts.findIndex((P)=>P.id===J);if(H<0)return{sessionId:$.sessionId,prompts:Nf(f),updated:!1};let W=f.pendingPrompts[H];if(!W)return{sessionId:$.sessionId,prompts:Nf(f),updated:!1};let Q=$.prompt===void 0?W.prompt:YT($.prompt).trim();if(!Q)throw Error("prompt cannot be empty");let Z=$.delivery??W.delivery,j={...W,prompt:Q,delivery:Z};return f.pendingPrompts.splice(H,1),AT(f,j,H,W.delivery),{sessionId:$.sessionId,prompts:Nf(f),prompt:j4(j),updated:!0}}delete(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=$.promptId.trim(),H=f.pendingPrompts.findIndex((Q)=>Q.id===J);if(H<0)return{sessionId:$.sessionId,prompts:Nf(f),removed:!1};let[W]=f.pendingPrompts.splice(H,1);return{sessionId:$.sessionId,prompts:Nf(f),prompt:W?j4(W):void 0,removed:!0}}enqueue(f,$){let{prompt:J,delivery:H,userImages:W,userFiles:Q}=$,Z=f.pendingPrompts.findIndex((j)=>j.prompt===J);if(Z>=0){let[j]=f.pendingPrompts.splice(Z,1),P={...j,prompt:J,userImages:W??j.userImages,userFiles:Q??j.userFiles};if(H==="steer"||j.delivery==="steer")f.pendingPrompts.unshift({...P,delivery:"steer"});else f.pendingPrompts.push(P)}else{let j={id:`pending_${Date.now()}_${BT(5)}`,prompt:J,delivery:H,userImages:W,userFiles:Q};if(H==="steer")f.pendingPrompts.unshift(j);else f.pendingPrompts.push(j)}return Nf(f)}consumeSteer(f){let $=f.pendingPrompts.findIndex((H)=>H.delivery==="steer");if($<0)return{prompts:Nf(f)};let[J]=f.pendingPrompts.splice($,1);return{entry:J,prompts:Nf(f)}}shiftNext(f){return{entry:f.pendingPrompts.shift(),prompts:Nf(f)}}requeueFront(f,$){return f.pendingPrompts.unshift($),Nf(f)}clear(f){return f.pendingPrompts.length=0,[]}}class VW{deps;service=new Pj;constructor(f){this.deps=f}list(f){return this.service.list(this.deps.getSession(f))}update(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=this.service.update($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}delete(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=this.service.delete($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}enqueue(f,$){let J=this.deps.getSession(f);if(!J||J.aborting)return;this.service.enqueue(J,$),this.emitPrompts(J),this.scheduleDrain(f,J)}consumeSteer(f){let $=this.deps.getSession(f);if(!$)return;let{entry:J}=this.service.consumeSteer($);if(!J)return;return this.emitPrompts($),this.emitSubmitted($,J),J.prompt}clearAborted(f){if(f.pendingPrompts.length===0)return;this.service.clear(f),this.emitPrompts(f)}emitPrompts(f){this.deps.emit({type:"pending_prompts",payload:{sessionId:f.sessionId,prompts:Nf(f)}})}scheduleDrain(f,$){if($.pendingPrompts.length===0||$.aborting||$.drainingPendingPrompts||!$.agent.canStartRun())return;queueMicrotask(()=>{this.drain(f)})}async drain(f){let $=this.deps.getSession(f);if(!$||$.aborting||$.drainingPendingPrompts)return;if(!$.agent.canStartRun())return;let{entry:J}=this.service.shiftNext($);if(!J)return;this.emitPrompts($),this.emitSubmitted($,J),$.drainingPendingPrompts=!0;try{await this.deps.send({sessionId:f,prompt:J.prompt,userImages:J.userImages,userFiles:J.userFiles})}catch(H){if((H instanceof Error?H.message:String(H)).includes("already in progress"))this.service.requeueFront($,J),this.emitPrompts($);else throw H}finally{if($.drainingPendingPrompts=!1,$.pendingPrompts.length>0&&$.status!=="failed"&&$.status!=="cancelled")queueMicrotask(()=>{this.drain(f)})}}emitSubmitted(f,$){let J=j4($);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:f.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function j4(f){return{id:f.id,prompt:f.prompt,delivery:f.delivery,attachmentCount:(f.userImages?.length??0)+(f.userFiles?.length??0)}}function Nf(f){return f.pendingPrompts.map(j4)}function AT(f,$,J,H){if($.delivery==="steer")f.pendingPrompts.unshift($);else if(H==="steer")f.pendingPrompts.push($);else f.pendingPrompts.splice(J,0,$)}Af();class YW{deps;constructor(f){this.deps=f}dispatchAgentEvent(f,$,J){let H=this.deps.getSession(f),W={sessionId:f,config:$,liveSession:H,usageBySession:this.deps.usageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},Q=EH(J),Z=H&&Q.agentId===Xj(H.agent);SH(W,J,Z?{isPrimaryAgentEvent:!0,...H?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent(f,$){let J=this.deps.getSession(f);if(J){if(FH(J,$),$.type==="agent_event"){let H={sessionId:f,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};SH(H,$.event,{teamRole:"teammate",teamAgentId:$.agentId,isPrimaryAgentEvent:!1})}if($.type==="teammate_spawned"){let H=Q0({agentId:$.teammate.runtimeAgentId??$.agentId,conversationId:$.teammate.conversationId,parentAgentId:$.teammate.parentAgentId,createdByAgentId:Xj(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:$.agentId});if(H)x0(J.config.telemetry,{ulid:f,modelId:$.teammate.modelId??J.config.modelId,provider:J.config.providerId,...H})}}if(await yH(f,$,this.deps.invokeBackendOptional),J)KH(J,f,$,this.deps.emit)}async handlePluginEvent(f,$,J){if($.name==="plugin_log"){this.handlePluginLog(f,$.payload);return}if($.name==="automation_event"){let P=this.deps.getSession(f)?.config.extensionContext?.automation??J;if(!P)return;let X=$.payload&&typeof $.payload==="object"?$.payload:void 0;if(!X)return;await P.ingestEvent(X);return}if($.name!=="steer_message"&&$.name!=="queue_message"&&$.name!=="pending_prompt")return;let H=$.payload&&typeof $.payload==="object"?$.payload:void 0,W=typeof H?.sessionId==="string"&&H.sessionId.trim().length>0?H.sessionId.trim():f,Q=typeof H?.prompt==="string"?H.prompt.trim():"";if(!Q)return;let Z=$.name==="steer_message"?"steer":$.name==="queue_message"?"queue":H?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(W,{prompt:Q,delivery:Z})}handlePluginLog(f,$,J){let H=this.deps.getSession(f),W=J??H?.config.extensionContext?.logger??H?.config.logger;if(!W||!$||typeof $!=="object")return;let Q=$,Z=typeof Q.message==="string"?Q.message:"";if(!Z)return;let j=Q.metadata&&typeof Q.metadata==="object"?{...Q.metadata}:{};if(j.sessionId??=f,typeof Q.pluginName==="string"&&Q.pluginName)j.pluginName=Q.pluginName;if(Q.level==="debug"){W.debug(Z,j);return}if(Q.level==="error"){if(W.error)W.error(Z,j);else W.log(Z,{...j,severity:"error"});return}W.log(Z,j)}}function Xj(f){return f.getAgentId()}function BW(f){return{sessionId:f.sessionId,source:f.source,pid:process.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:q0(f.config),teamName:f.config.teamName?.trim()||void 0,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,parentSessionId:typeof f.sessionMetadata?.parentSessionId==="string"?f.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof f.sessionMetadata?.parentAgentId==="string"?f.sessionMetadata.parentAgentId:void 0,agentId:typeof f.sessionMetadata?.agentId==="string"?f.sessionMetadata.agentId:void 0,conversationId:typeof f.sessionMetadata?.conversationId==="string"?f.sessionMetadata.conversationId:void 0,isSubagent:typeof f.sessionMetadata?.isSubagent==="boolean"?f.sessionMetadata.isSubagent:!1,prompt:f.pendingPrompt,metadata:f.sessionMetadata,messagesPath:f.artifacts?.messagesPath,updatedAt:f.updatedAt??f.endedAt??f.startedAt}}function AW(f,$){let J=f[$];return typeof J==="function"?J:null}async function Vj(f,$,...J){let H=AW(f,$);if(!H)throw Error(`session service method not available: ${$}`);return Promise.resolve(H.apply(f,J))}async function Yj(f,$,...J){let H=AW(f,$);if(!H)return;await Promise.resolve(H.apply(f,J))}async function Bj(f,$,...J){let H=AW(f,$);if(!H)return;return await Promise.resolve(H.apply(f,J))}ef();Af();function RW(f,$,J,H){return w$({configProvider:{getRuntimeConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:$.hooks,extensions:$.extensions,logger:$.logger,telemetry:$.telemetry},getConnectionConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Q=$.enableTools?y1({cwd:$.cwd,...uf[U0({mode:$.mode})],executors:H}):[];if($.enableSpawnAgent)Q.push(RW(f,$,J,H));return S$(Q)},onSubAgentEvent:(Q)=>f.onAgentEvent(J,$,Q),onSubAgentStart:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime;f.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let j=Q0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)x0($.telemetry,{ulid:J,modelId:$.modelId,provider:$.providerId,...j});Y2($.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...j}),f.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime,j=f.subAgentStarts.get(Q.subAgentId),P=j?Date.now()-j.startedAt:0,X=Q.result?.text?Q.result.text.split(`
|
|
693
|
-
`).length:0;Y2($.telemetry,{event:"ended",ulid:J,durationMs:P,outputLines:X,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...Q0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId})}),f.subAgentStarts.delete(Q.subAgentId),f.invokeBackendOptional("handleSubAgentEnd",J,Q)}})}import{readFile as RT,stat as FT}from"node:fs/promises";var yT=20480000;async function Aj(f){let $=await FT(f);if(!$.isFile())throw Error("Path is not a file");if($.size>yT)throw Error("File is too large to read into context.");let J=await RT(f,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var Rj=5000;class E0{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new E1;sessions=new Map;usageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new n$;constructor(f){let $=KT();if($)MT($);let J=j$(f.distinctId);this.sessionService=f.sessionService,this.runtimeBuilder=f.runtimeBuilder??new Q4,this.createAgentInstance=f.createAgent??((H)=>new G0(H)),this.defaultCapabilities=Vf(f.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=f.toolPolicies,this.providerSettingsManager=f.providerSettingsManager??new C0,this.oauthTokenManager=f.oauthTokenManager??new XW({providerSettingsManager:this.providerSettingsManager,telemetry:f.telemetry}),this.defaultTelemetry=f.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=f.fetch,this.pendingPromptsController=new VW({getSession:(H)=>this.sessions.get(H),emit:(H)=>this.emit(H),send:(H)=>this.runTurn(H)}),this.pendingPrompts={list:async(H)=>this.pendingPromptsController.list(H.sessionId),update:async(H)=>this.pendingPromptsController.update(H),delete:async(H)=>this.pendingPromptsController.delete(H)},this.eventBridge=new YW({getSession:(H)=>this.sessions.get(H),usageBySession:this.usageBySession,emit:(H)=>this.emit(H),persistMessages:(H,W,Q)=>{this.invoke("persistSessionMessages",H,W,Q)},enqueuePendingPrompt:(H,W)=>this.pendingPromptsController.enqueue(H,W),invokeBackendOptional:(H,...W)=>this.invokeOptional(H,...W)})}async startSession(f){let $=f.source??Pf.CLI,J=n(),H=f.config.sessionId?.trim()??"",W=H||hT(),Q=f,Z=Q.initialMessages??[];this.usageBySession.set(W,Z.length>0?CH(Z):c$());let j=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!j)throw Error("session service method not available: ensureSessionsDir");let P=FW(j,W),X=FW(P,`${W}.messages.json`),V=FW(P,`${W}.json`),Y=q0(f.config),B=yf.parse({version:1,session_id:W,source:$,pid:process.pid,started_at:J,status:"running",interactive:f.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Q.config.cwd,workspace_root:Y,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,messages_path:X}),A;if(H.length>0&&Z.length>0&&!Q.prompt?.trim()){let q=await this.invokeOptionalValue("readSessionManifest",W);if(q)B=q,A={manifestPath:V,messagesPath:q.messages_path||X,manifest:q}}let U=Vf(this.defaultCapabilities,f.capabilities),y=U?.toolExecutors??this.toolExecutors,F=f.localRuntime,K=F?.extensionContext?.logger??F?.logger,M=F?.extensionContext?.automation,T;T=await GZ({input:Q,localRuntime:f.localRuntime,sessionId:W,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(q)=>{if(q.name==="plugin_log"){this.eventBridge.handlePluginLog(W,q.payload,K);return}this.eventBridge.handlePluginEvent(W,q,M)},onTeamEvent:(q)=>{this.eventBridge.handleTeamEvent(W,q),T.config.onTeamEvent?.(q)},createSpawnTool:()=>RW({getSession:(q)=>this.sessions.get(q),subAgentStarts:this.subAgentStarts,onAgentEvent:(q,xf,Ef)=>this.eventBridge.dispatchAgentEvent(q,xf,Ef),invokeBackendOptional:(q,...xf)=>this.invokeOptional(q,...xf)},T.config,W,y),readSessionMetadata:async()=>(await this.getSession(W))?.metadata,writeSessionMetadata:async(q)=>{await this.persistSessionMetadata(W,()=>q)}});let G=await this.runtimeBuilder.build(T.runtimeBuilderInput),h=T.config,L=T.providerConfig;if(G.teamRuntime&&!h.teamName?.trim())h.teamName=G.teamRuntime.getTeamName();let x=[...G.tools,...h.extraTools??[]],Cf=G.extensions??T.extensions,p={sessionId:W,providerId:L.providerId,modelId:L.modelId,apiKey:L.apiKey,baseUrl:L.baseUrl,headers:L.headers,knownModels:L.knownModels,providerConfig:L,thinking:h.thinking,reasoningEffort:h.reasoningEffort??L.reasoningEffort,systemPrompt:h.systemPrompt,maxIterations:h.maxIterations,execution:h.execution,prepareTurn:wH(h),tools:x,hooks:T.hooks,extensions:Cf,hookErrorMode:h.hookErrorMode,initialMessages:T.effectiveInput.initialMessages,userFileContentLoader:Aj,toolPolicies:T.toolPolicies,requestToolApproval:T.requestToolApproval,onConsecutiveMistakeLimitReached:h.onConsecutiveMistakeLimitReached,completionPolicy:G.completionPolicy,consumePendingUserMessage:()=>{let q=this.pendingPromptsController.consumeSteer(W);return q?d1(q,h.mode):q},logger:G.logger??h.logger,extensionContext:h.extensionContext,onEvent:(q)=>this.eventBridge.dispatchAgentEvent(W,h,q)};p.hooks={...p.hooks,onEvent:async(q)=>{if(await T.hooks?.onEvent?.(q),q.type!=="assistant-message")return;let xf=this.sessions.get(W);if(!xf)return;let Ef=xf.agent.getMessages();try{await this.invoke("persistSessionMessages",W,Ef,h.systemPrompt)}catch(s){h.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:W,error:s})}}};let g=this.createAgentInstance(p);if(p.onEvent)g.subscribeEvents(p.onEvent);G.registerLeadAgent?.(g);let v=Q0({agentId:g.getAgentId(),conversationId:g.getConversationId(),teamId:G.teamRuntime?.getTeamId(),teamName:G.teamRuntime?.getTeamName(),teamRole:G.teamRuntime?"lead":void 0});if(hZ(h,W,H.length>0,Y,v),v)x0(h.telemetry,{ulid:W,modelId:h.modelId,provider:h.providerId,...v});if(G.teamRuntime)c4(h.telemetry,{ulid:W,teamId:G.teamRuntime.getTeamId(),teamName:G.teamRuntime.getTeamName(),leadAgentId:g.getAgentId(),restoredFromPersistence:G.teamRestoredFromPersistence===!0});let i={sessionId:W,config:h,sessionMetadata:Q.sessionMetadata,...A?{artifacts:A}:{},source:$,startedAt:A?.manifest.started_at??J,updatedAt:A?.manifest.ended_at??A?.manifest.started_at??J,pendingPrompt:B.prompt,runtime:G,agent:g,started:!1,status:A?.manifest.status??"running",aborting:!1,interactive:f.interactive===!0,persistedMessages:Z,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:T.pluginSandboxShutdown,submitAndExitObserved:!1};if(this.sessions.set(W,i),this.emitStatus(W,"running"),Z.length>0&&!A){if(await this.ensureSessionPersisted(i),await this.invoke("persistSessionMessages",i.sessionId,Z,i.config.systemPrompt),!Q.prompt?.trim())await this.updateStatus(i,"completed",0)}let If;try{if(Q.prompt?.trim())if(If=await this.executeTurn(i,{prompt:Q.prompt,userImages:Q.userImages,userFiles:Q.userFiles}),!i.interactive)await this.finalizeSingleRun(i,If.finishReason);else await this.completeInteractiveTurn(i,If.finishReason)}catch(q){if(i.interactive&&i.aborting)If=await this.completeAbortedInteractiveTurn(i);else throw await this.failSession(i),q}return{sessionId:W,manifest:B,manifestPath:V,messagesPath:X,result:If}}async restoreSession(f){return this.sessionVersioning.restoreCheckpoint({...f,getSession:($)=>this.getSession($),readMessages:($)=>this.readSessionMessages($),buildStartInput:($,J)=>{let H=$.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:$.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...H?{sessionMetadata:H}:{},initialMessages:$.initialMessages}},startSession:($)=>this.startSession($),getStartedSessionId:($)=>$.sessionId,readRestoredSession:($)=>this.getSession($)})}async runTurn(f){let $=this.getSessionOrThrow(f.sessionId),J=$.agent.canStartRun(),H=f.delivery??($.interactive&&!J?"queue":void 0);if($.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:f.sessionId,promptLength:f.prompt.length,userImageCount:f.userImages?.length??0,userFileCount:f.userFiles?.length??0,delivery:H??"immediate"}}),H==="queue"||H==="steer"){this.pendingPromptsController.enqueue(f.sessionId,{prompt:f.prompt,delivery:H,userImages:f.userImages,userFiles:f.userFiles});return}try{let W=await this.executeTurn($,{prompt:f.prompt,userImages:f.userImages,userFiles:f.userFiles});if(!$.interactive)await this.finalizeSingleRun($,W.finishReason);else await this.completeInteractiveTurn($,W.finishReason);if(W.finishReason==="error"||W.finishReason==="aborted")return W;return queueMicrotask(()=>{this.pendingPromptsController.drain(f.sessionId)}),W}catch(W){if($.interactive&&$.aborting)return await this.completeAbortedInteractiveTurn($);throw await this.failSession($),W}}async getAccumulatedUsage(f){return x7(this.usageBySession.get(f))}async abort(f,$){let J=this.sessions.get(f);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:f}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort($)}async stopSession(f){let $=this.sessions.get(f);if(!$)return;if($.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:f}}),$.interactive&&$.status!=="running"){await this.releaseSessionRuntime($,"session_stop");return}$.aborting=!0,$.agent.abort(Error("session_stop")),await this.shutdownSession($,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose(f="session_manager_dispose"){let $=[...this.sessions.values()];if($.length===0)return;await Promise.allSettled($.map((J)=>J.interactive&&J.status!=="running"?this.releaseSessionRuntime(J,f):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:f,endReason:"disposed"}))),this.usageBySession.clear()}async getSession(f){let $=this.sessions.get(f);if($)return BW($);let J=f.trim();if(!J)return;let H=await this.getRow(J);if(H)return w1(H);let W=await this.readManifest(J);return W?nJ(W):void 0}async listSessions(f=200){let J=(await this.listRows(f)).map(w1),H=new Set(J.map((W)=>W.sessionId));for(let W of this.sessions.values()){if(H.has(W.sessionId))continue;J.unshift(BW(W))}return J.slice(0,f)}async deleteSession(f){if(this.sessions.has(f))await this.stopSession(f);let $=await this.invoke("deleteSession",f);if($.deleted)this.usageBySession.delete(f);return $.deleted}async updateSession(f,$){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:f,prompt:$.prompt,metadata:$.metadata,title:$.title}))?.updated===!0}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.getRow($);if(J?.messagesPath)return J$(J.messagesPath);let H=await this.readManifest($);return J$(H?.messages_path)}async dispatchHookEvent(f){await g7(f,{queueSpawnRequest:($)=>this.invokeOptional("queueSpawnRequest",$),upsertSubagentSessionFromHook:($)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",$),appendSubagentHookAudit:($,J)=>this.invokeOptional("appendSubagentHookAudit",$,J),applySubagentStatus:($,J)=>this.invokeOptional("applySubagentStatus",$,J)})}subscribe(f,$){return this.events.subscribe(f,$)}async updateSessionModel(f,$){let J=this.getSessionOrThrow(f);J.config.modelId=$,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:$}),J.agent.updateConnection({modelId:$})}handlePluginEvent(f,$,J){return this.eventBridge.handlePluginEvent(f,$,J)}async executeTurn(f,$){let J=await this.prepareTurnInput(f,$),H=J.prompt.trim();if(!H)throw Error("prompt cannot be empty");if(!f.artifacts&&!f.pendingPrompt)f.pendingPrompt=H;await this.ensureSessionPersisted(f),await this.syncOAuthCredentials(f),await this.markTurnRunning(f);let W=await this.executeAgentTurn(f,H,J.userImages,J.userFiles);while(UH(f,W.finishReason)){let Q=await GH(f);if(Q.length===0)break;let Z=hH(f,Q);W=await this.executeAgentTurn(f,Z)}return W}async completeInteractiveTurn(f,$){if(c1(f))return;let J=$==="aborted"||f.aborting,H=$==="error";await this.updateStatus(f,J?"cancelled":H?"failed":"completed",H?1:0),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$,ts:Date.now()}}),f.aborting=!1}async completeAbortedInteractiveTurn(f){let $=new Date,J=f.agent.getMessages();return f.persistedMessages=J,f.started=f.started||J.length>0,await this.completeInteractiveTurn(f,"aborted"),{text:"",usage:c$(),messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:f.config.modelId,provider:f.config.providerId},startedAt:$,endedAt:$,durationMs:0}}async executeAgentTurn(f,$,J,H){let W=f.started||f.agent.getMessages().length>0,Q=f.persistedMessages??f.agent.getMessages(),Z=this.usageBySession.get(f.sessionId)??c$();f.turnUsageBaseline=Z,k4(f.config.telemetry,f.sessionId,f.config.mode),$1(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,model:f.config.modelId,source:"user",mode:f.config.mode,...this.getSessionAgentTelemetryIdentity(f)});try{let j=W?()=>f.agent.continue($,J,H):()=>f.agent.run($,J,H),P=await this.runWithAuthRetry(f,j,Q);f.started=!0;let X=_8(P.messages,P,Q);f.persistedMessages=X;let V=d$(Z,P.usage);return this.usageBySession.set(f.sessionId,V),await this.persistSessionMetadata(f.sessionId,(Y)=>({...Y??{},totalCost:V.totalCost})),await this.invoke("persistSessionMessages",f.sessionId,X,f.config.systemPrompt),this.observeTaskCompletionTool(f,P),P}catch(j){throw await this.invoke("persistSessionMessages",f.sessionId,f.agent.getMessages(),f.config.systemPrompt),j}finally{f.turnUsageBaseline=void 0}}observeTaskCompletionTool(f,$){if(f.submitAndExitObserved)return;if(!$.toolCalls.some((H)=>H.name===$f.SUBMIT_AND_EXIT&&H.error===void 0))return;f.submitAndExitObserved=!0,X2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity(f)})}async prepareTurnInput(f,$){let J=q0(f.config),H=DT($.prompt).trim();if(!H)return{prompt:"",userImages:$.userImages,userFiles:this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles)};let W=await t2(H,J);TZ(f.config.telemetry,W);let Q=d1(W.prompt,f.config.mode),Z=this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles),j=this.resolveAbsoluteFilePaths(J,W.matchedFiles),P=Array.from(new Set([...Z,...j]));return{prompt:Q,userImages:$.userImages,userFiles:P.length>0?P:void 0}}async ensureSessionPersisted(f){if(f.artifacts)return;let $=q0(f.config);f.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:f.sessionId,source:f.source,pid:process.pid,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:$,teamName:f.config.teamName,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,prompt:f.pendingPrompt,metadata:f.sessionMetadata,startedAt:f.startedAt})}async markTurnRunning(f){if(f.status==="running")return;await this.updateStatus(f,"running",null)}async persistSessionMetadata(f,$){let J=this.sessions.get(f),H=await this.invokeOptionalValue("readSessionManifest",f)??J?.artifacts?.manifest,W=$(H?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:f,metadata:W}))?.updated===!1)return;J.sessionMetadata=W,J.artifacts.manifest.metadata=W}async finalizeSingleRun(f,$){if(c1(f))return;let J=$==="aborted"||f.aborting,H=$==="error";await this.shutdownSession(f,{status:J?"cancelled":H?"failed":"completed",exitCode:H?1:0,shutdownReason:H?"session_error":"session_complete",endReason:$})}async failSession(f){await this.shutdownSession(f,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession(f,$){if($.status==="completed"&&!f.submitAndExitObserved)X2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity(f)});x8(f);let J=[],H=(W,Q)=>{J.push(Q),f.config.logger?.log("Session shutdown cleanup failed",{sessionId:f.sessionId,stage:W,error:Q,severity:"warn"})};if(f.artifacts){try{await this.updateStatus(f,$.status,$.exitCode)}catch(W){H("update_status",W)}try{await f.agent.shutdown($.shutdownReason)}catch(W){H("agent_shutdown",W)}}try{await Promise.resolve(f.runtime.shutdown($.shutdownReason))}catch(W){H("runtime_shutdown",W)}try{await f.pluginSandboxShutdown?.()}catch(W){H("plugin_sandbox_shutdown",W)}if(this.sessions.delete(f.sessionId),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$.endReason,ts:Date.now()}}),J.length>0&&$.status==="failed")throw J[0]}async releaseSessionRuntime(f,$){let J=[],H=(W,Q)=>{J.push(Q),f.config.logger?.log("Session runtime cleanup failed",{sessionId:f.sessionId,stage:W,error:Q,severity:"warn"})};try{await f.agent.shutdown($)}catch(W){H("agent_shutdown",W)}try{await Promise.resolve(f.runtime.shutdown($))}catch(W){H("runtime_shutdown",W)}try{await f.pluginSandboxShutdown?.()}catch(W){H("plugin_sandbox_shutdown",W)}if(this.sessions.delete(f.sessionId),J.length>0)throw J[0]}async updateStatus(f,$,J){if(!f.artifacts)return;let H=await this.invoke("updateSessionStatus",f.sessionId,$,J);if(!H.updated)return;let W=await this.invokeOptionalValue("readSessionManifest",f.sessionId)??f.artifacts.manifest;if(W.status=$,$==="running")delete W.ended_at,W.exit_code=null;else W.ended_at=H.endedAt??n(),W.exit_code=typeof J==="number"?J:null;f.artifacts.manifest=W,f.status=$,f.updatedAt=H.endedAt??n(),f.endedAt=$==="running"?null:W.ended_at,f.exitCode=W.exit_code,await this.invoke("writeSessionManifest",f.artifacts.manifestPath,W),this.emitStatus(f.sessionId,$)}async runWithAuthRetry(f,$,J){try{return await $()}catch(H){if(!TT(H,f.config.providerId))throw H;return await this.syncOAuthCredentials(f,{forceRefresh:!0}),f.agent.restore(J),$()}}async syncOAuthCredentials(f,$){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:f.config.providerId,forceRefresh:$?.forceRefresh})}catch(H){if(H instanceof Z4)throw Error(`${H.providerId} requires re-authentication.`);throw H}if(!J?.apiKey||f.config.apiKey===J.apiKey)return;f.config.apiKey=J.apiKey,f.agent.updateConnection({apiKey:J.apiKey}),f.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),f.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow(f){let $=this.sessions.get(f);if(!$)throw Error(`session not found: ${f}`);return $}resolveAbsoluteFilePaths(f,$){if(!$||$.length===0)return[];let J=$.map((H)=>H.trim()).filter((H)=>H.length>0).map((H)=>UT(H)?H:GT(f,H));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity(f){return Q0({agentId:f.agent.getAgentId(),conversationId:f.agent.getConversationId(),teamId:f.runtime.teamRuntime?.getTeamId(),teamName:f.runtime.teamRuntime?.getTeamName(),teamRole:f.runtime.teamRuntime?"lead":void 0})}emitStatus(f,$){this.emitSessionSnapshot(f),this.emit({type:"status",payload:{sessionId:f,status:$}})}async emitSessionSnapshot(f){let $=await this.getSession(f);if(!$)return;this.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:z0({session:$,messages:await this.readSessionMessages(f),usage:this.usageBySession.get(f)})}})}emit(f){this.events.emit(f)}async listRows(f){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor(f)),Rj))}async getRow(f){let $=f.trim();if(!$)return;return(await this.listRows(Rj)).find((H)=>H.sessionId===$)}async readManifest(f){let $=f.trim();if(!$)return;return await this.invokeOptionalValue("readSessionManifest",$)}invoke(f,...$){return Vj(this.sessionService,f,...$)}invokeOptional(f,...$){return Yj(this.sessionService,f,...$)}invokeOptionalValue(f,...$){return Bj(this.sessionService,f,...$)}}function _T(f){if(f.backendMode)return f.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let $=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if($==="local"||$==="hub"||$==="remote")return $;return"auto"}var e1,f2;function LT(f,$){if(f!=="auto"&&f!=="hub")return;if($.hub?.endpoint?.trim())return;HQ($.hub?.workspaceRoot?.trim()||$.hub?.cwd?.trim()||process.cwd())}async function zT(f){await f.reconcileDeadSessions?.().catch(()=>{})}function yj(f){try{let $=new O0;return $.init(),new N0($,{messagesArtifactUploader:f.messagesArtifactUploader})}catch{return f.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new _H(void 0,{messagesArtifactUploader:f.messagesArtifactUploader})}}function Fj(f,$,J){return new E0({sessionService:J??f.sessionService??yj(f),capabilities:f.capabilities,telemetry:f.telemetry,toolPolicies:f.toolPolicies,distinctId:$,fetch:f.fetch})}async function OT(f){if(e1)return e1;if(f2)return await f2;return f2=(async()=>{return e1=yj(f),await zT(e1),e1})().finally(()=>{f2=void 0}),await f2}async function P4(f){let $=j$(f.distinctId);f.telemetry?.setDistinctId($);let J=_T(f);if(LT(J,f),J==="remote"){let H=f.remote?.endpoint?.trim();if(!H)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return f.logger?.log("Using remote runtime host",{endpoint:H}),new b8({endpoint:H,authToken:f.remote?.authToken,clientType:f.remote?.clientType,displayName:f.remote?.displayName,workspaceRoot:f.remote?.workspaceRoot,cwd:f.remote?.cwd,capabilities:f.capabilities})}if(J==="hub"){let H=f.hub?.endpoint?.trim(),W=H||await m1({strategy:f.hub?.strategy??"require-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(!W)throw Error("No compatible hub runtime is available.");return f.logger?.log("Using hub runtime host",{url:W,explicitEndpoint:H||void 0}),new Z$({url:W,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd})}if(J==="auto"){let H=await QH({endpoint:f.hub?.endpoint,strategy:f.hub?.strategy??"prefer-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(H){f.logger?.log("Using discovered local hub runtime host",{url:H});let W=new Z$({url:H,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});try{return await W.connect(),W}catch(Q){f.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:Q})}}return f.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),Fj(f,$)}return Fj(f,$)}class yW{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor(f,$,J,H,W,Q,Z,j,P){this.clientName=$,this.runtimeAddress=J,this.host=f,this.prepare=H,this.capabilities=W,this.logger=Q,this.telemetry=Z,this.distinctId=j,this.settings=Z7(f),this.pendingPrompts=j7(f),this.automation=new F6(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=P?new N1({workspaceRoot:P.workspaceRoot??process.cwd(),specs:{cronSpecsDir:P.cronSpecsDir??P.cronDir,scope:c5(P.cronScope),workspaceRoot:P.workspaceRoot},runtimeHandlers:d5({host:f,getExtensionContext:()=>q2({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:P.dbPath,logger:P.logger,pollIntervalMs:P.pollIntervalMs,claimLeaseSeconds:P.claimLeaseSeconds,globalMaxConcurrency:P.globalMaxConcurrency,watcherDebounceMs:P.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((X)=>{if(X.type!=="ended")return;this.disposeSessionBootstrap(X.payload.sessionId)})}static async create(f={}){let $=Vf(f.capabilities),J=await P4({...f,capabilities:$}),H=u5(f.automation),W=new yW(J,f.clientName,J.runtimeAddress,f.prepare,$,f.logger,f.telemetry,f.distinctId,H?{...H,logger:f.logger}:void 0);if(H&&H.autoStart!==!1)await W.automation.start();return W}async disposeSessionBootstrap(f){let $=this.activeSessionBootstraps.get(f);if(!$)return;this.activeSessionBootstraps.delete(f),await Promise.resolve($.dispose?.())}async start(f){let $=P7(f),J=await this.prepare?.($);try{let H=J?await J.applyToStartSessionInput($):$,W=await this.host.startSession(UJ(H,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>q2({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(W.sessionId))this.activeSessionBootstraps.set(W.sessionId,J);else await Promise.resolve(J.dispose?.());return X7({input:H,sessionId:W.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),W}catch(H){throw await Promise.resolve(J?.dispose?.()),H}}send=(...f)=>this.host.runTurn(...f);getAccumulatedUsage=(...f)=>{return this.host.getAccumulatedUsage?.(...f)??Promise.resolve(void 0)};abort=(...f)=>this.host.abort(...f);stop=async(f)=>{await this.host.stopSession(f),await this.disposeSessionBootstrap(f)};dispose=async(...f)=>{try{await this.automationService?.dispose(),await this.host.dispose(...f)}finally{this.unsubscribeBootstrapCleanup();let $=[...this.activeSessionBootstraps.keys()];await Promise.allSettled($.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...f)=>this.host.getSession(...f);listHistory=async(f={})=>await aJ(this.host,f);list=async(f=200,$={})=>await this.listHistory({...$,limit:f});delete=async(f)=>{let $=await this.host.deleteSession(f);if($)await this.disposeSessionBootstrap(f);return $};update=(...f)=>this.host.updateSession(...f);readMessages=(...f)=>this.host.readSessionMessages(...f);async restore(f){let $=f.start?UJ(f.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>q2({automationService:this.automationService,automation:this.automation,context:J,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:f.sessionId,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restore:f.restore,start:$})}ingestHookEvent=(...f)=>this.host.dispatchHookEvent(...f);subscribe(f,$){return this.host.subscribe(f,$)}updateSessionModel=(...f)=>{return this.host.updateSessionModel?.(...f)??Promise.resolve()}}import{HookEventNameSchema as Uj,HookEventPayloadSchema as Gj,parseHookEventPayload as V4,resolveHookSessionContext as ST}from"@cline/shared";import{z as A$}from"zod";import{spawn as NT}from"node:child_process";import{augmentNodeCommandForDebug as qT,withResolvedClineBuildEnv as bT}from"@cline/shared";function wT(f){let $=f.trim();if(!$)return{};let H=$.split(`
|
|
694
|
-
`).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),W=H.length>0?H[H.length-1]:$;try{return{parsedJson:JSON.parse(W)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse subprocess stdout JSON"}}}function CT(f,$){let J=f instanceof Error?f:Error(String(f)),H=J,W=$.join(" ");if(H.code==="EACCES")return Error(`Failed to execute hook command "${W}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${W}": ${J.message}`)}async function ET(f,$){let J=f.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((H,W)=>{let Q=(Z)=>{J.off("error",Q);let j=Z.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){H();return}W(Z)};J.once("error",Q),J.end($,(Z)=>{if(J.off("error",Q),Z){let j=Z.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){H();return}W(Z);return}H()})})}async function X4(f,$){let J=qT($.command,{env:$.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let H=!!$.detached,W=NT(J[0],J.slice(1),{cwd:$.cwd,env:bT($.env),stdio:H?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:H}),Q=new Promise((B)=>{W.once("spawn",()=>{try{$.onSpawn?.({command:J,pid:W.pid??void 0,detached:H})}catch{}B()})}),Z=new Promise((B,A)=>{W.once("error",(R)=>{A(CT(R,J))})});if(await ET(W,JSON.stringify(f)),H){await Promise.race([Q,Z]),W.unref();return}if(!W.stdout||!W.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let j="",P="",X=!1,V;W.stdout.on("data",(B)=>{j+=B.toString()}),W.stderr.on("data",(B)=>{P+=B.toString()});let Y=new Promise((B)=>{if(($.timeoutMs??0)>0)V=setTimeout(()=>{X=!0,W.kill("SIGKILL")},$.timeoutMs);W.once("close",(A)=>{if(V)clearTimeout(V);let{parsedJson:R,parseError:U}=wT(j);B({exitCode:A,stdout:j,stderr:P,parsedJson:R,parseError:U,timedOut:X})})});return await Promise.race([Y,Z])}var kT=A$.object({contextModification:A$.string().optional(),cancel:A$.boolean().optional(),review:A$.boolean().optional(),errorMessage:A$.string().optional(),context:A$.string().optional(),overrideInput:A$.unknown().optional()}).passthrough();var mT=["agent","hook"];async function Y4(f,$={}){let J=$.command??mT;return await X4(f,{command:J,cwd:$.cwd,env:$.env,detached:$.detached,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn})}function hj(f){return f instanceof Error?f:Error(String(f))}function IT(f){if(!f||typeof f!=="object")return;let $=kT.safeParse(f);if(!$.success)return;let J=$.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let W=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:W,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function Kj(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,H]of Object.entries(f))if(typeof H==="string")$[J]=H;else $[J]=JSON.stringify(H);return $}function Z0(f,$,J){let H=J.env??process.env,W=H.CLINE_USER_ID?.trim()||H.USER?.trim()||"unknown",Q=J.cwd||process.cwd();return{clineVersion:H.CLINE_VERSION?.trim()||"",hookName:f,timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:ST(J.sessionContext,{hookName:f,conversationId:$.conversationId,agentId:$.agentId,parentAgentId:$.parentAgentId}),workspaceRoots:Q?[Q]:[],workspaceInfo:J.workspaceInfo,userId:W,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function xT(f){return{name:f.name,message:f.message,stack:f.stack}}function gT(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function vT(f){return{agentId:f.snapshot.agentId,conversationId:f.snapshot.conversationId??f.snapshot.runId??f.snapshot.agentId,parentAgentId:f.snapshot.parentAgentId??null}}function uT(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function cT(f){return{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}function dT(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}async function R$(f,$){try{let J=await Y4(f,{command:$.command,cwd:$.cwd,env:$.env,detached:!0,onSpawn:$.onSpawn});$.onDispatch?.({payload:f,result:J,detached:!0})}catch(J){$.onDispatchError?.(hj(J),f)}}function Tj(f={}){return{hooks:{beforeRun:async(j)=>{let P=vT(j);if((f.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let V={...Z0("agent_resume",P,f),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await R$(V,f)}else{let V={...Z0("agent_start",P,f),hookName:"agent_start",taskStart:{taskMetadata:{}}};await R$(V,f)}return},beforeTool:async(j)=>{let P={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},X={...Z0("tool_call",P,f),hookName:"tool_call",iteration:j.snapshot.iteration,tool_call:{id:j.toolCall.toolCallId,name:j.toolCall.toolName,input:j.input},preToolUse:{toolName:j.toolCall.toolName,parameters:Kj(j.input)}};try{let V=await Y4(X,{command:f.command,cwd:f.cwd,env:f.env,detached:!1,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn});if(f.onDispatch?.({payload:X,result:V,detached:!1}),V?.timedOut)throw Error("tool_call hook command timed out");if(V?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${V.parseError}`);return dT(IT(V?.parsedJson))}catch(V){f.onDispatchError?.(hj(V),X);return}},afterTool:async(j)=>{let P=cT(j),X={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},V={...Z0("tool_result",X,f),hookName:"tool_result",iteration:j.snapshot.iteration,tool_result:P,postToolUse:{toolName:P.name,parameters:Kj(P.input),result:typeof P.output==="string"?P.output:JSON.stringify(P.output),success:!P.error,executionTimeMs:P.durationMs}};await R$(V,f);return},afterRun:async({snapshot:j,result:P})=>{let X={agentId:j.agentId,conversationId:j.conversationId??j.runId??j.agentId,parentAgentId:j.parentAgentId??null};if(P.status==="completed"){let B={...Z0("agent_end",X,f),hookName:"agent_end",iteration:P.iterations,turn:{outputText:P.outputText,status:P.status},taskComplete:{taskMetadata:{}}};await R$(B,f);return}let V=P.status==="aborted"||gT(P.error?.message)?"agent_abort":"agent_error",Y=V==="agent_error"?{...Z0(V,X,f),hookName:V,iteration:P.iterations,error:xT(P.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...Z0(V,X,f),hookName:V,reason:P.error?.message,taskCancel:{taskMetadata:{}}};await R$(Y,f)},onEvent:async(j)=>{if(j.type!=="message-added"||j.message.role!=="user")return;let P={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},X={...Z0("prompt_submit",P,f),hookName:"prompt_submit",userPromptSubmit:{prompt:uT(j.message.content),attachments:[]}};await R$(X,f)}},shutdown:async({agentId:j,conversationId:P,parentAgentId:X,reason:V})=>{let Y={...Z0("session_shutdown",{agentId:j,conversationId:P,parentAgentId:X},f),hookName:"session_shutdown",reason:V};await R$(Y,f)}}}import{createSessionId as rT}from"@cline/shared";function qf(f,$){return{version:f.version,requestId:f.requestId,ok:!0,payload:$}}function Dj(f,$,J){return{version:f.version,requestId:f.requestId??rT("hubreq_"),ok:!1,error:{code:$,message:J}}}class B4{schedules;constructor(f){this.schedules=f}async handleCommand(f){try{switch(f.command){case"schedule.create":return qf(f,{schedule:this.schedules.createSchedule(this.toCreateInput(f.payload??{}))});case"schedule.list":return qf(f,{schedules:this.schedules.listSchedules({enabled:typeof f.payload?.enabled==="boolean"?f.payload.enabled:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0,tags:Array.isArray(f.payload?.tags)?f.payload?.tags:void 0})});case"schedule.get":return qf(f,{schedule:this.schedules.getSchedule(String(f.payload?.scheduleId??""))});case"schedule.update":return qf(f,{schedule:this.schedules.updateSchedule(String(f.payload?.scheduleId??""),this.toUpdateInput(f.payload??{}))});case"schedule.delete":return qf(f,{deleted:this.schedules.deleteSchedule(String(f.payload?.scheduleId??""))});case"schedule.enable":return qf(f,{schedule:this.schedules.resumeSchedule(String(f.payload?.scheduleId??""))});case"schedule.disable":return qf(f,{schedule:this.schedules.pauseSchedule(String(f.payload?.scheduleId??""))});case"schedule.trigger":return qf(f,{execution:await this.schedules.triggerScheduleNow(String(f.payload?.scheduleId??""))});case"schedule.list_executions":return qf(f,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof f.payload?.scheduleId==="string"?f.payload.scheduleId:void 0,status:typeof f.payload?.status==="string"?f.payload.status:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0})});case"schedule.stats":return qf(f,{stats:this.schedules.getScheduleStats(String(f.payload?.scheduleId??""))});case"schedule.active":return qf(f,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return qf(f,{runs:this.schedules.getUpcomingRuns(typeof f.payload?.limit==="number"?f.payload.limit:void 0)});default:return Dj(f,"unsupported_command",`Unsupported hub schedule command: ${f.command}`)}}catch($){return Dj(f,"schedule_command_failed",$ instanceof Error?$.message:String($))}}toCreateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider&&f.model?{providerId:String(f.provider),modelId:String(f.model)}:void 0;return{...f,modelSelection:$}}toUpdateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider||f.model?{providerId:typeof f.provider==="string"?f.provider:"",modelId:typeof f.model==="string"?f.model:""}:void 0;return{...f,modelSelection:$}}}function R4(f){return f?new Date(f).getTime():void 0}function lT(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function A4(f){let $=f.metadata;return{scheduleId:f.externalId,name:f.title,cronPattern:f.scheduleExpr??"",prompt:f.prompt??"",workspaceRoot:f.workspaceRoot??"",cwd:typeof $?.__hubScheduleCwd==="string"?$.__hubScheduleCwd:void 0,modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:f.enabled&&!f.removed&&f.parseStatus==="valid",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,maxParallel:f.maxParallel??1,createdAt:new Date(f.createdAt).getTime(),updatedAt:new Date(f.updatedAt).getTime(),nextRunAt:R4(f.nextRunAt),lastRunAt:R4(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:lT(f)}}function pT(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function Mj(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:R4(f.startedAt),endedAt:R4(f.completedAt),status:pT(f.status),errorMessage:f.error}}class F4{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new O1({dbPath:f.dbPath}),this.materializer=new D1({store:this.store}),this.runner=new M1({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:"",logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule(f){if(qJ(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return A4(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?A4($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>A4($))}updateSchedule(f,$){if($.cronPattern!==void 0)qJ($.cronPattern);let J=this.store.getHubSchedule(f);if(!J)return;let H=$.workspaceRoot!==void 0?$.workspaceRoot.trim():J.workspaceRoot;if(($.enabled??J.enabled)&&!H)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule(f,{...$,scheduleId:f});return Q?A4(Q):void 0}deleteSchedule(f){return this.store.deleteHubSchedule(f)}pauseSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!1})}resumeSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!0})}async triggerScheduleNow(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;await this.runner.tick();let J=this.store.getRun($.runId)??$;return Mj(J,f)}listScheduleExecutions(f){let $=f.scheduleId?this.store.getHubSchedule(f.scheduleId):void 0,J={specId:$?.specId,limit:f.limit};return this.store.listRuns(J).map((W)=>{let Q=$??this.store.getSpec(W.specId);if(!Q||Q.source!=="hub-schedule")return;return Mj(W,Q.externalId)}).filter((W)=>{if(!W)return!1;return!f.status||W.status===f.status})}getScheduleStats(f){let $=this.listScheduleExecutions({scheduleId:f,limit:1e4});if($.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,H=0,W=0,Q;for(let Z of $){if(Z.status==="success"||Z.status==="completed")J+=1;if(!Q&&Z.status!=="success"&&Z.status!=="completed")Q=Z;if(Z.startedAt&&Z.endedAt)W+=Z.endedAt-Z.startedAt,H+=1}return{totalRuns:$.length,successRate:J/$.length,avgDurationSeconds:H>0?W/H/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((f)=>{let $=this.store.getSpec(f.specId);if(!$||$.source!=="hub-schedule"||!f.sessionId)return[];return[{executionId:f.runId,scheduleId:$.externalId,sessionId:f.sessionId,startedAt:f.startedAt??new Date().toISOString(),timeoutAt:$.timeoutSeconds&&f.startedAt?new Date(new Date(f.startedAt).getTime()+$.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(f=20){let $={triggerKind:"schedule",enabled:!0,limit:f};return this.store.listSpecs($).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,H)=>String(J.nextRunAt).localeCompare(String(H.nextRunAt))).slice(0,f).map(({spec:J,nextRunAt:H})=>({scheduleId:J.externalId,name:J.title,nextRunAt:H}))}}G4();function FD(f,$){if(f instanceof Error)return f;if(f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"&&f.message.trim())return Error(f.message.trim());let J=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return Error(J?`Failed to connect to hub at ${$} (${J} event before socket open).`:`Failed to connect to hub at ${$}.`)}var yD="cline-hub-auth.";function KD(f){return f.host!==void 0||f.port!==void 0||f.pathname!==void 0}function UD(f,$){let J=new URL(f),H=new URL($);return J.search="",J.hash="",H.search="",H.hash="",J.toString()===H.toString()}async function GD(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=Bf(),H=await Zf(J.discoveryPath);if(H?.url&&UD(f.toString(),H.url))return H.authToken;return}async function hD(f={}){let $=_0(f);if(!KD(f)){let J=Bf(),H=await Zf(J.discoveryPath);if(H?.url)return H.url}return $0($.host,$.port,$.pathname)}async function zj(f){return await new Promise(($,J)=>{(async()=>{let H=new URL(f),W=await GD(H);H.hash="";let Q=new WebSocket(H.toString(),W?[`${yD}${W}`]:void 0),Z=new Map,j=0;Q.addEventListener("open",()=>{$({send(P){let X=P.requestId??`hub-client-${++j}`;return new Promise((V,Y)=>{Z.set(X,{resolve:V,reject:Y});let B={kind:"command",envelope:{...P,requestId:X}};Q.send(JSON.stringify(B))})},close(){Q.close()}})}),Q.addEventListener("message",(P)=>{let X=JSON.parse(String(P.data));if(X.kind==="reply"&&X.envelope.requestId){let V=Z.get(X.envelope.requestId);if(V)Z.delete(X.envelope.requestId),V.resolve(X.envelope)}}),Q.addEventListener("close",()=>{for(let P of Z.values())P.reject(Error("Hub connection closed"));Z.clear()}),Q.addEventListener("error",(P)=>{J(FD(P,f))})})().catch(J)})}async function JI(f){try{return(await zj(f)).close(),!0}catch{return!1}}async function HI(f,$){let J=await hD(f),H=await zj(J);try{return await H.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{H.close()}}function nf(f){return f?JSON.parse(JSON.stringify(f)):{}}function h4(f){let $=f?.session&&typeof f.session==="object"?f.session:void 0;if(!$)return;let J=$.metadata&&typeof $.metadata==="object"?nf($.metadata):void 0;return{sessionId:typeof $.sessionId==="string"?$.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function Oj(f,$){return f.error?.message??`hub command failed: ${$}`}function TD(f){let $=nf(f);if(typeof $.error==="string"&&$.error.trim())return{...$,error:$.error.trim()};let J=$.result&&typeof $.result==="object"?$.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...$,error:J.text.trim()};let H=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof H?.message==="string"&&H.message.trim())return{...$,error:H.message.trim()};return $}function DD(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))throw Error("hub checkpoint restore returned no checkpoint");let J=$;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function MD(f){let $=f.sessionId?.trim();if(!$)return;switch(f.event){case"iteration.started":return{sessionId:$,eventType:"runtime.chat.iteration_start",payload:nf(f.payload)};case"iteration.finished":return{sessionId:$,eventType:"runtime.chat.iteration_end",payload:nf(f.payload)};case"assistant.delta":return{sessionId:$,eventType:"runtime.chat.text_delta",payload:nf(f.payload)};case"tool.started":return{sessionId:$,eventType:"runtime.chat.tool_call_start",payload:nf(f.payload)};case"tool.finished":return{sessionId:$,eventType:"runtime.chat.tool_call_end",payload:nf(f.payload)};case"approval.requested":return{sessionId:$,eventType:"approval.requested",payload:nf(f.payload)};case"run.aborted":return{sessionId:$,eventType:"runtime.chat.aborted",payload:nf(f.payload)};case"run.failed":return{sessionId:$,eventType:"runtime.chat.failed",payload:TD(f.payload)};case"run.completed":return{sessionId:$,eventType:"runtime.chat.completed",payload:nf(f.payload)};default:return}}class _D{options;client;metadataApplied=!1;constructor(f){this.options=f;this.client=new J0({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-session-client",displayName:f.displayName??"hub session client",workspaceRoot:f.workspaceRoot,cwd:f.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.create",{workspaceRoot:f.workspaceRoot,cwd:f.cwd,sessionConfig:{providerId:f.provider,modelId:f.model,apiKey:f.apiKey,cwd:f.cwd??f.workspaceRoot,workspaceRoot:f.workspaceRoot,systemPrompt:f.systemPrompt??"",mode:f.mode??"act",rules:f.rules,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawnAgent:f.enableSpawn!==!1,enableAgentTeams:f.enableTeams!==!1,disableMcpSettingsTools:f.disableMcpSettingsTools,missionLogIntervalSteps:f.missionStepInterval,missionLogIntervalMs:f.missionTimeIntervalMs},metadata:{source:f.source??"cli",provider:f.provider,model:f.model,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,prompt:void 0,interactive:f.interactive!==!1},runtimeOptions:{mode:f.mode,systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,autoApproveTools:f.autoApproveTools,toolExecutors:f.toolExecutors,configExtensions:f.configExtensions},modelSelection:{provider:f.provider,model:f.model,apiKey:f.apiKey},toolPolicies:f.toolPolicies}),J=h4($.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession(f,$,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:$.prompt,attachments:$.attachments,delivery:$.delivery,timeoutSeconds:$.config.timeoutSeconds},f,J)).payload?.result}}async stopRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:f},f),{applied:!0}}async abortRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:f},f),{applied:!0}}async updateSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:f.sessionId,metadata:f.metadata},f.sessionId),{updated:!0}}async getSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.get",void 0,f);return h4($.payload)}async readMessages(f){let $=f.trim();if(!$)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(Oj(J,"session.messages"));let H=J.payload?.messages;return Array.isArray(H)?H:[]}async restore(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let H=f.config,W=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...H?{workspaceRoot:H.workspaceRoot,cwd:H.cwd,sessionConfig:{providerId:H.provider,modelId:H.model,apiKey:H.apiKey,cwd:H.cwd??H.workspaceRoot,workspaceRoot:H.workspaceRoot,systemPrompt:H.systemPrompt??"",mode:H.mode??"act",rules:H.rules,maxIterations:H.maxIterations,enableTools:H.enableTools,enableSpawnAgent:H.enableSpawn!==!1,enableAgentTeams:H.enableTeams!==!1,disableMcpSettingsTools:H.disableMcpSettingsTools,missionLogIntervalSteps:H.missionStepInterval,missionLogIntervalMs:H.missionTimeIntervalMs},metadata:{source:H.source??"cli",provider:H.provider,model:H.model,enableTools:H.enableTools,enableSpawn:H.enableSpawn,enableTeams:H.enableTeams,prompt:void 0,interactive:H.interactive!==!1},runtimeOptions:{mode:H.mode,systemPrompt:H.systemPrompt,maxIterations:H.maxIterations,enableTools:H.enableTools,enableSpawn:H.enableSpawn,enableTeams:H.enableTeams,autoApproveTools:H.autoApproveTools,configExtensions:H.configExtensions},modelSelection:{provider:H.provider,model:H.model,apiKey:H.apiKey},toolPolicies:H.toolPolicies}:{}},$);if(!W.ok)throw Error(Oj(W,"session.restore"));let Q=h4(W.payload);if(J&&!Q?.sessionId)throw Error("hub checkpoint restore returned no session id");let Z=Array.isArray(W.payload?.messages)?W.payload.messages:void 0,j=DD(W.payload);return{sessionId:Q?.sessionId,startResult:Q?.sessionId?{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}:void 0,...Z?{messages:Z}:{},checkpoint:j}}async listSessions(f){await this.ensureMetadataApplied();let $=await this.client.command("session.list",{limit:f?.limit??200});return(Array.isArray($.payload?.sessions)?$.payload?.sessions:[]).map((H)=>h4({session:H})).filter((H)=>Boolean(H?.sessionId))}async deleteSession(f,$=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:f,deleteCheckpointRefs:$})).payload?.deleted===!0}async respondToolApproval(f){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:f.approvalId,approved:f.approved,payload:f.reason?{reason:f.reason}:void 0,responderClientId:f.responderClientId})}streamEvents(f,$){let J=new Set((f.sessionIds??[]).map((W)=>W.trim()).filter(Boolean)),H=this.client.subscribe((W)=>{let Q=MD(W);if(!Q)return;if(J.size>0&&!J.has(Q.sessionId))return;$.onEvent?.(Q)});return this.ensureMetadataApplied().catch((W)=>{$.onError?.(W instanceof Error?W:Error(String(W)))}),H}streamTeamProgress(f,$){let J=this.client.subscribe((H)=>{if(H.event!=="team.progress"||!H.payload)return;$.onProjection?.(H.payload)});return this.ensureMetadataApplied().catch((H)=>{$.onError?.(H instanceof Error?H:Error(String(H)))}),J}async createSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",f)).payload?.schedule}async listSchedules(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.list");return Array.isArray($.payload?.schedules)?$.payload?.schedules:[]}async getSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:f})).payload?.schedule}async updateSchedule(f,$){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:f,...$})).payload?.schedule}async pauseSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:f})).payload?.schedule}async resumeSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:f})).payload?.schedule}async deleteSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:f})).payload?.deleted===!0}async triggerScheduleNow(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:f})).payload?.execution}async listScheduleExecutions(f,$){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:f,limit:$});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let f=await this.client.command("schedule.active");return Array.isArray(f.payload?.executions)?f.payload?.executions:[]}async getUpcomingScheduledRuns(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.upcoming",{limit:f});return Array.isArray($.payload?.upcoming)?$.payload?.upcoming:[]}}class LD{client;constructor(f){this.client=new J0({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-ui-client",displayName:f.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify(f){await this.client.command("ui.notify",f)}async sendShowWindow(f){await this.client.command("ui.show_window",f??{})}async listClients(){let f=await this.client.command("client.list");return Array.isArray(f.payload?.clients)?f.payload.clients:[]}async listSessions(f=200){let $=await this.client.command("session.list",{limit:f});return Array.isArray($.payload?.sessions)?$.payload.sessions:[]}subscribeUI(f){return this.client.subscribe(($)=>{switch($.event){case"ui.notify":f.onNotify?.($.payload);break;case"ui.show_window":f.onShowWindow?.($.payload);break;case"hub.client.registered":f.onClientRegistered?.($.payload??{});break;case"hub.client.disconnected":f.onClientDisconnected?.($.payload??{});break;case"session.created":f.onSessionCreated?.($.payload??{});break;case"session.updated":f.onSessionUpdated?.($.payload??{});break;case"session.detached":f.onSessionDetached?.($.payload??{});break}})}}import{normalizeProviderId as zD}from"@cline/llms";function OD(f){return{text:f.text,usage:f.usage,inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function ND(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}function RI(f={}){let $=new E0({sessionService:new N0(new O0),fetch:f.fetch,telemetry:f.telemetry});return{async startSession(J){let H=(J.cwd?.trim()||J.workspaceRoot).trim(),W=await $.startSession({source:J.source?.trim()||Pf.CLI,interactive:!1,config:{providerId:zD(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:H,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:ND(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(J,H){let W=await $.runTurn({sessionId:J,prompt:H.prompt,userImages:H.attachments?.userImages,userFiles:H.attachments?.userFiles?.map((Q)=>Q.content)});if(!W)throw Error("local hub schedule runtime returned no turn result");return{result:OD(W)}},async abortSession(J){return await $.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function qD(f){if(typeof f==="string")return f.trim()||void 0;if(!Array.isArray(f))return;return f.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
|
|
695
|
-
`).trim()||void 0}var Nj=120,hW="...";function TW(f){let $=f.trim();if(!$)return"";if(Buffer.byteLength($,"utf8")<=Nj)return $;let J=Nj-Buffer.byteLength(hW,"utf8");if(J<=0)return hW;let H="";for(let W of $){if(Buffer.byteLength(H+W,"utf8")>J)break;H+=W}return`${H}${hW}`}async function qj(f){let $=f?.sessionId?.trim()||"unknown",J=typeof f?.metadata?.messagesPath==="string"?f.metadata.messagesPath:void 0,W=[...await J$(J)].reverse().find((P)=>P.role==="assistant"),Q=W?qD(W.content):void 0,Z=f?.workspaceRoot?.trim()||"workspace",j=typeof f?.metadata?.prompt==="string"?f.metadata.prompt.trim():Z;return{title:`Task completed (${$})`,body:TW(Q&&Q.length>0?Q:j.length>0?j:Z),severity:"info"}}import{createSessionId as HM}from"@cline/shared";import{createSessionId as ED}from"@cline/shared";import{createSessionId as CD}from"@cline/shared";function bD(f){switch(f){case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function wD(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):{};if(f.parentSessionId?.trim())$.parentSessionId=f.parentSessionId;if(f.parentAgentId?.trim())$.parentAgentId=f.parentAgentId;if(f.agentId?.trim())$.agentId=f.agentId;if(f.conversationId?.trim())$.conversationId=f.conversationId;if(f.messagesPath?.trim())$.messagesPath=f.messagesPath;if(f.prompt?.trim())$.prompt=f.prompt;if(f.provider?.trim())$.provider=f.provider;if(f.model?.trim())$.model=f.model;if(f.source?.trim())$.source=f.source;if(typeof f.pid==="number")$.pid=f.pid;return Object.keys($).length>0?$:void 0}function T4(f,$){return{sessionId:f.sessionId,workspaceRoot:f.workspaceRoot,cwd:f.cwd,createdAt:Date.parse(f.startedAt),updatedAt:Date.parse(f.updatedAt),createdByClientId:$?.createdByClientId??"hub",status:bD(f.status),participants:$?[...$.participants.values()]:[],metadata:wD(f),runtimeOptions:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,mode:typeof f.metadata?.mode==="string"?f.metadata.mode:void 0,systemPrompt:typeof f.metadata?.systemPrompt==="string"?f.metadata.systemPrompt:void 0},runtimeSession:f.agentId?{agentId:f.agentId,team:f.teamName?{teamId:f.teamName}:void 0}:void 0}}function m(f,$){return{version:f.version,requestId:f.requestId,ok:!0,...$!==void 0?{payload:$}:{}}}function E(f,$,J){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:$,message:J}}}function D4(f){return f&&typeof f==="object"&&!Array.isArray(f)?f:void 0}function Uf(f){if(typeof f.payload?.sessionId==="string")return f.payload.sessionId.trim();return f.sessionId?.trim()??""}function F$(f,$,J){return{version:"v1",event:f,eventId:CD("hevt_"),sessionId:J,timestamp:Date.now(),payload:$}}async function bf(f,$){let J=await f.sessionHost.getSession($);if(!J)return;return T4(J,f.sessionState.get($))}async function wf(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let[H,W]=await Promise.all([typeof f.sessionHost.readSessionMessages==="function"?f.sessionHost.readSessionMessages($):[],f.sessionHost.getAccumulatedUsage?.($)]);return z0({session:J,messages:H,usage:W})}function M4(f,$,J,H,W={}){let Q=f.sessionState.get($);if(Q){if(W.interactive!==void 0)Q.interactive=W.interactive;if(!Q.participants.has(J))Q.participants.set(J,{clientId:J,attachedAt:Date.now(),role:H});return Q}let Z={createdByClientId:J,interactive:W.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:H}]])};return f.sessionState.set($,Z),Z}async function DW(f,$){let J=ED("approval_"),H=$.sessionId;if(f.sessionState.get(H)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((Q)=>{f.pendingApprovals.set(J,{sessionId:H,resolve:Q}),f.publish(f.buildEvent("approval.requested",{approvalId:J,sessionId:$.sessionId,agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:JSON.stringify($.input??null),policy:$.policy},H))})}function MW(f,$,J){let H=f.pendingApprovals.get($);if(!H)return;return f.pendingApprovals.delete($),H.resolve(J),{sessionId:H.sessionId}}function _W(f,$,J){let H=0;for(let[W,Q]of[...f.pendingApprovals.entries()]){if(!$({approvalId:W,sessionId:Q.sessionId}))continue;f.pendingApprovals.delete(W),Q.resolve({approved:!1,reason:J}),f.publish(f.buildEvent("approval.resolved",{approvalId:W,approved:!1,cancelled:!0,reason:J},Q.sessionId)),H+=1}return H}async function bj(f,$){let J=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"";if(!f.pendingApprovals.get(J))return E($,"approval_not_found",`Unknown approval: ${J}`);let W=typeof $.payload?.reason==="string"?$.payload.reason:$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)&&typeof $.payload.payload.reason==="string"?$.payload.payload.reason:void 0,Q=$.payload?.approved===!0,Z=MW(f,J,{approved:Q,reason:W});if(!Z)return E($,"approval_not_found",`Unknown approval: ${J}`);return f.publish(f.buildEvent("approval.resolved",{approvalId:J,approved:Q,reason:W},Z.sessionId)),m($,{approvalId:J,approved:Q})}import{createSessionId as mD}from"@cline/shared";function SD(f){if(f instanceof Error)return{name:f.name,message:f.message,stack:f.stack};if(f===void 0)return;return f}var wj={debug:10,info:20,warn:30,error:40,silent:50};function kD(){let f=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if(f==="debug"||f==="info"||f==="warn"||f==="error"||f==="silent")return f;return process.env.VITEST?"error":"info"}function k(f,$,J={}){if(wj[f]<wj[kD()])return;let H=JSON.stringify({ts:new Date().toISOString(),level:f,component:"hub",message:$,...Object.fromEntries(Object.entries(J).map(([W,Q])=>[W,SD(Q)]).filter(([,W])=>W!==void 0))});if(f==="error"||f==="warn"){console.error(`[hub] ${H}`);return}console.log(`[hub] ${H}`)}function LW(f,$){let J=$ instanceof Error?$.stack||$.message:String($);k("error",f,{error:J})}async function Cj(f,$,J,H,W,Q){let Z=mD("capreq_"),j=performance.now();return k("info","capability.request.start",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:W}),await new Promise((P,X)=>{f.pendingCapabilityRequests.set(Z,{sessionId:$,targetClientId:W,capabilityName:J,onProgress:Q,resolve:(V)=>{if(k(V.ok?"info":"warn","capability.request.end",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:W,ok:V.ok,error:V.error,durationMs:Math.round(performance.now()-j)}),!V.ok){X(Error(V.error||`Capability ${J} was rejected by ${W}.`));return}P(V.payload)}}),f.publish(f.buildEvent("capability.requested",{requestId:Z,targetClientId:W,capabilityName:J,payload:H},$)),k("info","capability.request.published",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:W})})}function Ej(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",H=f.pendingCapabilityRequests.get(J);if(!H)return E($,"capability_not_found",`Unknown capability request: ${J}`);if(($.clientId?.trim()||"")!==H.targetClientId)return E($,"capability_wrong_client",`Capability request ${J} is owned by ${H.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==H.sessionId)return E($,"capability_wrong_session",`Capability request ${J} belongs to session ${H.sessionId}`);let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{};return H.onProgress?.(Q),m($,{requestId:J})}function S0(f,$,J){let H=0;for(let[W,Q]of[...f.pendingCapabilityRequests.entries()]){if(!$({requestId:W,...Q}))continue;f.pendingCapabilityRequests.delete(W),k("warn","capability.request.cancelled",{requestId:W,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,reason:J}),Q.resolve({ok:!1,error:J}),f.publish(f.buildEvent("capability.resolved",{requestId:W,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,ok:!1,cancelled:!0,error:J},Q.sessionId)),H+=1}return H}async function Sj(f,$){let J=typeof $.payload?.sessionId==="string"?$.payload.sessionId.trim():$.sessionId?.trim()||"",H=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName.trim():"",W=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId.trim():"";if(!J||!H||!W)return E($,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},Z=await f.requestCapability(J,H,Q,W);return m($,Z)}catch(Q){return E($,"capability_request_failed",Q instanceof Error?Q.message:String(Q))}}function kj(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",H=f.pendingCapabilityRequests.get(J);if(!H)return E($,"capability_not_found",`Unknown capability request: ${J}`);let W=$.clientId?.trim()||"";if(W!==H.targetClientId)return E($,"capability_wrong_client",`Capability request ${J} is owned by ${H.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==H.sessionId)return E($,"capability_wrong_session",`Capability request ${J} belongs to session ${H.sessionId}`);f.pendingCapabilityRequests.delete(J);let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:void 0,Z=typeof $.payload?.error==="string"?$.payload.error:void 0,j=$.payload?.ok===!0;return k(j?"info":"warn","capability.respond",{requestId:J,sessionId:H.sessionId,capabilityName:H.capabilityName,targetClientId:H.targetClientId,respondedByClientId:W,ok:j,error:Z}),H.resolve({ok:j,payload:Q,error:Z}),f.publish(f.buildEvent("capability.resolved",{requestId:J,capabilityName:H.capabilityName,targetClientId:H.targetClientId,respondedByClientId:W,ok:j,payload:Q,error:Z},H.sessionId)),m($,{requestId:J,ok:j})}import{createSessionId as ID}from"@cline/shared";function mj(f,$){let J=$.payload,H=J?.clientId?.trim()||$.clientId?.trim()||ID("client_");return f.clients.set(H,{clientId:H,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),f.publish(f.buildEvent("hub.client.registered",{clientId:H,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),m($,{clientId:H})}function Ij(f,$){let J=$.clientId?.trim(),H=J?f.clients.get(J):void 0;if(!J||!H)return E($,"client_not_found","Client is not registered with this hub.");let W=D4($.payload?.metadata);if(H.lastSeenAt=Date.now(),W)H.metadata=JSON.parse(JSON.stringify(W));return m($)}function xj(f,$,J){let H=$.clientId?.trim();if(H)f.clients.delete(H),J(H),f.publish(f.buildEvent("hub.client.disconnected",{clientId:H}));return m($)}function gj(f,$){return m($,{clients:[...f.clients.values()]})}var xD=30000;function gD(f){if(f==="aborted")return"run.aborted";if(f==="error"||f==="failed")return"run.failed";return"run.completed"}function vD(f){if(f.finishReason!=="error")return;return f.text.trim()||void 0}function uD(f){let $=typeof f.timeoutMs==="number"?f.timeoutMs:typeof f.timeout_ms==="number"?f.timeout_ms:void 0;if($&&Number.isFinite($)&&$>0)return Math.floor($);let J=typeof f.timeoutSeconds==="number"?f.timeoutSeconds:typeof f.timeout_seconds==="number"?f.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function cD(f,$,J,H){let W=performance.now(),Q=!1,Z={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:J.sessionId,timeoutMs:H},j=setInterval(()=>{if(Q)return;let V=Math.round(performance.now()-W);k("warn","run.heartbeat",{...Z,elapsedMs:V}),f.publish(f.buildEvent("run.heartbeat",{requestId:$.requestId,elapsedMs:V,...H?{timeoutMs:H}:{}},J.sessionId))},xD),P=f.sessionHost.runTurn(J);P.then((V)=>{if(!Q)return;k("warn","run.late_end",{...Z,elapsedMs:Math.round(performance.now()-W),finishReason:V?.finishReason})},(V)=>{if(!Q)return;k("error","run.late_error",{...Z,elapsedMs:Math.round(performance.now()-W),error:V})});let X;try{if(!H)return await P;return await Promise.race([P,new Promise((V,Y)=>{X=setTimeout(()=>{let B=`Hub run ${$.command} timed out after ${H}ms.`;Q=!0,clearInterval(j),Y(Error(B)),k("error","run.timeout",{...Z,elapsedMs:Math.round(performance.now()-W)}),_W(f,(A)=>A.sessionId===J.sessionId,B),S0(f,(A)=>A.sessionId===J.sessionId,B),f.sessionHost.abort(J.sessionId,B).catch((A)=>{k("error","run.timeout_abort_failed",{...Z,error:A})})},H)})])}finally{if(Q=!0,clearInterval(j),X)clearTimeout(X)}}async function vj(f,$){let J=Uf($),H=$.payload&&typeof $.payload==="object"?$.payload:{},W=typeof H.prompt==="string"?H.prompt:typeof H.input==="string"?H.input:"";if(!W.trim())return E($,"invalid_session_input","session input requires a prompt string");f.publish(f.buildEvent("run.started",void 0,J));let Q=H.attachments&&typeof H.attachments==="object"&&!Array.isArray(H.attachments)?H.attachments:void 0,Z=Array.isArray(Q?.userFiles)?Q.userFiles.filter((V)=>typeof V==="string"):void 0,j=uD(H);f.suppressNextTerminalEventBySession.set(J,"run.start.reply");let P;try{P=await cD(f,$,{sessionId:J,prompt:W,delivery:H.delivery==="queue"||H.delivery==="steer"?H.delivery:void 0,userImages:Array.isArray(Q?.userImages)?Q.userImages:void 0,userFiles:Z,timeoutMs:j},j)}catch(V){if(f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J);throw f.publish(f.buildEvent("run.failed",{reason:"error",error:V instanceof Error?V.message:String(V)},J)),V}if(P){let V=await wf(f,J),Y=vD(P);if(f.publish(f.buildEvent(gD(P.finishReason),{reason:P.finishReason,...Y?{error:Y}:{},result:P,...V?{snapshot:V}:{}},J)),f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J)}else f.suppressNextTerminalEventBySession.delete(J);let X=await wf(f,J);return m($,P||X?{...P?{result:P}:{},...X?{snapshot:X}:{}}:void 0)}async function uj(f,$){let J=Uf($),H=typeof $.payload?.reason==="string"?$.payload.reason:"Run was aborted before pending approval or capability request was resolved.";return _W(f,(W)=>W.sessionId===J,H),await f.sessionHost.abort(J,$.payload?.reason),S0(f,(W)=>W.sessionId===J,H),f.publish(f.buildEvent("run.aborted",{reason:H},J)),m($,{applied:!0})}async function cj(f,$){let J=V4($.payload?.payload);if(!J)return E($,"invalid_hook_payload","session.hook requires a valid hook event payload");return await f.sessionHost.dispatchHookEvent(J),m($,{applied:!0})}async function dj(f,$){switch($.type){case"chunk":return;case"agent_event":dD(f,$);return;case"hook":if($.payload.hookEventName==="tool_call")f.publish(f.buildEvent("tool.started",{toolName:$.payload.toolName},$.payload.sessionId));else if($.payload.hookEventName==="tool_result")f.publish(f.buildEvent("tool.finished",{toolName:$.payload.toolName},$.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:$.payload.sessionId,summary:$.payload.summary,lastEvent:$.payload.lifecycle};f.publish(f.buildEvent("team.progress",J,$.payload.sessionId));return}case"pending_prompts":f.publish(f.buildEvent("session.pending_prompts",{sessionId:$.payload.sessionId,prompts:$.payload.prompts},$.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:$.payload.id,prompt:$.payload.prompt,delivery:$.payload.delivery,attachmentCount:$.payload.attachmentCount};f.publish(f.buildEvent("session.pending_prompt_submitted",{sessionId:$.payload.sessionId,prompt:J},$.payload.sessionId));return}case"session_snapshot":f.publish(f.buildEvent("session.updated",{sessionId:$.payload.sessionId,snapshot:$.payload.snapshot},$.payload.sessionId));return;case"status":{let[J,H]=await Promise.all([bf(f,$.payload.sessionId),wf(f,$.payload.sessionId)]);if(J)f.publish(f.buildEvent("session.updated",{session:J,...H?{snapshot:H}:{}},$.payload.sessionId));return}case"ended":await rD(f,$);return;default:return}}function dD(f,$){let{sessionId:J,event:H}=$.payload;if(H.type==="iteration_start"){f.publish(f.buildEvent("iteration.started",{iteration:H.iteration},J));return}if(H.type==="iteration_end"){f.publish(f.buildEvent("iteration.finished",{iteration:H.iteration,hadToolCalls:H.hadToolCalls,toolCallCount:H.toolCallCount},J));return}if(H.type==="content_start"){if(H.contentType==="text"&&typeof H.text==="string"&&H.text.length>0){f.publish(f.buildEvent("assistant.delta",{text:H.text},J));return}if(H.contentType==="reasoning"){if(H.redacted&&!H.reasoning){f.publish(f.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof H.reasoning==="string"&&H.reasoning.length>0)f.publish(f.buildEvent("reasoning.delta",{text:H.reasoning,redacted:H.redacted===!0},J));return}if(H.contentType==="tool"){f.publish(f.buildEvent("tool.started",{toolCallId:H.toolCallId,toolName:H.toolName,input:H.input},J));return}}if(H.type==="content_end"){switch(H.contentType){case"text":f.publish(f.buildEvent("assistant.finished",{text:H.text},J));break;case"reasoning":f.publish(f.buildEvent("reasoning.finished",{reasoning:H.reasoning},J));break;case"tool":f.publish(f.buildEvent("tool.finished",{toolCallId:H.toolCallId,toolName:H.toolName,output:H.output,error:H.error},J));break}return}if(H.type==="done")f.publish(f.buildEvent("agent.done",{reason:H.reason,text:H.text,iterations:H.iterations,usage:H.usage},J))}async function rD(f,$){let J=f.suppressNextTerminalEventBySession.get($.payload.sessionId),H=J===$.payload.reason||J==="run.start.reply";if(H)f.suppressNextTerminalEventBySession.delete($.payload.sessionId);let[W,Q]=await Promise.all([bf(f,$.payload.sessionId),wf(f,$.payload.sessionId)]);if($.payload.reason==="completed"){let Z=await qj(W);f.publish(f.buildEvent("ui.notify",Z,$.payload.sessionId))}if(H)return;f.publish(f.buildEvent($.payload.reason==="aborted"?"run.aborted":$.payload.reason==="error"||$.payload.reason==="failed"?"run.failed":"run.completed",{reason:$.payload.reason,...Q?{snapshot:Q}:{}},$.payload.sessionId))}import{createSessionId as lj,parseRuntimeConfigExtensions as pj}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as rI,HUB_COMPACTION_CAPABILITY as lI,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as pI,HUB_HOOK_CAPABILITY_PREFIX as iI,HUB_MISTAKE_LIMIT_CAPABILITY as nI,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as aI,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as tI,isHubToolExecutorName as lD}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as $x,HUB_COMPACTION_CAPABILITY as Jx,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Hx,HUB_HOOK_CAPABILITY_PREFIX as Wx,HUB_MISTAKE_LIMIT_CAPABILITY as Qx,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Zx,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as jx}from"@cline/shared";var pD=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function y$(f){return f&&typeof f==="object"&&!Array.isArray(f)?JSON.parse(JSON.stringify(f)):void 0}function iD(f,$){let J=typeof f.name==="string"?f.name.trim():"",H=typeof f.description==="string"?f.description:"",W=typeof f.capabilityName==="string"?f.capabilityName.trim():"",Q=y$(f.inputSchema);if(!J||!H||!Q||!W||$.has(W))return;return $.add(W),{kind:"tool",capabilityName:W,name:J,description:H,inputSchema:Q,...y$(f.lifecycle)?{lifecycle:y$(f.lifecycle)}:{}}}function OW(f){if(!Array.isArray(f))return[];let $=[],J=new Set;for(let H of f){if(!H||typeof H!=="object"||Array.isArray(H))continue;let W=H,Q=W.kind,Z=typeof W.capabilityName==="string"?W.capabilityName.trim():"";if(!Z||J.has(Z))continue;if(Q==="tool"){let j=iD(W,J);if(j)$.push(j);continue}if(Q==="toolExecutor"){let j=W.executor;if(!lD(j))continue;J.add(Z),$.push({kind:"toolExecutor",capabilityName:Z,executor:j});continue}if(Q==="hook"){let j=typeof W.name==="string"?W.name.trim():"";if(!j)continue;J.add(Z),$.push({kind:"hook",capabilityName:Z,name:j});continue}if(Q==="compaction"){J.add(Z),$.push({kind:"compaction",capabilityName:Z,...y$(W.config)?{config:y$(W.config)}:{}});continue}if(Q==="checkpoint"){J.add(Z),$.push({kind:"checkpoint",capabilityName:Z,...y$(W.config)?{config:y$(W.config)}:{}});continue}if(Q==="mistakeLimit"){J.add(Z),$.push({kind:"mistakeLimit",capabilityName:Z});continue}if(Q==="userInstructionService")J.add(Z),$.push({kind:"userInstructionService",capabilityName:Z})}return $}function rj(f){return{agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,metadata:f.metadata}}function nD(f){return Object.hasOwn(f,"update")?f.update:f}function Q2(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function aD(f){let $=(f??[]).map(Q2).filter(Boolean);return $.length>0?new Set($):void 0}function tD(f,$,J){if(!J)return!0;let H=Q2(f),W=Q2($),Q=H.includes(":")?H.split(":").at(-1)??H:H,Z=W.includes(":")?W.split(":").at(-1)??W:W;return J.has(H)||J.has(W)||J.has(Q)||J.has(Z)}function zW(f,$){let J=aD($);return f.records.skill.map((H)=>({id:H.id,name:H.item.name,description:"description"in H.item&&typeof H.item.description==="string"?H.item.description:void 0,disabled:H.item.disabled===!0,skill:H.item})).filter((H)=>tD(H.id,H.name,J))}function sD(f,$){let J=async(H,W)=>{let Q=Q2(H),j=zW(f,$).filter((B)=>B.id===Q||Q2(B.name)===Q||B.id.endsWith(`:${Q}`)).filter((B)=>!B.disabled);if(j.length!==1)return j.length>1?`Skill "${H}" is ambiguous. Use one of: ${j.map((B)=>B.id).join(", ")}`:`Skill "${H}" not found.`;let P=j[0].skill,X=W?.trim(),V=X?`
|
|
696
|
-
<command-args>${
|
|
697
|
-
|
|
698
|
-
`:"";return`<command-name>${
|
|
691
|
+
version = team_outcome_fragments.version + 1`,[W,Q.outcomeId,Q.id,Q.section,Q.sourceAgentId,Q.sourceRunId??null,Q.content,Q.status,Q.reviewedBy??null,Q.reviewedAt?Q.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted(f,$){let J=J1(f),W=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(W.length===0)return[];let H=FW();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
|
|
692
|
+
WHERE team_name = ? AND status IN ('queued', 'running')`,[$,H,J]),W.map((Q)=>Q.run_id)}handleTeamEvent(f,$){this.appendTeamEvent(f,$.type,$)}}function Yj(f={}){try{let $=new Q2(f);return $.init(),$}catch{let $=new A4({teamDir:f.teamDir});return $.init(),$}}function KW(f,$){return TD(f,$)}function _D(f,$){let J=$?.["*"]??{},W=$?.[f]??{};return{...J,...W}.enabled!==!1}function MD(f,$){return f.filter((J)=>_D(J.name,$))}function Vj(f,$){return g$(MD(f,$))}function Rj(){return`team-${DD(5)}`}function yW(f,$,J,W,H,Q,Z,j){let X=df[M0({mode:J})],A=F1($,W,J,H??R1);return Vj(D1({cwd:f,...X,enableSkills:!!Z,...A,executors:{...Z?{skills:Z}:{},...j??{}}}),Q)}function LD(f){return yW(f.cwd,f.providerId,f.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,hD,f.toolExecutors).some(($)=>$.name==="skills")}var hD=async()=>"";async function OD(f){let $=f1();if(!Q4({filePath:$}))return{tools:[]};let J=new H2({clientFactory:H4()}),W;try{W=await Z4(J,{filePath:$})}catch(j){await J.dispose().catch(()=>{});let X=j instanceof Error?j.message:String(j);return f?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${X}`),{tools:[]}}let H=W.filter((j)=>j.disabled!==!0),Q=await Promise.allSettled(H.map((j)=>X4({serverName:j.name,provider:J}))),Z=[];for(let[j,X]of Q.entries())if(X.status==="fulfilled")Z.push(...X.value);else{let A=X.reason instanceof Error?X.reason.message:String(X.reason);f?.log(`[mcp] Failed to load tools from MCP server "${H[j].name}", skipping: ${A}`)}return{tools:Z,shutdown:async()=>{await J.dispose()}}}function zD(f,$){if(!f)return;for(let J of f.getTeammateIds())try{f.shutdownTeammate(J,$)}catch{}}function ND(f){if(f===void 0)return!0;switch(f){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function qD(f){let $=df[M0({mode:f.mode})];return{sessionId:f.sessionId||"",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",enableTools:f.enableTools!==!1,enableSpawnAgent:f.enableSpawnAgent??$.enableSpawnAgent??!0,enableAgentTeams:f.enableAgentTeams??$.enableAgentTeams??!0,disableMcpSettingsTools:f.disableMcpSettingsTools===!0,yolo:f.yolo===!0,missionLogIntervalSteps:typeof f.missionLogIntervalSteps==="number"&&Number.isFinite(f.missionLogIntervalSteps)?f.missionLogIntervalSteps:3,missionLogIntervalMs:typeof f.missionLogIntervalMs==="number"&&Number.isFinite(f.missionLogIntervalMs)?f.missionLogIntervalMs:120000}}class P4{teamRuntimeEntries=new Map;async build(f){let{config:$,hooks:J,extensions:W,logger:H,telemetry:Q,createSpawnTool:Z,onTeamRestored:j,userInstructionService:X,configExtensions:A,toolExecutors:P}=f,B=f.onTeamEvent??(()=>{}),Y=qD($),V=rf(),R=[],U=$.teamName?.trim()||Rj(),K=$.sessionId?.trim()||U,F=KW(A,"rules"),y=KW(A,"skills"),D=KW(A,"workflows"),M=F||y||D,T=!1,_=Boolean(X),L=X,O;if(!L&&M)L=m$({skills:{workspacePath:$.cwd},rules:{workspacePath:$.cwd},workflows:{workspacePath:$.cwd}});if(L)await L.start().catch(()=>{});let e=Y.enableTools&&y&&Boolean(L)&&(_||L?.hasConfiguredSkills($.skills)===!0)&&LD({cwd:$.cwd,providerId:$.providerId,mode:Y.mode,modelId:$.modelId,toolRoutingRules:$.toolRoutingRules,toolPolicies:$.toolPolicies,toolExecutors:P}),ff=L&&M?L.createExtension({includeRules:F,includeSkills:y,includeWorkflows:D,registerSkillsTool:e,allowedSkillNames:$.skills}):void 0,a=ff?[...W??$.extensions??[],ff]:W??$.extensions;if(Y.enableTools){if(R.push(...yW($.cwd,$.providerId,Y.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,P)),!Y.disableMcpSettingsTools){let u=await OD($.logger);R.push(...u.tools),O=u.shutdown}}let g,Pf=Y.enableAgentTeams?Yj():void 0,B0=Pf?.loadRuntime(K),r=B0?.state,tf=B0?.teammates??[],b=new Map(tf.map((u)=>[u.agentId,u])),l=$.sessionId||U,sf,of=[],u0=!1,_$=Z8({providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey??"",baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:J,extensions:a,logger:H??$.logger,telemetry:f.telemetry??$.telemetry,workspaceMetadata:$.workspaceMetadata});if(!this.teamRuntimeEntries.has(l))this.teamRuntimeEntries.set(l,{delegatedAgentConfigProvider:_$});let W1=()=>{if(!Y.enableAgentTeams)return;let u=this.teamRuntimeEntries.get(l)??{delegatedAgentConfigProvider:_$};if(this.teamRuntimeEntries.set(l,u),g=u.runtime,!g){if(g=new n1({teamName:U,leadAgentId:$.sessionId||"lead",missionLogIntervalSteps:Y.missionLogIntervalSteps,missionLogIntervalMs:Y.missionLogIntervalMs,onTeamEvent:(o)=>{if(B(o),g&&Pf){if(o.type==="teammate_spawned"&&o.teammate?.rolePrompt){let ef={agentId:o.agentId,rolePrompt:o.teammate.rolePrompt,modelId:o.teammate.modelId,maxIterations:o.teammate.maxIterations};b.set(ef.agentId,ef)}if(o.type==="teammate_shutdown"&&!ND(o.reason))b.delete(o.agentId);Pf.handleTeamEvent(K,o),Pf.persistRuntime(K,g.exportState(),Array.from(b.values()))}}}),r)g.hydrateState(r),u0=!0;u.runtime=g}if(!T){if(!g)return;T=!0;let o=P8({runtime:g,leadAgentId:$.sessionId||"lead",restoredFromPersistence:Boolean(r),restoredTeammates:tf,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(ef)=>{of=ef,sf?.addTools(ef)},createBaseTools:Y.enableTools?()=>yW($.cwd,$.providerId,Y.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,void 0,P):void 0,teammateConfigProvider:_$});if(u0)g.recoverActiveRuns("runtime_recovered");if(o.restoredFromPersistence)j?.();R.push(...o.tools)}return g};if(Y.enableSpawnAgent&&Z){let u=Z();R.push({...u,execute:async(o,ef)=>{return W1(),u.execute(o,ef)}})}if(Y.enableAgentTeams)W1();let R2=Vj(R,$.toolPolicies),w4=R2.some((u)=>u.name===Hf.SUBMIT_AND_EXIT&&u.lifecycle?.completesRun===!0),M$=Y.enableAgentTeams?()=>{let u=this.teamRuntimeEntries.get(l)?.runtime;if(!u)return;let o=u.listTasks(),ef=o.some((Y0)=>Y0.status==="in_progress"||Y0.status==="pending"),fH=u.listRuns({}),nX=fH.some((Y0)=>Y0.status==="running"||Y0.status==="queued");if(ef||nX){let Y0=o.filter((Lf)=>Lf.status==="in_progress"||Lf.status==="pending").map((Lf)=>`${Lf.id} (${Lf.status}): ${Lf.title}`).join(", "),$H=fH.filter((Lf)=>Lf.status==="running"||Lf.status==="queued").map((Lf)=>`${Lf.id} (${Lf.status})`).join(", "),b4=[];if(Y0)b4.push(`Unfinished tasks: ${Y0}`);if($H)b4.push(`Active runs: ${$H}`);return`[SYSTEM] You still have team obligations. ${b4.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,H1=w4?{requireCompletionTool:!0,...M$?{completionGuard:M$}:{}}:M$?{completionGuard:M$}:void 0;return{tools:R2,logger:H??$.logger,telemetry:Q??$.telemetry,teamRuntime:g,teamRestoredFromPersistence:Boolean(r),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(l)?.delegatedAgentConfigProvider??_$,extensions:a,completionPolicy:H1,registerLeadAgent:(u)=>{if(sf=u,of.length>0)u.addTools(g$(of,[...V]))},shutdown:async(u)=>{if(zD(g,u),this.teamRuntimeEntries.delete(l),await O?.(),!_)L?.stop()}}}}import{getClineEnvironmentConfig as wD,isOAuthProviderId as bD}from"@cline/shared";var UW="workos:";function CD(f,$){if(f==="cline")return`${UW}${$}`;return $}function ED(f,$){if(f==="cline"&&$.toLowerCase().startsWith(UW))return $.slice(UW.length);return $}function SD(f){let J=Zf(f)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function kD(f,$){let J=f.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let W=SD($);if(W)return W;return Date.now()-1}function ID(f,$){let J=$.auth?.accessToken?.trim(),W=$.auth?.refreshToken?.trim();if(!J||!W)return null;let H=ED(f,J);if(!H)return null;return{access:H,refresh:W,expires:kD($,H),accountId:$.auth?.accountId}}function mD(f,$){let J=f?.expiresAt,W=$?.expiresAt;return f?.accessToken===$?.accessToken&&f?.refreshToken===$?.refreshToken&&f?.accountId===$?.accountId&&J===W}class B4 extends Error{providerId;constructor(f){super(`OAuth credentials for provider "${f}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=f}}class GW{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor(f){this.providerSettingsManager=f?.providerSettingsManager??new x0,this.telemetry=f?.telemetry}async resolveProviderApiKey(f){if(!bD(f.providerId))return null;return this.resolveWithSingleFlight(f.providerId,f.forceRefresh)}async resolveWithSingleFlight(f,$=!1){let J=this.refreshInFlight.get(f);if(J)return J;let W=this.resolveProviderApiKeyInternal(f,$).catch((H)=>{throw H}).finally(()=>{this.refreshInFlight.delete(f)});return this.refreshInFlight.set(f,W),W}async resolveProviderApiKeyInternal(f,$){let J=this.providerSettingsManager.getProviderSettings(f);if(!J)return null;let W=ID(f,J);if(!W)return null;let H=await this.resolveCredentials(f,J,W,$);if(!H)throw new B4(f);let Q=CD(f,H.access),Z={...J.auth??{},accessToken:Q,refreshToken:H.refresh,accountId:H.accountId};Z.expiresAt=H.expires;let j={...J,auth:Z},X=!mD(J.auth,j.auth);if(X)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:f,apiKey:Q,accountId:H.accountId,refreshed:X}}async resolveCredentials(f,$,J,W){if(f==="cline")return $6(J,{apiBaseUrl:$.baseUrl?.trim()||wD().apiBaseUrl,telemetry:this.telemetry},{forceRefresh:W});if(f==="oca")return A6(J,{forceRefresh:W,telemetry:this.telemetry},{mode:$.oca?.mode,telemetry:this.telemetry});return W6(J,{forceRefresh:W,telemetry:this.telemetry})}}import{normalizeUserInput as xD}from"@cline/shared";import{nanoid as gD}from"nanoid";class Fj{list(f){return f?Ef(f):[]}update(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=$.promptId.trim(),W=f.pendingPrompts.findIndex((X)=>X.id===J);if(W<0)return{sessionId:$.sessionId,prompts:Ef(f),updated:!1};let H=f.pendingPrompts[W];if(!H)return{sessionId:$.sessionId,prompts:Ef(f),updated:!1};let Q=$.prompt===void 0?H.prompt:xD($.prompt).trim();if(!Q)throw Error("prompt cannot be empty");let Z=$.delivery??H.delivery,j={...H,prompt:Q,delivery:Z};return f.pendingPrompts.splice(W,1),vD(f,j,W,H.delivery),{sessionId:$.sessionId,prompts:Ef(f),prompt:Y4(j),updated:!0}}delete(f,$){if(!f)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=$.promptId.trim(),W=f.pendingPrompts.findIndex((Q)=>Q.id===J);if(W<0)return{sessionId:$.sessionId,prompts:Ef(f),removed:!1};let[H]=f.pendingPrompts.splice(W,1);return{sessionId:$.sessionId,prompts:Ef(f),prompt:H?Y4(H):void 0,removed:!0}}enqueue(f,$){let{prompt:J,delivery:W,userImages:H,userFiles:Q}=$,Z=f.pendingPrompts.findIndex((j)=>j.prompt===J);if(Z>=0){let[j]=f.pendingPrompts.splice(Z,1),X={...j,prompt:J,userImages:H??j.userImages,userFiles:Q??j.userFiles};if(W==="steer"||j.delivery==="steer")f.pendingPrompts.unshift({...X,delivery:"steer"});else f.pendingPrompts.push(X)}else{let j={id:`pending_${Date.now()}_${gD(5)}`,prompt:J,delivery:W,userImages:H,userFiles:Q};if(W==="steer")f.pendingPrompts.unshift(j);else f.pendingPrompts.push(j)}return Ef(f)}consumeSteer(f){let $=f.pendingPrompts.findIndex((W)=>W.delivery==="steer");if($<0)return{prompts:Ef(f)};let[J]=f.pendingPrompts.splice($,1);return{entry:J,prompts:Ef(f)}}shiftNext(f){return{entry:f.pendingPrompts.shift(),prompts:Ef(f)}}requeueFront(f,$){return f.pendingPrompts.unshift($),Ef(f)}clear(f){return f.pendingPrompts.length=0,[]}}class TW{deps;service=new Fj;constructor(f){this.deps=f}list(f){return this.service.list(this.deps.getSession(f))}update(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=this.service.update($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}delete(f){let $=this.deps.getSession(f.sessionId);if(!$||$.aborting)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=this.service.delete($,f);return this.emitPrompts($),this.scheduleDrain(f.sessionId,$),J}enqueue(f,$){let J=this.deps.getSession(f);if(!J||J.aborting)return;this.service.enqueue(J,$),this.emitPrompts(J),this.scheduleDrain(f,J)}consumeSteer(f){let $=this.deps.getSession(f);if(!$)return;let{entry:J}=this.service.consumeSteer($);if(!J)return;return this.emitPrompts($),this.emitSubmitted($,J),J.prompt}clearAborted(f){if(f.pendingPrompts.length===0)return;this.service.clear(f),this.emitPrompts(f)}emitPrompts(f){this.deps.emit({type:"pending_prompts",payload:{sessionId:f.sessionId,prompts:Ef(f)}})}scheduleDrain(f,$){if($.pendingPrompts.length===0||$.aborting||$.drainingPendingPrompts||!$.agent.canStartRun())return;queueMicrotask(()=>{this.drain(f)})}async drain(f){let $=this.deps.getSession(f);if(!$||$.aborting||$.drainingPendingPrompts)return;if(!$.agent.canStartRun())return;let{entry:J}=this.service.shiftNext($);if(!J)return;this.emitPrompts($),this.emitSubmitted($,J),$.drainingPendingPrompts=!0;try{await this.deps.send({sessionId:f,prompt:J.prompt,userImages:J.userImages,userFiles:J.userFiles})}catch(W){if((W instanceof Error?W.message:String(W)).includes("already in progress"))this.service.requeueFront($,J),this.emitPrompts($);else throw W}finally{if($.drainingPendingPrompts=!1,$.pendingPrompts.length>0&&$.status!=="failed"&&$.status!=="cancelled")queueMicrotask(()=>{this.drain(f)})}}emitSubmitted(f,$){let J=Y4($);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:f.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function Y4(f){return{id:f.id,prompt:f.prompt,delivery:f.delivery,attachmentCount:(f.userImages?.length??0)+(f.userFiles?.length??0)}}function Ef(f){return f.pendingPrompts.map(Y4)}function vD(f,$,J,W){if($.delivery==="steer")f.pendingPrompts.unshift($);else if(W==="steer")f.pendingPrompts.push($);else f.pendingPrompts.splice(J,0,$)}Uf();class _W{deps;constructor(f){this.deps=f}dispatchAgentEvent(f,$,J){let W=this.deps.getSession(f),H={sessionId:f,config:$,liveSession:W,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},Q=d5(J),Z=!!W&&(!Q.agentId||Q.agentId===DW(W.agent));r5(H,J,Z?{isPrimaryAgentEvent:!0,agentId:DW(W.agent),conversationId:W.agent.getConversationId(),...W?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent(f,$){let J=this.deps.getSession(f);if(J){if(O5(J,$),$.type==="agent_event"){let W={sessionId:f,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};r5(W,$.event,{agentId:$.agentId,teamRole:"teammate",teamAgentId:$.agentId,isPrimaryAgentEvent:!1})}if($.type==="teammate_spawned"){let W=A0({agentId:$.teammate.runtimeAgentId??$.agentId,conversationId:$.teammate.conversationId,parentAgentId:$.teammate.parentAgentId,createdByAgentId:DW(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:$.agentId});if(W)d0(J.config.telemetry,{ulid:f,modelId:$.teammate.modelId??J.config.modelId,provider:J.config.providerId,...W})}}if(await z5(f,$,this.deps.invokeBackendOptional),J)N5(J,f,$,this.deps.emit)}async handlePluginEvent(f,$,J){if($.name==="plugin_log"){this.handlePluginLog(f,$.payload);return}if($.name==="automation_event"){let X=this.deps.getSession(f)?.config.extensionContext?.automation??J;if(!X)return;let A=$.payload&&typeof $.payload==="object"?$.payload:void 0;if(!A)return;await X.ingestEvent(A);return}if($.name!=="steer_message"&&$.name!=="queue_message"&&$.name!=="pending_prompt")return;let W=$.payload&&typeof $.payload==="object"?$.payload:void 0,H=typeof W?.sessionId==="string"&&W.sessionId.trim().length>0?W.sessionId.trim():f,Q=typeof W?.prompt==="string"?W.prompt.trim():"";if(!Q)return;let Z=$.name==="steer_message"?"steer":$.name==="queue_message"?"queue":W?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(H,{prompt:Q,delivery:Z})}handlePluginLog(f,$,J){let W=this.deps.getSession(f),H=J??W?.config.extensionContext?.logger??W?.config.logger;if(!H||!$||typeof $!=="object")return;let Q=$,Z=typeof Q.message==="string"?Q.message:"";if(!Z)return;let j=Q.metadata&&typeof Q.metadata==="object"?{...Q.metadata}:{};if(j.sessionId??=f,typeof Q.pluginName==="string"&&Q.pluginName)j.pluginName=Q.pluginName;if(Q.level==="debug"){H.debug(Z,j);return}if(Q.level==="error"){if(H.error)H.error(Z,j);else H.log(Z,{...j,severity:"error"});return}H.log(Z,j)}}function DW(f){return f.getAgentId()}function MW(f){return{sessionId:f.sessionId,source:f.source,pid:process.pid,startedAt:f.startedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,status:f.status,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:k0(f.config),teamName:f.config.teamName?.trim()||void 0,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,parentSessionId:typeof f.sessionMetadata?.parentSessionId==="string"?f.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof f.sessionMetadata?.parentAgentId==="string"?f.sessionMetadata.parentAgentId:void 0,agentId:typeof f.sessionMetadata?.agentId==="string"?f.sessionMetadata.agentId:void 0,conversationId:typeof f.sessionMetadata?.conversationId==="string"?f.sessionMetadata.conversationId:void 0,isSubagent:typeof f.sessionMetadata?.isSubagent==="boolean"?f.sessionMetadata.isSubagent:!1,prompt:f.pendingPrompt,metadata:f.sessionMetadata,messagesPath:f.artifacts?.messagesPath,updatedAt:f.updatedAt??f.endedAt??f.startedAt}}function LW(f,$){let J=f[$];return typeof J==="function"?J:null}async function Kj(f,$,...J){let W=LW(f,$);if(!W)throw Error(`session service method not available: ${$}`);return Promise.resolve(W.apply(f,J))}async function yj(f,$,...J){let W=LW(f,$);if(!W)return;await Promise.resolve(W.apply(f,J))}async function Uj(f,$,...J){let W=LW(f,$);if(!W)return;return await Promise.resolve(W.apply(f,J))}W0();Uf();function hW(f,$,J,W){return I$({configProvider:{getRuntimeConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking,maxIterations:$.maxIterations,hooks:$.hooks,extensions:$.extensions,logger:$.logger,telemetry:$.telemetry},getConnectionConfig:()=>f.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey,baseUrl:$.baseUrl,headers:$.headers,providerConfig:$.providerConfig,knownModels:$.knownModels,thinking:$.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Q=$.enableTools?D1({cwd:$.cwd,...df[M0({mode:$.mode})],executors:W}):[];if($.enableSpawnAgent)Q.push(hW(f,$,J,W));return g$(Q)},onSubAgentEvent:(Q)=>f.onAgentEvent(J,$,Q),onSubAgentStart:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime;f.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let j=A0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)d0($.telemetry,{ulid:J,modelId:$.modelId,provider:$.providerId,...j});U2($.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...j}),f.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let Z=f.getSession(J)?.runtime.teamRuntime,j=f.subAgentStarts.get(Q.subAgentId),X=j?Date.now()-j.startedAt:0,A=Q.result?.text?Q.result.text.split(`
|
|
693
|
+
`).length:0;U2($.telemetry,{event:"ended",ulid:J,durationMs:X,outputLines:A,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...A0({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:Z?.getTeamId(),teamName:Z?.getTeamName(),createdByAgentId:Q.parentAgentId})}),f.subAgentStarts.delete(Q.subAgentId),f.invokeBackendOptional("handleSubAgentEnd",J,Q)}})}import{readFile as uD,stat as cD}from"node:fs/promises";var dD=20480000;async function Gj(f){let $=await cD(f);if(!$.isFile())throw Error("Path is not a file");if($.size>dD)throw Error("File is too large to read into context.");let J=await uD(f,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var Tj=5000;function Z2(f){return typeof f==="number"&&Number.isFinite(f)?f:void 0}function sD(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,J=Z2($.inputTokens),W=Z2($.outputTokens),H=Z2($.cacheReadTokens),Q=Z2($.cacheWriteTokens),Z=Z2($.totalCost);if(J===void 0||W===void 0||H===void 0||Q===void 0||Z===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:H,cacheWriteTokens:Q,totalCost:Z}}function oD(f,$){return{inputTokens:Math.max(f.inputTokens,$.inputTokens),outputTokens:Math.max(f.outputTokens,$.outputTokens),cacheReadTokens:Math.max(f.cacheReadTokens,$.cacheReadTokens),cacheWriteTokens:Math.max(f.cacheWriteTokens,$.cacheWriteTokens),totalCost:Math.max(f.totalCost,$.totalCost)}}class g0{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new v1;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new e$;constructor(f){let $=lD();if($)tD($);let J=B$(f.distinctId);this.sessionService=f.sessionService,this.runtimeBuilder=f.runtimeBuilder??new P4,this.createAgentInstance=f.createAgent??((W)=>new L0(W)),this.defaultCapabilities=Ff(f.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=f.toolPolicies,this.providerSettingsManager=f.providerSettingsManager??new x0,this.oauthTokenManager=f.oauthTokenManager??new GW({providerSettingsManager:this.providerSettingsManager,telemetry:f.telemetry}),this.defaultTelemetry=f.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=f.fetch,this.pendingPromptsController=new TW({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 _W({getSession:(W)=>this.sessions.get(W),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(W)=>this.emit(W),persistMessages:(W,H,Q)=>{this.invoke("persistSessionMessages",W,H,Q)},enqueuePendingPrompt:(W,H)=>this.pendingPromptsController.enqueue(W,H),invokeBackendOptional:(W,...H)=>this.invokeOptional(W,...H)})}async startSession(f){let $=f.source??Rf.CLI,J=n(),W=f.config.sessionId?.trim()??"",H=W||iD(),Q=f,Z=Q.initialMessages??[],j=Z.length>0?r8(Z):Vf(),X=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!X)throw Error("session service method not available: ensureSessionsDir");let A=OW(X,H),P=OW(A,`${H}.messages.json`),B=OW(A,`${H}.json`),Y=k0(f.config),V=Df.parse({version:1,session_id:H,source:$,pid:process.pid,started_at:J,status:"running",interactive:f.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Q.config.cwd,workspace_root:Y,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,messages_path:P}),R;if(W.length>0&&Z.length>0&&!Q.prompt?.trim()){let b=await this.invokeOptionalValue("readSessionManifest",H);if(b)V=b,R={manifestPath:B,messagesPath:b.messages_path||P,manifest:b}}let K=await this.seedAggregateUsageFromArtifacts({initialUsage:j,sessionDir:A,rootMessagesPath:R?.messagesPath??P,manifest:V});this.usageBySession.set(H,j),this.aggregateUsageBySession.set(H,K);let F=Ff(this.defaultCapabilities,f.capabilities),y=F?.toolExecutors??this.toolExecutors,D=f.localRuntime,M=D?.extensionContext?.logger??D?.logger,T=D?.extensionContext?.automation,_;_=await OZ({input:Q,localRuntime:f.localRuntime,sessionId:H,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:F,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(b)=>{if(b.name==="plugin_log"){this.eventBridge.handlePluginLog(H,b.payload,M);return}this.eventBridge.handlePluginEvent(H,b,T)},onTeamEvent:(b)=>{this.eventBridge.handleTeamEvent(H,b),_.config.onTeamEvent?.(b)},createSpawnTool:()=>hW({getSession:(b)=>this.sessions.get(b),subAgentStarts:this.subAgentStarts,onAgentEvent:(b,l,sf)=>this.eventBridge.dispatchAgentEvent(b,l,sf),invokeBackendOptional:(b,...l)=>this.invokeOptional(b,...l)},_.config,H,y),readSessionMetadata:async()=>(await this.getSession(H))?.metadata,writeSessionMetadata:async(b)=>{await this.persistSessionMetadata(H,()=>b)}});let L=await this.runtimeBuilder.build(_.runtimeBuilderInput),O=_.config,e=_.providerConfig;if(L.teamRuntime&&!O.teamName?.trim())O.teamName=L.teamRuntime.getTeamName();let ff=[...L.tools,...O.extraTools??[]],a=L.extensions??_.extensions,g={sessionId:H,providerId:e.providerId,modelId:e.modelId,apiKey:e.apiKey,baseUrl:e.baseUrl,headers:e.headers,knownModels:e.knownModels,providerConfig:e,thinking:O.thinking,reasoningEffort:O.reasoningEffort??e.reasoningEffort,systemPrompt:O.systemPrompt,maxIterations:O.maxIterations,execution:O.execution,prepareTurn:c5(O),tools:ff,hooks:_.hooks,extensions:a,hookErrorMode:O.hookErrorMode,initialMessages:_.effectiveInput.initialMessages,userFileContentLoader:Gj,toolPolicies:_.toolPolicies,requestToolApproval:_.requestToolApproval,onConsecutiveMistakeLimitReached:O.onConsecutiveMistakeLimitReached,completionPolicy:L.completionPolicy,consumePendingUserMessage:()=>{let b=this.pendingPromptsController.consumeSteer(H);return b?t1(b,O.mode):b},logger:L.logger??O.logger,extensionContext:O.extensionContext,onEvent:(b)=>this.eventBridge.dispatchAgentEvent(H,O,b)};g.hooks={...g.hooks,onEvent:async(b)=>{if(await _.hooks?.onEvent?.(b),b.type!=="assistant-message")return;let l=this.sessions.get(H);if(!l)return;let sf=l.agent.getMessages();try{await this.invoke("persistSessionMessages",H,sf,O.systemPrompt)}catch(of){O.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:H,error:of})}}};let Pf=this.createAgentInstance(g);if(g.onEvent)Pf.subscribeEvents(g.onEvent);L.registerLeadAgent?.(Pf);let B0=A0({agentId:Pf.getAgentId(),conversationId:Pf.getConversationId(),teamId:L.teamRuntime?.getTeamId(),teamName:L.teamRuntime?.getTeamName(),teamRole:L.teamRuntime?"lead":void 0});if(zZ(O,H,W.length>0,Y,B0),B0)d0(O.telemetry,{ulid:H,modelId:O.modelId,provider:O.providerId,...B0});if(L.teamRuntime)i4(O.telemetry,{ulid:H,teamId:L.teamRuntime.getTeamId(),teamName:L.teamRuntime.getTeamName(),leadAgentId:Pf.getAgentId(),restoredFromPersistence:L.teamRestoredFromPersistence===!0});let r={sessionId:H,config:O,sessionMetadata:Q.sessionMetadata,...R?{artifacts:R}:{},source:$,startedAt:R?.manifest.started_at??J,updatedAt:R?.manifest.ended_at??R?.manifest.started_at??J,pendingPrompt:V.prompt,runtime:L,agent:Pf,started:!1,status:R?.manifest.status??"running",aborting:!1,interactive:f.interactive===!0,persistedMessages:Z,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:_.pluginSandboxShutdown,submitAndExitObserved:!1};if(this.sessions.set(H,r),this.emitStatus(H,"running"),Z.length>0&&!R){if(await this.ensureSessionPersisted(r),await this.invoke("persistSessionMessages",r.sessionId,Z,r.config.systemPrompt),!Q.prompt?.trim())await this.updateStatus(r,"completed",0)}let tf;try{if(Q.prompt?.trim())if(tf=await this.executeTurn(r,{prompt:Q.prompt,userImages:Q.userImages,userFiles:Q.userFiles}),!r.interactive)await this.finalizeSingleRun(r,tf.finishReason);else await this.completeInteractiveTurn(r,tf.finishReason)}catch(b){if(r.interactive&&r.aborting)tf=await this.completeAbortedInteractiveTurn(r);else throw await this.failSession(r),b}return{sessionId:H,manifest:V,manifestPath:B,messagesPath:P,result:tf}}async restoreSession(f){return this.sessionVersioning.restoreCheckpoint({...f,getSession:($)=>this.getSession($),readMessages:($)=>this.readSessionMessages($),buildStartInput:($,J)=>{let W=$.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:$.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...W?{sessionMetadata:W}:{},initialMessages:$.initialMessages}},startSession:($)=>this.startSession($),getStartedSessionId:($)=>$.sessionId,readRestoredSession:($)=>this.getSession($)})}async runTurn(f){let $=this.getSessionOrThrow(f.sessionId),J=$.agent.canStartRun(),W=f.delivery??($.interactive&&!J?"queue":void 0);if($.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:f.sessionId,promptLength:f.prompt.length,userImageCount:f.userImages?.length??0,userFileCount:f.userFiles?.length??0,delivery:W??"immediate"}}),W==="queue"||W==="steer"){this.pendingPromptsController.enqueue(f.sessionId,{prompt:f.prompt,delivery:W,userImages:f.userImages,userFiles:f.userFiles});return}try{let H=await this.executeTurn($,{prompt:f.prompt,userImages:f.userImages,userFiles:f.userFiles});if(!$.interactive)await this.finalizeSingleRun($,H.finishReason);else await this.completeInteractiveTurn($,H.finishReason);if(H.finishReason==="error"||H.finishReason==="aborted")return H;return queueMicrotask(()=>{this.pendingPromptsController.drain(f.sessionId)}),H}catch(H){if($.interactive&&$.aborting)return await this.completeAbortedInteractiveTurn($);throw await this.failSession($),H}}async getAccumulatedUsage(f){let $=$5(this.usageBySession.get(f)),J=$5(this.aggregateUsageBySession.get(f));return $||J?{usage:$,aggregateUsage:J}:void 0}async abort(f,$){let J=this.sessions.get(f);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:f}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort($)}async stopSession(f){let $=this.sessions.get(f);if(!$)return;if($.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:f}}),$.interactive&&$.status!=="running"){await this.releaseSessionRuntime($,"session_stop");return}$.aborting=!0,$.agent.abort(Error("session_stop")),await this.shutdownSession($,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose(f="session_manager_dispose"){let $=[...this.sessions.values()];if($.length===0)return;await Promise.allSettled($.map((J)=>J.interactive&&J.status!=="running"?this.releaseSessionRuntime(J,f):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:f,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession(f){let $=this.sessions.get(f);if($)return MW($);let J=f.trim();if(!J)return;let W=await this.getRow(J);if(W)return x1(W);let H=await this.readManifest(J);return H?H5(H):void 0}async listSessions(f=200){let J=(await this.listRows(f)).map(x1),W=new Set(J.map((H)=>H.sessionId));for(let H of this.sessions.values()){if(W.has(H.sessionId))continue;J.unshift(MW(H))}return J.slice(0,f)}async deleteSession(f){if(this.sessions.has(f))await this.stopSession(f);let $=await this.invoke("deleteSession",f);if($.deleted)this.usageBySession.delete(f),this.aggregateUsageBySession.delete(f);return $.deleted}async updateSession(f,$){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:f,prompt:$.prompt,metadata:$.metadata,title:$.title}))?.updated===!0}}async readSessionMessages(f){let $=f.trim();if(!$)return[];let J=await this.getRow($);if(J?.messagesPath)return N0(J.messagesPath);let W=await this.readManifest($);return N0(W?.messages_path)}async dispatchHookEvent(f){await lQ(f,{queueSpawnRequest:($)=>this.invokeOptional("queueSpawnRequest",$),upsertSubagentSessionFromHook:($)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",$),appendSubagentHookAudit:($,J)=>this.invokeOptional("appendSubagentHookAudit",$,J),applySubagentStatus:($,J)=>this.invokeOptional("applySubagentStatus",$,J)})}subscribe(f,$){return this.events.subscribe(f,$)}async updateSessionModel(f,$){let J=this.getSessionOrThrow(f);J.config.modelId=$,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:$}),J.agent.updateConnection({modelId:$})}handlePluginEvent(f,$,J){return this.eventBridge.handlePluginEvent(f,$,J)}async executeTurn(f,$){let J=await this.prepareTurnInput(f,$),W=J.prompt.trim();if(!W)throw Error("prompt cannot be empty");if(!f.artifacts&&!f.pendingPrompt)f.pendingPrompt=W;await this.ensureSessionPersisted(f),await this.syncOAuthCredentials(f),await this.markTurnRunning(f);let H=await this.executeAgentTurn(f,W,J.userImages,J.userFiles);while(q5(f,H.finishReason)){let Q=await w5(f);if(Q.length===0)break;let Z=b5(f,Q);H=await this.executeAgentTurn(f,Z)}return H}async completeInteractiveTurn(f,$){if(a1(f))return;let J=$==="aborted"||f.aborting,W=$==="error";await this.updateStatus(f,J?"cancelled":W?"failed":"completed",W?1:0),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$,ts:Date.now()}}),f.aborting=!1}async completeAbortedInteractiveTurn(f){let $=new Date,J=f.agent.getMessages();return f.persistedMessages=J,f.started=f.started||J.length>0,await this.completeInteractiveTurn(f,"aborted"),{text:"",usage:Vf(),messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:f.config.modelId,provider:f.config.providerId},startedAt:$,endedAt:$,durationMs:0}}async executeAgentTurn(f,$,J,W){let H=f.started||f.agent.getMessages().length>0,Q=f.persistedMessages??f.agent.getMessages(),Z=this.usageBySession.get(f.sessionId)??Vf(),j=this.aggregateUsageBySession.get(f.sessionId)??Z;f.turnUsageBaseline=Z,f.turnAggregateUsageBaseline=j,f.turnPrimaryUsage=Vf(),f.turnUsageByAgent=new Map,v4(f.config.telemetry,f.sessionId,f.config.mode),Q1(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,model:f.config.modelId,source:"user",mode:f.config.mode,...this.getSessionAgentTelemetryIdentity(f)});try{let X=H?()=>f.agent.continue($,J,W):()=>f.agent.run($,J,W),A=await this.runWithAuthRetry(f,X,Q);f.started=!0;let P=z8(A.messages,A,Q);f.persistedMessages=P;let B=d8(f.turnUsageByAgent?.values()??[]),Y=Xf(Z,A.usage),V=Xf(Xf(Vf(),A.usage),B),R=Xf(j,V);return this.usageBySession.set(f.sessionId,Y),this.aggregateUsageBySession.set(f.sessionId,R),await this.persistSessionMetadata(f.sessionId,(U)=>({...U??{},totalCost:Y.totalCost,aggregatedAgentsCost:R.totalCost,usage:Y,aggregateUsage:R})),await this.invoke("persistSessionMessages",f.sessionId,P,f.config.systemPrompt),this.observeTaskCompletionTool(f,A),A}catch(X){throw await this.invoke("persistSessionMessages",f.sessionId,f.agent.getMessages(),f.config.systemPrompt),X}finally{f.turnUsageBaseline=void 0,f.turnAggregateUsageBaseline=void 0,f.turnPrimaryUsage=void 0,f.turnUsageByAgent=void 0}}observeTaskCompletionTool(f,$){if(f.submitAndExitObserved)return;if(!$.toolCalls.some((W)=>W.name===Hf.SUBMIT_AND_EXIT&&W.error===void 0))return;f.submitAndExitObserved=!0,K2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity(f)})}async prepareTurnInput(f,$){let J=k0(f.config),W=aD($.prompt).trim();if(!W)return{prompt:"",userImages:$.userImages,userFiles:this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles)};let H=await f8(W,J);NZ(f.config.telemetry,H);let Q=t1(H.prompt,f.config.mode),Z=this.resolveAbsoluteFilePaths(f.config.cwd,$.userFiles),j=this.resolveAbsoluteFilePaths(J,H.matchedFiles),X=Array.from(new Set([...Z,...j]));return{prompt:Q,userImages:$.userImages,userFiles:X.length>0?X:void 0}}async ensureSessionPersisted(f){if(f.artifacts)return;let $=k0(f.config);f.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:f.sessionId,source:f.source,pid:process.pid,interactive:f.interactive,provider:f.config.providerId,model:f.config.modelId,cwd:f.config.cwd,workspaceRoot:$,teamName:f.config.teamName,enableTools:f.config.enableTools,enableSpawn:f.config.enableSpawnAgent,enableTeams:f.config.enableAgentTeams,prompt:f.pendingPrompt,metadata:f.sessionMetadata,startedAt:f.startedAt})}async markTurnRunning(f){if(f.status==="running")return;await this.updateStatus(f,"running",null)}async persistSessionMetadata(f,$){let J=this.sessions.get(f),W=await this.invokeOptionalValue("readSessionManifest",f)??J?.artifacts?.manifest,H=$(W?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:f,metadata:H}))?.updated===!1)return;J.sessionMetadata=H,J.artifacts.manifest.metadata=H}async finalizeSingleRun(f,$){if(a1(f))return;let J=$==="aborted"||f.aborting,W=$==="error";await this.shutdownSession(f,{status:J?"cancelled":W?"failed":"completed",exitCode:W?1:0,shutdownReason:W?"session_error":"session_complete",endReason:$})}async failSession(f){await this.shutdownSession(f,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession(f,$){if($.status==="completed"&&!f.submitAndExitObserved)K2(f.config.telemetry,{ulid:f.sessionId,provider:f.config.providerId,modelId:f.config.modelId,mode:f.config.mode,durationMs:Date.now()-Date.parse(f.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity(f)});u8(f);let J=[],W=(H,Q)=>{J.push(Q),f.config.logger?.log("Session shutdown cleanup failed",{sessionId:f.sessionId,stage:H,error:Q,severity:"warn"})};if(f.artifacts){try{await this.updateStatus(f,$.status,$.exitCode)}catch(H){W("update_status",H)}try{await f.agent.shutdown($.shutdownReason)}catch(H){W("agent_shutdown",H)}}try{await Promise.resolve(f.runtime.shutdown($.shutdownReason))}catch(H){W("runtime_shutdown",H)}try{await f.pluginSandboxShutdown?.()}catch(H){W("plugin_sandbox_shutdown",H)}if(this.sessions.delete(f.sessionId),this.emit({type:"ended",payload:{sessionId:f.sessionId,reason:$.endReason,ts:Date.now()}}),J.length>0&&$.status==="failed")throw J[0]}async releaseSessionRuntime(f,$){let J=[],W=(H,Q)=>{J.push(Q),f.config.logger?.log("Session runtime cleanup failed",{sessionId:f.sessionId,stage:H,error:Q,severity:"warn"})};try{await f.agent.shutdown($)}catch(H){W("agent_shutdown",H)}try{await Promise.resolve(f.runtime.shutdown($))}catch(H){W("runtime_shutdown",H)}try{await f.pluginSandboxShutdown?.()}catch(H){W("plugin_sandbox_shutdown",H)}if(this.sessions.delete(f.sessionId),J.length>0)throw J[0]}async updateStatus(f,$,J){if(!f.artifacts)return;let W=await this.invoke("updateSessionStatus",f.sessionId,$,J);if(!W.updated)return;let H=await this.invokeOptionalValue("readSessionManifest",f.sessionId)??f.artifacts.manifest;if(H.status=$,$==="running")delete H.ended_at,H.exit_code=null;else H.ended_at=W.endedAt??n(),H.exit_code=typeof J==="number"?J:null;f.artifacts.manifest=H,f.status=$,f.updatedAt=W.endedAt??n(),f.endedAt=$==="running"?null:H.ended_at,f.exitCode=H.exit_code,await this.invoke("writeSessionManifest",f.artifacts.manifestPath,H),this.emitStatus(f.sessionId,$)}async runWithAuthRetry(f,$,J){try{return await $()}catch(W){if(!nD(W,f.config.providerId))throw W;return await this.syncOAuthCredentials(f,{forceRefresh:!0}),f.agent.restore(J),$()}}async syncOAuthCredentials(f,$){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:f.config.providerId,forceRefresh:$?.forceRefresh})}catch(W){if(W instanceof B4)throw Error(`${W.providerId} requires re-authentication.`);throw W}if(!J?.apiKey||f.config.apiKey===J.apiKey)return;f.config.apiKey=J.apiKey,f.agent.updateConnection({apiKey:J.apiKey}),f.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),f.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow(f){let $=this.sessions.get(f);if(!$)throw Error(`session not found: ${f}`);return $}resolveAbsoluteFilePaths(f,$){if(!$||$.length===0)return[];let J=$.map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>pD(W)?W:zW(f,W));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity(f){return A0({agentId:f.agent.getAgentId(),conversationId:f.agent.getConversationId(),teamId:f.runtime.teamRuntime?.getTeamId(),teamName:f.runtime.teamRuntime?.getTeamName(),teamRole:f.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts(f){let $=await this.summarizePersistedTeammateUsage(f.sessionDir,f.rootMessagesPath,f.manifest.session_id),J=Xf(f.initialUsage,$);return this.withPersistedAggregateUsageFloor(J,f.manifest)}async summarizePersistedTeammateUsage(f,$,J){let W=zW($),H=`${J}.messages.json`,Q;try{Q=rD(f)}catch{return Vf()}let Z=Vf();for(let j of Q){if(!j.endsWith(".messages.json"))continue;if(j===H)continue;let X=zW(f,j);if(X===W)continue;let A=await N0(X);if(A.length===0)continue;Z=Xf(Z,r8(A))}return Z}withPersistedAggregateUsageFloor(f,$){let J=sD($.metadata?.aggregateUsage);if(J)return oD(f,J);let W=$.metadata?.aggregatedAgentsCost;if(typeof W!=="number"||!Number.isFinite(W)||W<=f.totalCost)return f;return{...f,totalCost:W}}emitStatus(f,$){this.emitSessionSnapshot(f),this.emit({type:"status",payload:{sessionId:f,status:$}})}async emitSessionSnapshot(f){let $=await this.getSession(f);if(!$)return;this.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:b0({session:$,messages:await this.readSessionMessages(f),usage:this.usageBySession.get(f),aggregateUsage:this.aggregateUsageBySession.get(f)})}})}emit(f){this.events.emit(f)}async listRows(f){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor(f)),Tj))}async getRow(f){let $=f.trim();if(!$)return;return(await this.listRows(Tj)).find((W)=>W.sessionId===$)}async readManifest(f){let $=f.trim();if(!$)return;return await this.invokeOptionalValue("readSessionManifest",$)}invoke(f,...$){return Kj(this.sessionService,f,...$)}invokeOptional(f,...$){return yj(this.sessionService,f,...$)}invokeOptionalValue(f,...$){return Uj(this.sessionService,f,...$)}}function eD(f){if(f.backendMode)return f.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let $=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if($==="local"||$==="hub"||$==="remote")return $;return"auto"}var j2,X2;function f_(f,$){if(f!=="auto"&&f!=="hub")return;if($.hub?.endpoint?.trim())return;A7($.hub?.workspaceRoot?.trim()||$.hub?.cwd?.trim()||process.cwd())}async function $_(f){await f.reconcileDeadSessions?.().catch(()=>{})}function _j(f){try{let $=new E0;return $.init(),new S0($,{messagesArtifactUploader:f.messagesArtifactUploader})}catch{return f.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new k5(void 0,{messagesArtifactUploader:f.messagesArtifactUploader})}}function Dj(f,$,J){return new g0({sessionService:J??f.sessionService??_j(f),capabilities:f.capabilities,telemetry:f.telemetry,toolPolicies:f.toolPolicies,distinctId:$,fetch:f.fetch})}async function J_(f){if(j2)return j2;if(X2)return await X2;return X2=(async()=>{return j2=_j(f),await $_(j2),j2})().finally(()=>{X2=void 0}),await X2}async function V4(f){let $=B$(f.distinctId);f.telemetry?.setDistinctId($);let J=eD(f);if(f_(J,f),J==="remote"){let W=f.remote?.endpoint?.trim();if(!W)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return f.logger?.log("Using remote runtime host",{endpoint:W}),new E8({endpoint:W,authToken:f.remote?.authToken,clientType:f.remote?.clientType,displayName:f.remote?.displayName,workspaceRoot:f.remote?.workspaceRoot,cwd:f.remote?.cwd,capabilities:f.capabilities})}if(J==="hub"){let W=f.hub?.endpoint?.trim(),H=W||await d1({strategy:f.hub?.strategy??"require-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(!H)throw Error("No compatible hub runtime is available.");return f.logger?.log("Using hub runtime host",{url:H,explicitEndpoint:W||void 0}),new P$({url:H,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd})}if(J==="auto"){let W=await F5({endpoint:f.hub?.endpoint,strategy:f.hub?.strategy??"prefer-hub",workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});if(W){f.logger?.log("Using discovered local hub runtime host",{url:W});let H=new P$({url:W,authToken:f.hub?.authToken,clientType:f.hub?.clientType,displayName:f.hub?.displayName,capabilities:f.capabilities},{workspaceRoot:f.hub?.workspaceRoot,cwd:f.hub?.cwd});try{return await H.connect(),H}catch(Q){f.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:Q})}}return f.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),Dj(f,$)}return Dj(f,$)}class NW{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor(f,$,J,W,H,Q,Z,j,X){this.clientName=$,this.runtimeAddress=J,this.host=f,this.prepare=W,this.capabilities=H,this.logger=Q,this.telemetry=Z,this.distinctId=j,this.settings=VQ(f),this.pendingPrompts=RQ(f),this.automation=new _6(()=>{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 k1({workspaceRoot:X.workspaceRoot??process.cwd(),specs:{cronSpecsDir:X.cronSpecsDir??X.cronDir,scope:nH(X.cronScope),workspaceRoot:X.workspaceRoot},runtimeHandlers:aH({host:f,getExtensionContext:()=>E2({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:X.dbPath,logger:X.logger,pollIntervalMs:X.pollIntervalMs,claimLeaseSeconds:X.claimLeaseSeconds,globalMaxConcurrency:X.globalMaxConcurrency,watcherDebounceMs:X.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((A)=>{if(A.type!=="ended")return;this.disposeSessionBootstrap(A.payload.sessionId)})}static async create(f={}){let $=Ff(f.capabilities),J=await V4({...f,capabilities:$}),W=iH(f.automation),H=new NW(J,f.clientName,J.runtimeAddress,f.prepare,$,f.logger,f.telemetry,f.distinctId,W?{...W,logger:f.logger}:void 0);if(W&&W.autoStart!==!1)await H.automation.start();return H}async disposeSessionBootstrap(f){let $=this.activeSessionBootstraps.get(f);if(!$)return;this.activeSessionBootstraps.delete(f),await Promise.resolve($.dispose?.())}async start(f){let $=FQ(f),J=await this.prepare?.($);try{let W=J?await J.applyToStartSessionInput($):$,H=await this.host.startSession(zJ(W,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>E2({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(H.sessionId))this.activeSessionBootstraps.set(H.sessionId,J);else await Promise.resolve(J.dispose?.());return KQ({input:W,sessionId:H.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),H}catch(W){throw await Promise.resolve(J?.dispose?.()),W}}send=(...f)=>this.host.runTurn(...f);getAccumulatedUsage=(...f)=>{return this.host.getAccumulatedUsage?.(...f)??Promise.resolve(void 0)};abort=(...f)=>this.host.abort(...f);stop=async(f)=>{await this.host.stopSession(f),await this.disposeSessionBootstrap(f)};dispose=async(...f)=>{try{await this.automationService?.dispose(),await this.host.dispose(...f)}finally{this.unsubscribeBootstrapCleanup();let $=[...this.activeSessionBootstraps.keys()];await Promise.allSettled($.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...f)=>this.host.getSession(...f);listHistory=async(f={})=>await Q5(this.host,f);list=async(f=200,$={})=>await this.listHistory({...$,limit:f});delete=async(f)=>{let $=await this.host.deleteSession(f);if($)await this.disposeSessionBootstrap(f);return $};update=(...f)=>this.host.updateSession(...f);readMessages=(...f)=>this.host.readSessionMessages(...f);async restore(f){let $=f.start?zJ(f.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>E2({automationService:this.automationService,automation:this.automation,context:J,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:f.sessionId,checkpointRunCount:f.checkpointRunCount,cwd:f.cwd,restore:f.restore,start:$})}ingestHookEvent=(...f)=>this.host.dispatchHookEvent(...f);subscribe(f,$){return this.host.subscribe(f,$)}updateSessionModel=(...f)=>{return this.host.updateSessionModel?.(...f)??Promise.resolve()}}import{HookEventNameSchema as Lj,HookEventPayloadSchema as hj,parseHookEventPayload as F4,resolveHookSessionContext as A_}from"@cline/shared";import{z as y$}from"zod";import{spawn as W_}from"node:child_process";import{augmentNodeCommandForDebug as H_,withResolvedClineBuildEnv as Q_}from"@cline/shared";function Z_(f){let $=f.trim();if(!$)return{};let W=$.split(`
|
|
694
|
+
`).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),H=W.length>0?W[W.length-1]:$;try{return{parsedJson:JSON.parse(H)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse subprocess stdout JSON"}}}function j_(f,$){let J=f instanceof Error?f:Error(String(f)),W=J,H=$.join(" ");if(W.code==="EACCES")return Error(`Failed to execute hook command "${H}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${H}": ${J.message}`)}async function X_(f,$){let J=f.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((W,H)=>{let Q=(Z)=>{J.off("error",Q);let j=Z.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){W();return}H(Z)};J.once("error",Q),J.end($,(Z)=>{if(J.off("error",Q),Z){let j=Z.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){W();return}H(Z);return}W()})})}async function R4(f,$){let J=H_($.command,{env:$.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!$.detached,H=W_(J[0],J.slice(1),{cwd:$.cwd,env:Q_($.env),stdio:W?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W}),Q=new Promise((Y)=>{H.once("spawn",()=>{try{$.onSpawn?.({command:J,pid:H.pid??void 0,detached:W})}catch{}Y()})}),Z=new Promise((Y,V)=>{H.once("error",(R)=>{V(j_(R,J))})});if(await X_(H,JSON.stringify(f)),W){await Promise.race([Q,Z]),H.unref();return}if(!H.stdout||!H.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let j="",X="",A=!1,P;H.stdout.on("data",(Y)=>{j+=Y.toString()}),H.stderr.on("data",(Y)=>{X+=Y.toString()});let B=new Promise((Y)=>{if(($.timeoutMs??0)>0)P=setTimeout(()=>{A=!0,H.kill("SIGKILL")},$.timeoutMs);H.once("close",(V)=>{if(P)clearTimeout(P);let{parsedJson:R,parseError:U}=Z_(j);Y({exitCode:V,stdout:j,stderr:X,parsedJson:R,parseError:U,timedOut:A})})});return await Promise.race([B,Z])}var P_=y$.object({contextModification:y$.string().optional(),cancel:y$.boolean().optional(),review:y$.boolean().optional(),errorMessage:y$.string().optional(),context:y$.string().optional(),overrideInput:y$.unknown().optional()}).passthrough();var B_=["agent","hook"];async function K4(f,$={}){let J=$.command??B_;return await R4(f,{command:J,cwd:$.cwd,env:$.env,detached:$.detached,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn})}function Oj(f){return f instanceof Error?f:Error(String(f))}function Y_(f){if(!f||typeof f!=="object")return;let $=P_.safeParse(f);if(!$.success)return;let J=$.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let H=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:H,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function Mj(f){if(!f||typeof f!=="object")return{};let $={};for(let[J,W]of Object.entries(f))if(typeof W==="string")$[J]=W;else $[J]=JSON.stringify(W);return $}function P0(f,$,J){let W=J.env??process.env,H=W.CLINE_USER_ID?.trim()||W.USER?.trim()||"unknown",Q=J.cwd||process.cwd();return{clineVersion:W.CLINE_VERSION?.trim()||"",hookName:f,timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:A_(J.sessionContext,{hookName:f,conversationId:$.conversationId,agentId:$.agentId,parentAgentId:$.parentAgentId}),workspaceRoots:Q?[Q]:[],workspaceInfo:J.workspaceInfo,userId:H,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function V_(f){return{name:f.name,message:f.message,stack:f.stack}}function R_(f){let $=String(f??"").toLowerCase();return $.includes("cancel")||$.includes("abort")||$.includes("interrupt")}function F_(f){return{agentId:f.snapshot.agentId,conversationId:f.snapshot.conversationId??f.snapshot.runId??f.snapshot.agentId,parentAgentId:f.snapshot.parentAgentId??null}}function K_(f){return f.filter(($)=>$.type==="text"&&typeof $.text==="string").map(($)=>$.text).join("")}function y_(f){return{id:f.toolCall.toolCallId,name:f.toolCall.toolName,input:f.input,output:f.result.output,error:f.result.isError?String(f.result.output):void 0,durationMs:f.durationMs,startedAt:f.startedAt,endedAt:f.endedAt}}function U_(f){if(!f)return;let $={};if(f.cancel===!0)$.stop=!0;if(f.overrideInput!==void 0)$.input=f.overrideInput;return Object.keys($).length>0?$:void 0}async function U$(f,$){try{let J=await K4(f,{command:$.command,cwd:$.cwd,env:$.env,detached:!0,onSpawn:$.onSpawn});$.onDispatch?.({payload:f,result:J,detached:!0})}catch(J){$.onDispatchError?.(Oj(J),f)}}function zj(f={}){return{hooks:{beforeRun:async(j)=>{let X=F_(j);if((f.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let P={...P0("agent_resume",X,f),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await U$(P,f)}else{let P={...P0("agent_start",X,f),hookName:"agent_start",taskStart:{taskMetadata:{}}};await U$(P,f)}return},beforeTool:async(j)=>{let X={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},A={...P0("tool_call",X,f),hookName:"tool_call",iteration:j.snapshot.iteration,tool_call:{id:j.toolCall.toolCallId,name:j.toolCall.toolName,input:j.input},preToolUse:{toolName:j.toolCall.toolName,parameters:Mj(j.input)}};try{let P=await K4(A,{command:f.command,cwd:f.cwd,env:f.env,detached:!1,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn});if(f.onDispatch?.({payload:A,result:P,detached:!1}),P?.timedOut)throw Error("tool_call hook command timed out");if(P?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${P.parseError}`);return U_(Y_(P?.parsedJson))}catch(P){f.onDispatchError?.(Oj(P),A);return}},afterTool:async(j)=>{let X=y_(j),A={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},P={...P0("tool_result",A,f),hookName:"tool_result",iteration:j.snapshot.iteration,tool_result:X,postToolUse:{toolName:X.name,parameters:Mj(X.input),result:typeof X.output==="string"?X.output:JSON.stringify(X.output),success:!X.error,executionTimeMs:X.durationMs}};await U$(P,f);return},afterRun:async({snapshot:j,result:X})=>{let A={agentId:j.agentId,conversationId:j.conversationId??j.runId??j.agentId,parentAgentId:j.parentAgentId??null};if(X.status==="completed"){let Y={...P0("agent_end",A,f),hookName:"agent_end",iteration:X.iterations,turn:{outputText:X.outputText,status:X.status},taskComplete:{taskMetadata:{}}};await U$(Y,f);return}let P=X.status==="aborted"||R_(X.error?.message)?"agent_abort":"agent_error",B=P==="agent_error"?{...P0(P,A,f),hookName:P,iteration:X.iterations,error:V_(X.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...P0(P,A,f),hookName:P,reason:X.error?.message,taskCancel:{taskMetadata:{}}};await U$(B,f)},onEvent:async(j)=>{if(j.type!=="message-added"||j.message.role!=="user")return;let X={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},A={...P0("prompt_submit",X,f),hookName:"prompt_submit",userPromptSubmit:{prompt:K_(j.message.content),attachments:[]}};await U$(A,f)}},shutdown:async({agentId:j,conversationId:X,parentAgentId:A,reason:P})=>{let B={...P0("session_shutdown",{agentId:j,conversationId:X,parentAgentId:A},f),hookName:"session_shutdown",reason:P};await U$(B,f)}}}import{createSessionId as G_}from"@cline/shared";function Sf(f,$){return{version:f.version,requestId:f.requestId,ok:!0,payload:$}}function Nj(f,$,J){return{version:f.version,requestId:f.requestId??G_("hubreq_"),ok:!1,error:{code:$,message:J}}}class y4{schedules;constructor(f){this.schedules=f}async handleCommand(f){try{switch(f.command){case"schedule.create":return Sf(f,{schedule:this.schedules.createSchedule(this.toCreateInput(f.payload??{}))});case"schedule.list":return Sf(f,{schedules:this.schedules.listSchedules({enabled:typeof f.payload?.enabled==="boolean"?f.payload.enabled:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0,tags:Array.isArray(f.payload?.tags)?f.payload?.tags:void 0})});case"schedule.get":return Sf(f,{schedule:this.schedules.getSchedule(String(f.payload?.scheduleId??""))});case"schedule.update":return Sf(f,{schedule:this.schedules.updateSchedule(String(f.payload?.scheduleId??""),this.toUpdateInput(f.payload??{}))});case"schedule.delete":return Sf(f,{deleted:this.schedules.deleteSchedule(String(f.payload?.scheduleId??""))});case"schedule.enable":return Sf(f,{schedule:this.schedules.resumeSchedule(String(f.payload?.scheduleId??""))});case"schedule.disable":return Sf(f,{schedule:this.schedules.pauseSchedule(String(f.payload?.scheduleId??""))});case"schedule.trigger":return Sf(f,{execution:await this.schedules.triggerScheduleNow(String(f.payload?.scheduleId??""))});case"schedule.list_executions":return Sf(f,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof f.payload?.scheduleId==="string"?f.payload.scheduleId:void 0,status:typeof f.payload?.status==="string"?f.payload.status:void 0,limit:typeof f.payload?.limit==="number"?f.payload.limit:void 0})});case"schedule.stats":return Sf(f,{stats:this.schedules.getScheduleStats(String(f.payload?.scheduleId??""))});case"schedule.active":return Sf(f,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return Sf(f,{runs:this.schedules.getUpcomingRuns(typeof f.payload?.limit==="number"?f.payload.limit:void 0)});default:return Nj(f,"unsupported_command",`Unsupported hub schedule command: ${f.command}`)}}catch($){return Nj(f,"schedule_command_failed",$ instanceof Error?$.message:String($))}}toCreateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider&&f.model?{providerId:String(f.provider),modelId:String(f.model)}:void 0;return{...f,modelSelection:$}}toUpdateInput(f){let $=f.modelSelection&&typeof f.modelSelection==="object"&&!Array.isArray(f.modelSelection)?f.modelSelection:f.provider||f.model?{providerId:typeof f.provider==="string"?f.provider:"",modelId:typeof f.model==="string"?f.model:""}:void 0;return{...f,modelSelection:$}}}function G4(f){return f?new Date(f).getTime():void 0}function T_(f){let $=f.metadata?{...f.metadata}:void 0;if($)delete $.__hubScheduleCreatedBy,delete $.__hubScheduleCwd,delete $.__hubRuntimeOptions;return $}function U4(f){let $=f.metadata;return{scheduleId:f.externalId,name:f.title,cronPattern:f.scheduleExpr??"",prompt:f.prompt??"",workspaceRoot:f.workspaceRoot??"",cwd:typeof $?.__hubScheduleCwd==="string"?$.__hubScheduleCwd:void 0,modelSelection:f.providerId||f.modelId?{providerId:f.providerId??"",modelId:f.modelId??""}:void 0,enabled:f.enabled&&!f.removed&&f.parseStatus==="valid",mode:f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act",systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,maxParallel:f.maxParallel??1,createdAt:new Date(f.createdAt).getTime(),updatedAt:new Date(f.updatedAt).getTime(),nextRunAt:G4(f.nextRunAt),lastRunAt:G4(f.lastRunAt),createdBy:typeof $?.__hubScheduleCreatedBy==="string"?$.__hubScheduleCreatedBy:void 0,tags:f.tags,runtimeOptions:$?.__hubRuntimeOptions&&typeof $.__hubRuntimeOptions==="object"&&!Array.isArray($.__hubRuntimeOptions)?$.__hubRuntimeOptions:void 0,metadata:T_(f)}}function D_(f){switch(f){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function qj(f,$){return{executionId:f.runId,scheduleId:$,sessionId:f.sessionId,triggeredAt:new Date(f.scheduledFor??f.createdAt).getTime(),startedAt:G4(f.startedAt),endedAt:G4(f.completedAt),status:D_(f.status),errorMessage:f.error}}class T4{store;materializer;runner;started=!1;disposed=!1;constructor(f){this.store=new S1({dbPath:f.dbPath}),this.materializer=new q1({store:this.store}),this.runner=new w1({store:this.store,materializer:this.materializer,runtimeHandlers:f.runtimeHandlers,workspaceRoot:"",logger:f.logger,pollIntervalMs:f.pollIntervalMs,claimLeaseSeconds:f.claimLeaseSeconds,globalMaxConcurrency:f.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule(f){if(xJ(f.cronPattern),!f.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return U4(this.store.createHubSchedule(f))}getSchedule(f){let $=this.store.getHubSchedule(f);return $?U4($):void 0}listSchedules(f={}){return this.store.listHubSchedules(f).map(($)=>U4($))}updateSchedule(f,$){if($.cronPattern!==void 0)xJ($.cronPattern);let J=this.store.getHubSchedule(f);if(!J)return;let W=$.workspaceRoot!==void 0?$.workspaceRoot.trim():J.workspaceRoot;if(($.enabled??J.enabled)&&!W)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule(f,{...$,scheduleId:f});return Q?U4(Q):void 0}deleteSchedule(f){return this.store.deleteHubSchedule(f)}pauseSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!1})}resumeSchedule(f){return this.updateSchedule(f,{scheduleId:f,enabled:!0})}async triggerScheduleNow(f){let $=this.store.enqueueHubScheduleRun(f,"manual");if(!$)return;await this.runner.tick();let J=this.store.getRun($.runId)??$;return qj(J,f)}listScheduleExecutions(f){let $=f.scheduleId?this.store.getHubSchedule(f.scheduleId):void 0,J={specId:$?.specId,limit:f.limit};return this.store.listRuns(J).map((H)=>{let Q=$??this.store.getSpec(H.specId);if(!Q||Q.source!=="hub-schedule")return;return qj(H,Q.externalId)}).filter((H)=>{if(!H)return!1;return!f.status||H.status===f.status})}getScheduleStats(f){let $=this.listScheduleExecutions({scheduleId:f,limit:1e4});if($.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,W=0,H=0,Q;for(let Z of $){if(Z.status==="success"||Z.status==="completed")J+=1;if(!Q&&Z.status!=="success"&&Z.status!=="completed")Q=Z;if(Z.startedAt&&Z.endedAt)H+=Z.endedAt-Z.startedAt,W+=1}return{totalRuns:$.length,successRate:J/$.length,avgDurationSeconds:W>0?H/W/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap((f)=>{let $=this.store.getSpec(f.specId);if(!$||$.source!=="hub-schedule"||!f.sessionId)return[];return[{executionId:f.runId,scheduleId:$.externalId,sessionId:f.sessionId,startedAt:f.startedAt??new Date().toISOString(),timeoutAt:$.timeoutSeconds&&f.startedAt?new Date(new Date(f.startedAt).getTime()+$.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns(f=20){let $={triggerKind:"schedule",enabled:!0,limit:f};return this.store.listSpecs($).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,W)=>String(J.nextRunAt).localeCompare(String(W.nextRunAt))).slice(0,f).map(({spec:J,nextRunAt:W})=>({scheduleId:J.externalId,name:J.title,nextRunAt:W}))}}L4();function r_(f,$){if(f instanceof Error)return f;if(f&&typeof f==="object"&&"message"in f&&typeof f.message==="string"&&f.message.trim())return Error(f.message.trim());let J=f&&typeof f==="object"&&"type"in f&&typeof f.type==="string"?f.type.trim():"";return Error(J?`Failed to connect to hub at ${$} (${J} event before socket open).`:`Failed to connect to hub at ${$}.`)}var l_="cline-hub-auth.";function p_(f){return f.host!==void 0||f.port!==void 0||f.pathname!==void 0}function i_(f,$){let J=new URL(f),W=new URL($);return J.search="",J.hash="",W.search="",W.hash="",J.toString()===W.toString()}async function n_(f){let $=f.searchParams.get("authToken")?.trim();if(f.searchParams.delete("authToken"),$)return $;let J=yf(),W=await Yf(J.discoveryPath);if(W?.url&&i_(f.toString(),W.url))return W.authToken;return}async function a_(f={}){let $=q0(f);if(!p_(f)){let J=yf(),W=await Yf(J.discoveryPath);if(W?.url)return W.url}return Q0($.host,$.port,$.pathname)}async function Cj(f){return await new Promise(($,J)=>{(async()=>{let W=new URL(f),H=await n_(W);W.hash="";let Q=new WebSocket(W.toString(),H?[`${l_}${H}`]:void 0),Z=new Map,j=0;Q.addEventListener("open",()=>{$({send(X){let A=X.requestId??`hub-client-${++j}`;return new Promise((P,B)=>{Z.set(A,{resolve:P,reject:B});let Y={kind:"command",envelope:{...X,requestId:A}};Q.send(JSON.stringify(Y))})},close(){Q.close()}})}),Q.addEventListener("message",(X)=>{let A=JSON.parse(String(X.data));if(A.kind==="reply"&&A.envelope.requestId){let P=Z.get(A.envelope.requestId);if(P)Z.delete(A.envelope.requestId),P.resolve(A.envelope)}}),Q.addEventListener("close",()=>{for(let X of Z.values())X.reject(Error("Hub connection closed"));Z.clear()}),Q.addEventListener("error",(X)=>{J(r_(X,f))})})().catch(J)})}async function pm(f){try{return(await Cj(f)).close(),!0}catch{return!1}}async function im(f,$){let J=await a_(f),W=await Cj(J);try{return await W.send({version:$.version??"v1",clientId:$.clientId??"hub-client",...$})}finally{W.close()}}function vf(f){return f?JSON.parse(JSON.stringify(f)):{}}function h4(f){let $=f?.session&&typeof f.session==="object"?f.session:void 0;if(!$)return;let J=$.metadata&&typeof $.metadata==="object"?vf($.metadata):void 0;return{sessionId:typeof $.sessionId==="string"?$.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function Ej(f,$){return f.error?.message??`hub command failed: ${$}`}function t_(f){let $=vf(f);if(typeof $.error==="string"&&$.error.trim())return{...$,error:$.error.trim()};let J=$.result&&typeof $.result==="object"?$.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...$,error:J.text.trim()};let W=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof W?.message==="string"&&W.message.trim())return{...$,error:W.message.trim()};return $}function s_(f){let $=f?.checkpoint;if(!$||typeof $!=="object"||Array.isArray($))throw Error("hub checkpoint restore returned no checkpoint");let J=$;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function o_(f){let $=f.sessionId?.trim();if(!$)return;switch(f.event){case"iteration.started":return{sessionId:$,eventType:"runtime.chat.iteration_start",payload:vf(f.payload)};case"iteration.finished":return{sessionId:$,eventType:"runtime.chat.iteration_end",payload:vf(f.payload)};case"assistant.delta":return{sessionId:$,eventType:"runtime.chat.text_delta",payload:vf(f.payload)};case"usage.updated":return{sessionId:$,eventType:"runtime.chat.usage",payload:vf(f.payload)};case"tool.started":return{sessionId:$,eventType:"runtime.chat.tool_call_start",payload:vf(f.payload)};case"tool.finished":return{sessionId:$,eventType:"runtime.chat.tool_call_end",payload:vf(f.payload)};case"approval.requested":return{sessionId:$,eventType:"approval.requested",payload:vf(f.payload)};case"run.aborted":return{sessionId:$,eventType:"runtime.chat.aborted",payload:vf(f.payload)};case"run.failed":return{sessionId:$,eventType:"runtime.chat.failed",payload:t_(f.payload)};case"run.completed":return{sessionId:$,eventType:"runtime.chat.completed",payload:vf(f.payload)};default:return}}class e_{options;client;metadataApplied=!1;constructor(f){this.options=f;this.client=new Z0({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-session-client",displayName:f.displayName??"hub session client",workspaceRoot:f.workspaceRoot,cwd:f.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.create",{workspaceRoot:f.workspaceRoot,cwd:f.cwd,sessionConfig:{providerId:f.provider,modelId:f.model,apiKey:f.apiKey,cwd:f.cwd??f.workspaceRoot,workspaceRoot:f.workspaceRoot,systemPrompt:f.systemPrompt??"",mode:f.mode??"act",rules:f.rules,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawnAgent:f.enableSpawn!==!1,enableAgentTeams:f.enableTeams!==!1,disableMcpSettingsTools:f.disableMcpSettingsTools,missionLogIntervalSteps:f.missionStepInterval,missionLogIntervalMs:f.missionTimeIntervalMs},metadata:{source:f.source??"cli",provider:f.provider,model:f.model,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,prompt:void 0,interactive:f.interactive!==!1},runtimeOptions:{mode:f.mode,systemPrompt:f.systemPrompt,maxIterations:f.maxIterations,timeoutSeconds:f.timeoutSeconds,enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,autoApproveTools:f.autoApproveTools,toolExecutors:f.toolExecutors,configExtensions:f.configExtensions},modelSelection:{provider:f.provider,model:f.model,apiKey:f.apiKey},toolPolicies:f.toolPolicies}),J=h4($.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession(f,$,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:$.prompt,attachments:$.attachments,delivery:$.delivery,timeoutSeconds:$.config.timeoutSeconds},f,J)).payload?.result}}async stopRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:f},f),{applied:!0}}async abortRuntimeSession(f){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:f},f),{applied:!0}}async updateSession(f){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:f.sessionId,metadata:f.metadata},f.sessionId),{updated:!0}}async getSession(f){await this.ensureMetadataApplied();let $=await this.client.command("session.get",void 0,f);return h4($.payload)}async readMessages(f){let $=f.trim();if(!$)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:$},$);if(!J.ok)throw Error(Ej(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async restore(f){let $=f.sessionId.trim();if(!$)throw Error("sessionId is required");let J=f.restore?.messages!==!1;if(J&&!f.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let W=f.config,H=await this.client.command("session.restore",{sessionId:$,checkpointRunCount:f.checkpointRunCount,restore:f.restore,...W?{workspaceRoot:W.workspaceRoot,cwd:W.cwd,sessionConfig:{providerId:W.provider,modelId:W.model,apiKey:W.apiKey,cwd:W.cwd??W.workspaceRoot,workspaceRoot:W.workspaceRoot,systemPrompt:W.systemPrompt??"",mode:W.mode??"act",rules:W.rules,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawnAgent:W.enableSpawn!==!1,enableAgentTeams:W.enableTeams!==!1,disableMcpSettingsTools:W.disableMcpSettingsTools,missionLogIntervalSteps:W.missionStepInterval,missionLogIntervalMs:W.missionTimeIntervalMs},metadata:{source:W.source??"cli",provider:W.provider,model:W.model,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,prompt:void 0,interactive:W.interactive!==!1},runtimeOptions:{mode:W.mode,systemPrompt:W.systemPrompt,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,autoApproveTools:W.autoApproveTools,configExtensions:W.configExtensions},modelSelection:{provider:W.provider,model:W.model,apiKey:W.apiKey},toolPolicies:W.toolPolicies}:{}},$);if(!H.ok)throw Error(Ej(H,"session.restore"));let Q=h4(H.payload);if(J&&!Q?.sessionId)throw Error("hub checkpoint restore returned no session id");let Z=Array.isArray(H.payload?.messages)?H.payload.messages:void 0,j=s_(H.payload);return{sessionId:Q?.sessionId,startResult:Q?.sessionId?{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}:void 0,...Z?{messages:Z}:{},checkpoint:j}}async listSessions(f){await this.ensureMetadataApplied();let $=await this.client.command("session.list",{limit:f?.limit??200});return(Array.isArray($.payload?.sessions)?$.payload?.sessions:[]).map((W)=>h4({session:W})).filter((W)=>Boolean(W?.sessionId))}async deleteSession(f,$=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:f,deleteCheckpointRefs:$})).payload?.deleted===!0}async respondToolApproval(f){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:f.approvalId,approved:f.approved,payload:f.reason?{reason:f.reason}:void 0,responderClientId:f.responderClientId})}streamEvents(f,$){let J=new Set((f.sessionIds??[]).map((H)=>H.trim()).filter(Boolean)),W=this.client.subscribe((H)=>{let Q=o_(H);if(!Q)return;if(J.size>0&&!J.has(Q.sessionId))return;$.onEvent?.(Q)});return this.ensureMetadataApplied().catch((H)=>{$.onError?.(H instanceof Error?H:Error(String(H)))}),W}streamTeamProgress(f,$){let J=this.client.subscribe((W)=>{if(W.event!=="team.progress"||!W.payload)return;$.onProjection?.(W.payload)});return this.ensureMetadataApplied().catch((W)=>{$.onError?.(W instanceof Error?W:Error(String(W)))}),J}async createSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",f)).payload?.schedule}async listSchedules(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.list");return Array.isArray($.payload?.schedules)?$.payload?.schedules:[]}async getSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:f})).payload?.schedule}async updateSchedule(f,$){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:f,...$})).payload?.schedule}async pauseSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:f})).payload?.schedule}async resumeSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:f})).payload?.schedule}async deleteSchedule(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:f})).payload?.deleted===!0}async triggerScheduleNow(f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:f})).payload?.execution}async listScheduleExecutions(f,$){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:f,limit:$});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let f=await this.client.command("schedule.active");return Array.isArray(f.payload?.executions)?f.payload?.executions:[]}async getUpcomingScheduledRuns(f){await this.ensureMetadataApplied();let $=await this.client.command("schedule.upcoming",{limit:f});return Array.isArray($.payload?.upcoming)?$.payload?.upcoming:[]}}class fM{client;constructor(f){this.client=new Z0({url:f.address,authToken:f.authToken,clientId:f.clientId,clientType:f.clientType??"hub-ui-client",displayName:f.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify(f){await this.client.command("ui.notify",f)}async sendShowWindow(f){await this.client.command("ui.show_window",f??{})}async listClients(){let f=await this.client.command("client.list");return Array.isArray(f.payload?.clients)?f.payload.clients:[]}async listSessions(f=200){let $=await this.client.command("session.list",{limit:f});return Array.isArray($.payload?.sessions)?$.payload.sessions:[]}subscribeUI(f){return this.client.subscribe(($)=>{switch($.event){case"ui.notify":f.onNotify?.($.payload);break;case"ui.show_window":f.onShowWindow?.($.payload);break;case"hub.client.registered":f.onClientRegistered?.($.payload??{});break;case"hub.client.disconnected":f.onClientDisconnected?.($.payload??{});break;case"session.created":f.onSessionCreated?.($.payload??{});break;case"session.updated":f.onSessionUpdated?.($.payload??{});break;case"session.detached":f.onSessionDetached?.($.payload??{});break}})}}import{normalizeProviderId as $M}from"@cline/llms";function JM(f){return{text:f.text,usage:f.usage,inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,iterations:f.iterations,finishReason:f.finishReason,toolCalls:f.toolCalls.map(($)=>({name:$.name,input:$.input,output:$.output,error:$.error,durationMs:$.durationMs}))}}function WM(f){return f.mode==="plan"?"plan":f.mode==="yolo"?"yolo":"act"}function Hx(f={}){let $=new g0({sessionService:new S0(new E0),fetch:f.fetch,telemetry:f.telemetry});return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),H=await $.startSession({source:J.source?.trim()||Rf.CLI,interactive:!1,config:{providerId:$M(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:WM(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:H.sessionId,startResult:{sessionId:H.sessionId,manifestPath:H.manifestPath,messagesPath:H.messagesPath}}},async sendSession(J,W){let H=await $.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content)});if(!H)throw Error("local hub schedule runtime returned no turn result");return{result:JM(H)}},async abortSession(J){return await $.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await $.stopSession(J),{applied:!0}}}}function HM(f){if(typeof f==="string")return f.trim()||void 0;if(!Array.isArray(f))return;return f.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
|
|
695
|
+
`).trim()||void 0}var Sj=120,CW="...";function EW(f){let $=f.trim();if(!$)return"";if(Buffer.byteLength($,"utf8")<=Sj)return $;let J=Sj-Buffer.byteLength(CW,"utf8");if(J<=0)return CW;let W="";for(let H of $){if(Buffer.byteLength(W+H,"utf8")>J)break;W+=H}return`${W}${CW}`}async function kj(f){let $=f?.sessionId?.trim()||"unknown",J=typeof f?.metadata?.messagesPath==="string"?f.metadata.messagesPath:void 0,H=[...await N0(J)].reverse().find((X)=>X.role==="assistant"),Q=H?HM(H.content):void 0,Z=f?.workspaceRoot?.trim()||"workspace",j=typeof f?.metadata?.prompt==="string"?f.metadata.prompt.trim():Z;return{title:`Task completed (${$})`,body:EW(Q&&Q.length>0?Q:j.length>0?j:Z),severity:"info"}}import{createSessionId as CM}from"@cline/shared";import{createSessionId as XM}from"@cline/shared";import{createSessionId as jM}from"@cline/shared";function QM(f){switch(f){case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function ZM(f){let $=f.metadata&&typeof f.metadata==="object"?JSON.parse(JSON.stringify(f.metadata)):{};if(f.parentSessionId?.trim())$.parentSessionId=f.parentSessionId;if(f.parentAgentId?.trim())$.parentAgentId=f.parentAgentId;if(f.agentId?.trim())$.agentId=f.agentId;if(f.conversationId?.trim())$.conversationId=f.conversationId;if(f.messagesPath?.trim())$.messagesPath=f.messagesPath;if(f.prompt?.trim())$.prompt=f.prompt;if(f.provider?.trim())$.provider=f.provider;if(f.model?.trim())$.model=f.model;if(f.source?.trim())$.source=f.source;if(typeof f.pid==="number")$.pid=f.pid;return Object.keys($).length>0?$:void 0}function O4(f,$,J,W){return{sessionId:f.sessionId,workspaceRoot:f.workspaceRoot,cwd:f.cwd,createdAt:Date.parse(f.startedAt),updatedAt:Date.parse(f.updatedAt),createdByClientId:$?.createdByClientId??"hub",status:QM(f.status),participants:$?[...$.participants.values()]:[],metadata:ZM(f),runtimeOptions:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams,mode:typeof f.metadata?.mode==="string"?f.metadata.mode:void 0,systemPrompt:typeof f.metadata?.systemPrompt==="string"?f.metadata.systemPrompt:void 0},runtimeSession:f.agentId?{agentId:f.agentId,team:f.teamName?{teamId:f.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...W?{aggregateUsage:{...W}}:{}}}function m(f,$){return{version:f.version,requestId:f.requestId,ok:!0,...$!==void 0?{payload:$}:{}}}function S(f,$,J){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:$,message:J}}}function z4(f){return f&&typeof f==="object"&&!Array.isArray(f)?f:void 0}function Mf(f){if(typeof f.payload?.sessionId==="string")return f.payload.sessionId.trim();return f.sessionId?.trim()??""}function T$(f,$,J){return{version:"v1",event:f,eventId:jM("hevt_"),sessionId:J,timestamp:Date.now(),payload:$}}async function kf(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let W=await f.sessionHost.getAccumulatedUsage?.($);return O4(J,f.sessionState.get($),W?.usage,W?.aggregateUsage)}async function If(f,$){let J=await f.sessionHost.getSession($);if(!J)return;let[W,H]=await Promise.all([typeof f.sessionHost.readSessionMessages==="function"?f.sessionHost.readSessionMessages($):[],f.sessionHost.getAccumulatedUsage?.($)]);return b0({session:J,messages:W,usage:H?.usage,aggregateUsage:H?.aggregateUsage})}function N4(f,$,J,W,H={}){let Q=f.sessionState.get($);if(Q){if(H.interactive!==void 0)Q.interactive=H.interactive;if(!Q.participants.has(J))Q.participants.set(J,{clientId:J,attachedAt:Date.now(),role:W});return Q}let Z={createdByClientId:J,interactive:H.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:W}]])};return f.sessionState.set($,Z),Z}async function SW(f,$){let J=XM("approval_"),W=$.sessionId;if(f.sessionState.get(W)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((Q)=>{f.pendingApprovals.set(J,{sessionId:W,resolve:Q}),f.publish(f.buildEvent("approval.requested",{approvalId:J,sessionId:$.sessionId,agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,toolCallId:$.toolCallId,toolName:$.toolName,inputJson:JSON.stringify($.input??null),policy:$.policy},W))})}function kW(f,$,J){let W=f.pendingApprovals.get($);if(!W)return;return f.pendingApprovals.delete($),W.resolve(J),{sessionId:W.sessionId}}function IW(f,$,J){let W=0;for(let[H,Q]of[...f.pendingApprovals.entries()]){if(!$({approvalId:H,sessionId:Q.sessionId}))continue;f.pendingApprovals.delete(H),Q.resolve({approved:!1,reason:J}),f.publish(f.buildEvent("approval.resolved",{approvalId:H,approved:!1,cancelled:!0,reason:J},Q.sessionId)),W+=1}return W}async function Ij(f,$){let J=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"";if(!f.pendingApprovals.get(J))return S($,"approval_not_found",`Unknown approval: ${J}`);let H=typeof $.payload?.reason==="string"?$.payload.reason:$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)&&typeof $.payload.payload.reason==="string"?$.payload.payload.reason:void 0,Q=$.payload?.approved===!0,Z=kW(f,J,{approved:Q,reason:H});if(!Z)return S($,"approval_not_found",`Unknown approval: ${J}`);return f.publish(f.buildEvent("approval.resolved",{approvalId:J,approved:Q,reason:H},Z.sessionId)),m($,{approvalId:J,approved:Q})}import{createSessionId as BM}from"@cline/shared";function AM(f){if(f instanceof Error)return{name:f.name,message:f.message,stack:f.stack};if(f===void 0)return;return f}var mj={debug:10,info:20,warn:30,error:40,silent:50};function PM(){let f=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if(f==="debug"||f==="info"||f==="warn"||f==="error"||f==="silent")return f;return process.env.VITEST?"error":"info"}function I(f,$,J={}){if(mj[f]<mj[PM()])return;let W=JSON.stringify({ts:new Date().toISOString(),level:f,component:"hub",message:$,...Object.fromEntries(Object.entries(J).map(([H,Q])=>[H,AM(Q)]).filter(([,H])=>H!==void 0))});if(f==="error"||f==="warn"){console.error(`[hub] ${W}`);return}console.log(`[hub] ${W}`)}function mW(f,$){let J=$ instanceof Error?$.stack||$.message:String($);I("error",f,{error:J})}async function xj(f,$,J,W,H,Q){let Z=BM("capreq_"),j=performance.now();return I("info","capability.request.start",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H}),await new Promise((X,A)=>{f.pendingCapabilityRequests.set(Z,{sessionId:$,targetClientId:H,capabilityName:J,onProgress:Q,resolve:(P)=>{if(I(P.ok?"info":"warn","capability.request.end",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H,ok:P.ok,error:P.error,durationMs:Math.round(performance.now()-j)}),!P.ok){A(Error(P.error||`Capability ${J} was rejected by ${H}.`));return}X(P.payload)}}),f.publish(f.buildEvent("capability.requested",{requestId:Z,targetClientId:H,capabilityName:J,payload:W},$)),I("info","capability.request.published",{requestId:Z,sessionId:$,capabilityName:J,targetClientId:H})})}function gj(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",W=f.pendingCapabilityRequests.get(J);if(!W)return S($,"capability_not_found",`Unknown capability request: ${J}`);if(($.clientId?.trim()||"")!==W.targetClientId)return S($,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==W.sessionId)return S($,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{};return W.onProgress?.(Q),m($,{requestId:J})}function v0(f,$,J){let W=0;for(let[H,Q]of[...f.pendingCapabilityRequests.entries()]){if(!$({requestId:H,...Q}))continue;f.pendingCapabilityRequests.delete(H),I("warn","capability.request.cancelled",{requestId:H,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,reason:J}),Q.resolve({ok:!1,error:J}),f.publish(f.buildEvent("capability.resolved",{requestId:H,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,ok:!1,cancelled:!0,error:J},Q.sessionId)),W+=1}return W}async function vj(f,$){let J=typeof $.payload?.sessionId==="string"?$.payload.sessionId.trim():$.sessionId?.trim()||"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName.trim():"",H=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId.trim():"";if(!J||!W||!H)return S($,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},Z=await f.requestCapability(J,W,Q,H);return m($,Z)}catch(Q){return S($,"capability_request_failed",Q instanceof Error?Q.message:String(Q))}}function uj(f,$){let J=typeof $.payload?.requestId==="string"?$.payload.requestId.trim():"",W=f.pendingCapabilityRequests.get(J);if(!W)return S($,"capability_not_found",`Unknown capability request: ${J}`);let H=$.clientId?.trim()||"";if(H!==W.targetClientId)return S($,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if($.sessionId?.trim()&&$.sessionId.trim()!==W.sessionId)return S($,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);f.pendingCapabilityRequests.delete(J);let Q=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:void 0,Z=typeof $.payload?.error==="string"?$.payload.error:void 0,j=$.payload?.ok===!0;return I(j?"info":"warn","capability.respond",{requestId:J,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:H,ok:j,error:Z}),W.resolve({ok:j,payload:Q,error:Z}),f.publish(f.buildEvent("capability.resolved",{requestId:J,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:H,ok:j,payload:Q,error:Z},W.sessionId)),m($,{requestId:J,ok:j})}import{createSessionId as YM}from"@cline/shared";function cj(f,$){let J=$.payload,W=J?.clientId?.trim()||$.clientId?.trim()||YM("client_");return f.clients.set(W,{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),f.publish(f.buildEvent("hub.client.registered",{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),m($,{clientId:W})}function dj(f,$){let J=$.clientId?.trim(),W=J?f.clients.get(J):void 0;if(!J||!W)return S($,"client_not_found","Client is not registered with this hub.");let H=z4($.payload?.metadata);if(W.lastSeenAt=Date.now(),H)W.metadata=JSON.parse(JSON.stringify(H));return m($)}function rj(f,$,J){let W=$.clientId?.trim();if(W)f.clients.delete(W),J(W),f.publish(f.buildEvent("hub.client.disconnected",{clientId:W}));return m($)}function lj(f,$){return m($,{clients:[...f.clients.values()]})}var VM=30000;function RM(f){if(f==="aborted")return"run.aborted";if(f==="error"||f==="failed")return"run.failed";return"run.completed"}function FM(f){if(f.finishReason!=="error")return;return f.text.trim()||void 0}function KM(f){let $=typeof f.timeoutMs==="number"?f.timeoutMs:typeof f.timeout_ms==="number"?f.timeout_ms:void 0;if($&&Number.isFinite($)&&$>0)return Math.floor($);let J=typeof f.timeoutSeconds==="number"?f.timeoutSeconds:typeof f.timeout_seconds==="number"?f.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function yM(f,$,J,W){let H=performance.now(),Q=!1,Z={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:J.sessionId,timeoutMs:W},j=setInterval(()=>{if(Q)return;let P=Math.round(performance.now()-H);I("warn","run.heartbeat",{...Z,elapsedMs:P}),f.publish(f.buildEvent("run.heartbeat",{requestId:$.requestId,elapsedMs:P,...W?{timeoutMs:W}:{}},J.sessionId))},VM),X=f.sessionHost.runTurn(J);X.then((P)=>{if(!Q)return;I("warn","run.late_end",{...Z,elapsedMs:Math.round(performance.now()-H),finishReason:P?.finishReason})},(P)=>{if(!Q)return;I("error","run.late_error",{...Z,elapsedMs:Math.round(performance.now()-H),error:P})});let A;try{if(!W)return await X;return await Promise.race([X,new Promise((P,B)=>{A=setTimeout(()=>{let Y=`Hub run ${$.command} timed out after ${W}ms.`;Q=!0,clearInterval(j),B(Error(Y)),I("error","run.timeout",{...Z,elapsedMs:Math.round(performance.now()-H)}),IW(f,(V)=>V.sessionId===J.sessionId,Y),v0(f,(V)=>V.sessionId===J.sessionId,Y),f.sessionHost.abort(J.sessionId,Y).catch((V)=>{I("error","run.timeout_abort_failed",{...Z,error:V})})},W)})])}finally{if(Q=!0,clearInterval(j),A)clearTimeout(A)}}async function pj(f,$){let J=Mf($),W=$.payload&&typeof $.payload==="object"?$.payload:{},H=typeof W.prompt==="string"?W.prompt:typeof W.input==="string"?W.input:"";if(!H.trim())return S($,"invalid_session_input","session input requires a prompt string");f.publish(f.buildEvent("run.started",void 0,J));let Q=W.attachments&&typeof W.attachments==="object"&&!Array.isArray(W.attachments)?W.attachments:void 0,Z=Array.isArray(Q?.userFiles)?Q.userFiles.filter((P)=>typeof P==="string"):void 0,j=KM(W);f.suppressNextTerminalEventBySession.set(J,"run.start.reply");let X;try{X=await yM(f,$,{sessionId:J,prompt:H,delivery:W.delivery==="queue"||W.delivery==="steer"?W.delivery:void 0,userImages:Array.isArray(Q?.userImages)?Q.userImages:void 0,userFiles:Z,timeoutMs:j},j)}catch(P){if(f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J);throw f.publish(f.buildEvent("run.failed",{reason:"error",error:P instanceof Error?P.message:String(P)},J)),P}if(X){let P=await If(f,J),B=FM(X);if(f.publish(f.buildEvent(RM(X.finishReason),{reason:X.finishReason,...B?{error:B}:{},result:X,...P?{snapshot:P}:{}},J)),f.suppressNextTerminalEventBySession.get(J)==="run.start.reply")f.suppressNextTerminalEventBySession.delete(J)}else f.suppressNextTerminalEventBySession.delete(J);let A=await If(f,J);return m($,X||A?{...X?{result:X}:{},...A?{snapshot:A}:{}}:void 0)}async function ij(f,$){let J=Mf($),W=typeof $.payload?.reason==="string"?$.payload.reason:"Run was aborted before pending approval or capability request was resolved.";return IW(f,(H)=>H.sessionId===J,W),await f.sessionHost.abort(J,$.payload?.reason),v0(f,(H)=>H.sessionId===J,W),f.publish(f.buildEvent("run.aborted",{reason:W},J)),m($,{applied:!0})}async function nj(f,$){let J=F4($.payload?.payload);if(!J)return S($,"invalid_hook_payload","session.hook requires a valid hook event payload");return await f.sessionHost.dispatchHookEvent(J),m($,{applied:!0})}async function aj(f,$){switch($.type){case"chunk":return;case"agent_event":await UM(f,$);return;case"hook":if($.payload.hookEventName==="tool_call")f.publish(f.buildEvent("tool.started",{toolName:$.payload.toolName},$.payload.sessionId));else if($.payload.hookEventName==="tool_result")f.publish(f.buildEvent("tool.finished",{toolName:$.payload.toolName},$.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:$.payload.sessionId,summary:$.payload.summary,lastEvent:$.payload.lifecycle};f.publish(f.buildEvent("team.progress",J,$.payload.sessionId));return}case"pending_prompts":f.publish(f.buildEvent("session.pending_prompts",{sessionId:$.payload.sessionId,prompts:$.payload.prompts},$.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:$.payload.id,prompt:$.payload.prompt,delivery:$.payload.delivery,attachmentCount:$.payload.attachmentCount};f.publish(f.buildEvent("session.pending_prompt_submitted",{sessionId:$.payload.sessionId,prompt:J},$.payload.sessionId));return}case"session_snapshot":f.publish(f.buildEvent("session.updated",{sessionId:$.payload.sessionId,snapshot:$.payload.snapshot},$.payload.sessionId));return;case"status":{let[J,W]=await Promise.all([kf(f,$.payload.sessionId),If(f,$.payload.sessionId)]);if(J)f.publish(f.buildEvent("session.updated",{session:J,...W?{snapshot:W}:{}},$.payload.sessionId));return}case"ended":await GM(f,$);return;default:return}}async function UM(f,$){let{sessionId:J,event:W}=$.payload;if(W.type==="iteration_start"){f.publish(f.buildEvent("iteration.started",{iteration:W.iteration},J));return}if(W.type==="iteration_end"){f.publish(f.buildEvent("iteration.finished",{iteration:W.iteration,hadToolCalls:W.hadToolCalls,toolCallCount:W.toolCallCount},J));return}if(W.type==="content_start"){if(W.contentType==="text"&&typeof W.text==="string"&&W.text.length>0){f.publish(f.buildEvent("assistant.delta",{text:W.text},J));return}if(W.contentType==="reasoning"){if(W.redacted&&!W.reasoning){f.publish(f.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof W.reasoning==="string"&&W.reasoning.length>0)f.publish(f.buildEvent("reasoning.delta",{text:W.reasoning,redacted:W.redacted===!0},J));return}if(W.contentType==="tool"){f.publish(f.buildEvent("tool.started",{toolCallId:W.toolCallId,toolName:W.toolName,input:W.input},J));return}}if(W.type==="content_end"){switch(W.contentType){case"text":f.publish(f.buildEvent("assistant.finished",{text:W.text},J));break;case"reasoning":f.publish(f.buildEvent("reasoning.finished",{reasoning:W.reasoning},J));break;case"tool":f.publish(f.buildEvent("tool.finished",{toolCallId:W.toolCallId,toolName:W.toolName,output:W.output,error:W.error},J));break}return}if(W.type==="usage"){let H;try{H=await f.sessionHost.getAccumulatedUsage?.(J)}catch{H=void 0}f.publish(f.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:W.inputTokens,outputTokens:W.outputTokens,cacheReadTokens:W.cacheReadTokens??0,cacheWriteTokens:W.cacheWriteTokens??0,totalCost:W.cost??0},totals:{inputTokens:W.totalInputTokens,outputTokens:W.totalOutputTokens,cacheReadTokens:W.totalCacheReadTokens??0,cacheWriteTokens:W.totalCacheWriteTokens??0,totalCost:W.totalCost??0},usage:H?.usage,aggregateUsage:H?.aggregateUsage,agent:{kind:$.payload.teamRole==="teammate"?"teammate":W.parentAgentId?"subagent":"lead",agentId:W.agentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamAgentId:$.payload.teamAgentId,teamRole:$.payload.teamRole}},J));return}if(W.type==="done")f.publish(f.buildEvent("agent.done",{reason:W.reason,text:W.text,iterations:W.iterations,usage:W.usage},J))}async function GM(f,$){let J=f.suppressNextTerminalEventBySession.get($.payload.sessionId),W=J===$.payload.reason||J==="run.start.reply";if(W)f.suppressNextTerminalEventBySession.delete($.payload.sessionId);let[H,Q]=await Promise.all([kf(f,$.payload.sessionId),If(f,$.payload.sessionId)]);if($.payload.reason==="completed"){let Z=await kj(H);f.publish(f.buildEvent("ui.notify",Z,$.payload.sessionId))}if(W)return;f.publish(f.buildEvent($.payload.reason==="aborted"?"run.aborted":$.payload.reason==="error"||$.payload.reason==="failed"?"run.failed":"run.completed",{reason:$.payload.reason,...Q?{snapshot:Q}:{}},$.payload.sessionId))}import{createSessionId as sj,parseRuntimeConfigExtensions as oj}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Sx,HUB_COMPACTION_CAPABILITY as kx,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Ix,HUB_HOOK_CAPABILITY_PREFIX as mx,HUB_MISTAKE_LIMIT_CAPABILITY as xx,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as gx,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as vx,isHubToolExecutorName as TM}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as lx,HUB_COMPACTION_CAPABILITY as px,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as ix,HUB_HOOK_CAPABILITY_PREFIX as nx,HUB_MISTAKE_LIMIT_CAPABILITY as ax,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as tx,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as sx}from"@cline/shared";var DM=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function D$(f){return f&&typeof f==="object"&&!Array.isArray(f)?JSON.parse(JSON.stringify(f)):void 0}function _M(f,$){let J=typeof f.name==="string"?f.name.trim():"",W=typeof f.description==="string"?f.description:"",H=typeof f.capabilityName==="string"?f.capabilityName.trim():"",Q=D$(f.inputSchema);if(!J||!W||!Q||!H||$.has(H))return;return $.add(H),{kind:"tool",capabilityName:H,name:J,description:W,inputSchema:Q,...D$(f.lifecycle)?{lifecycle:D$(f.lifecycle)}:{}}}function gW(f){if(!Array.isArray(f))return[];let $=[],J=new Set;for(let W of f){if(!W||typeof W!=="object"||Array.isArray(W))continue;let H=W,Q=H.kind,Z=typeof H.capabilityName==="string"?H.capabilityName.trim():"";if(!Z||J.has(Z))continue;if(Q==="tool"){let j=_M(H,J);if(j)$.push(j);continue}if(Q==="toolExecutor"){let j=H.executor;if(!TM(j))continue;J.add(Z),$.push({kind:"toolExecutor",capabilityName:Z,executor:j});continue}if(Q==="hook"){let j=typeof H.name==="string"?H.name.trim():"";if(!j)continue;J.add(Z),$.push({kind:"hook",capabilityName:Z,name:j});continue}if(Q==="compaction"){J.add(Z),$.push({kind:"compaction",capabilityName:Z,...D$(H.config)?{config:D$(H.config)}:{}});continue}if(Q==="checkpoint"){J.add(Z),$.push({kind:"checkpoint",capabilityName:Z,...D$(H.config)?{config:D$(H.config)}:{}});continue}if(Q==="mistakeLimit"){J.add(Z),$.push({kind:"mistakeLimit",capabilityName:Z});continue}if(Q==="userInstructionService")J.add(Z),$.push({kind:"userInstructionService",capabilityName:Z})}return $}function tj(f){return{agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,metadata:f.metadata}}function MM(f){return Object.hasOwn(f,"update")?f.update:f}function Y2(f){return f.trim().replace(/^\/+/,"").toLowerCase()}function LM(f){let $=(f??[]).map(Y2).filter(Boolean);return $.length>0?new Set($):void 0}function hM(f,$,J){if(!J)return!0;let W=Y2(f),H=Y2($),Q=W.includes(":")?W.split(":").at(-1)??W:W,Z=H.includes(":")?H.split(":").at(-1)??H:H;return J.has(W)||J.has(H)||J.has(Q)||J.has(Z)}function xW(f,$){let J=LM($);return f.records.skill.map((W)=>({id:W.id,name:W.item.name,description:"description"in W.item&&typeof W.item.description==="string"?W.item.description:void 0,disabled:W.item.disabled===!0,skill:W.item})).filter((W)=>hM(W.id,W.name,J))}function OM(f,$){let J=async(W,H)=>{let Q=Y2(W),j=xW(f,$).filter((Y)=>Y.id===Q||Y2(Y.name)===Q||Y.id.endsWith(`:${Q}`)).filter((Y)=>!Y.disabled);if(j.length!==1)return j.length>1?`Skill "${W}" is ambiguous. Use one of: ${j.map((Y)=>Y.id).join(", ")}`:`Skill "${W}" not found.`;let X=j[0].skill,A=H?.trim(),P=A?`
|
|
696
|
+
<command-args>${A}</command-args>`:"",B=X.description?.trim()?`Description: ${X.description.trim()}
|
|
697
|
+
|
|
698
|
+
`:"";return`<command-name>${X.name}</command-name>${P}
|
|
699
699
|
<command-instructions>
|
|
700
|
-
${
|
|
701
|
-
</command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>
|
|
700
|
+
${B}${X.instructions}
|
|
701
|
+
</command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>xW(f,$).map(({skill:W,...H})=>H),enumerable:!0}),J}function zM(f,$,J,W){let H={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},Q=async()=>{let Z=await W(f,J.capabilityName,{},$);if(Z?.snapshot)H=Z.snapshot};return{start:Q,stop:()=>{},refreshType:async()=>{await Q()},listRecords:(Z)=>[...H.records[Z]],listRuntimeCommands:()=>[...H.runtimeCommands],resolveRuntimeSlashCommand:(Z)=>{if(!Z.startsWith("/")||Z.length<2)return Z;let X=Z.match(/^\/(\S+)/)?.[1];if(!X)return Z;let A=H.runtimeCommands.find((P)=>P.name===X);return A?`${A.instructions}${Z.slice(X.length+1)}`:Z},hasConfiguredSkills:(Z)=>xW(H,Z).some((j)=>!j.disabled),createExtension:(Z)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[Z.includeRules?"rules":void 0,Z.registerSkillsTool?"tools":void 0,Z.includeSkills||Z.includeWorkflows?"commands":void 0].filter((j)=>Boolean(j))},setup(j){if(Z.includeRules)j.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>x2(H.records.rule.map((X)=>X.item).filter((X)=>X.disabled!==!0))});if(Z.registerSkillsTool)j.registerTool(C$(OM(H,Z.allowedSkillNames)));for(let X of H.runtimeCommands.filter((A)=>A.kind==="skill"&&Z.includeSkills||A.kind==="workflow"&&Z.includeWorkflows))j.registerCommand({name:X.name,description:X.description,handler:(A)=>{let P=A.trim();return P?`${X.instructions}
|
|
702
702
|
|
|
703
|
-
${V}`:P.instructions}})}})}}function eD(f,$,J,H){let W=J.map((Q)=>[Q.executor,async(...Z)=>{let j=Z.at(-1),P=Z.slice(0,-1);return(await H(f,Q.capabilityName,{executor:Q.executor,args:P,context:rj(j)},$))?.result}]);return W.length>0?Object.fromEntries(W):void 0}function fM(f,$,J,H){if(J.length===0)return;return J.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema,lifecycle:W.lifecycle,async execute(Q,Z){return(await H(f,W.capabilityName,{toolName:W.name,input:Q,context:rj(Z)},$,Z.emitUpdate?(P)=>{Z.emitUpdate?.(nD(P))}:void 0))?.result}}))}function $M(f,$,J,H){let W=new Map(J.map((Z)=>[Z.name,Z])),Q={};for(let Z of pD){let j=W.get(Z);if(!j)continue;Q[Z]=async(P)=>{return(await H(f,j.capabilityName,{context:P},$))?.control}}return Object.keys(Q).length>0?Q:void 0}function NW(f){let $=f.contributions.filter((P)=>P.kind==="toolExecutor"),J=f.contributions.filter((P)=>P.kind==="tool"),H=f.contributions.filter((P)=>P.kind==="hook"),W=f.contributions.find((P)=>P.kind==="compaction"),Q=f.contributions.find((P)=>P.kind==="checkpoint"),Z=f.contributions.find((P)=>P.kind==="mistakeLimit"),j=f.contributions.find((P)=>P.kind==="userInstructionService");return{hasClientContributions:f.contributions.length>0,toolExecutors:eD(f.sessionId,f.targetClientId,$,f.requestCapability),localRuntime:{...H.length>0?{hooks:$M(f.sessionId,f.targetClientId,H,f.requestCapability)}:{},...J.length>0?{extraTools:fM(f.sessionId,f.targetClientId,J,f.requestCapability)}:{},...W?{compaction:{...f.sessionConfig?.compaction??{},...W.config,compact:async(P)=>{return(await f.requestCapability(f.sessionId,W.capabilityName,{context:P},f.targetClientId))?.result}}}:{},...Q?{checkpoint:{...f.sessionConfig?.checkpoint??{},...Q.config,createCheckpoint:async(P)=>{return(await f.requestCapability(f.sessionId,Q.capabilityName,{context:P},f.targetClientId))?.result}}}:{},...Z?{onConsecutiveMistakeLimitReached:async(P)=>{return(await f.requestCapability(f.sessionId,Z.capabilityName,{context:P},f.targetClientId))?.result}}:{},...j?{userInstructionService:oD(f.sessionId,f.targetClientId,j,f.requestCapability)}:{}}}}var ij="hubCapabilityOwnerClientId";function nj(f,$){f[ij]=$}function JM(f){let $=f?.[ij];return typeof $==="string"&&$.trim()?$.trim():void 0}async function aj(f,$,J){let H=performance.now(),W={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:$.sessionId};k("info","session.create.begin",W);let Q=$.payload&&typeof $.payload==="object"?$.payload:{},Z=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{},j=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0,P=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{};if(typeof j?.mode==="string")Z.mode=j.mode;else if(typeof P.mode==="string")Z.mode=P.mode;if(typeof j?.systemPrompt==="string")Z.systemPrompt=j.systemPrompt;else if(typeof P.systemPrompt==="string")Z.systemPrompt=P.systemPrompt;if(j?.checkpoint?.enabled===!0)Z.checkpointEnabled=!0;else if(P.checkpointEnabled===!0)Z.checkpointEnabled=!0;let X=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},V=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():"";if(!V)return k("warn","session.create.invalid",{...W,reason:"missing_workspace_root"}),E($,"invalid_session_create","session.create requires workspaceRoot or cwd");let Y=$.clientId?.trim()||"hub-client",B=OW(P.clientContributions);if(k("info","session.create.contributions_parsed",{...W,clientId:Y,workspaceRoot:V,cwd:typeof Q.cwd==="string"?Q.cwd:void 0,contributionCount:B.length}),B.length>0)nj(Z,Y);let R=(typeof j?.sessionId==="string"?j.sessionId.trim():"")||lj(),U=pj(P.configExtensions);k("info","session.create.runtime_build.begin",{...W,sessionId:R,configExtensionCount:U?.length??0});let y=NW({sessionId:R,targetClientId:Y,contributions:B,sessionConfig:j,requestCapability:f.requestCapability});k("info","session.create.start_session.begin",{...W,sessionId:R,provider:j?.providerId??(typeof X.provider==="string"?X.provider:typeof Z.provider==="string"?Z.provider:"hub"),model:j?.modelId??(typeof X.model==="string"?X.model:typeof Z.model==="string"?Z.model:"hub")});let F=await f.sessionHost.startSession({source:typeof Z.source==="string"?Z.source:void 0,interactive:Z.interactive!==!1,sessionMetadata:Object.keys(Z).length>0?Z:void 0,initialMessages:Array.isArray(Q.initialMessages)?Q.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:U,...y.localRuntime},capabilities:{toolExecutors:y.toolExecutors,requestToolApproval:J},config:{...j??{},sessionId:R,providerId:j?.providerId??(typeof X.provider==="string"?X.provider:typeof Z.provider==="string"?Z.provider:"hub"),modelId:j?.modelId??(typeof X.model==="string"?X.model:typeof Z.model==="string"?Z.model:"hub"),apiKey:j?.apiKey??(typeof X.apiKey==="string"?X.apiKey:void 0),cwd:j?.cwd??(typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():V),workspaceRoot:j?.workspaceRoot??V,systemPrompt:j?.systemPrompt??(typeof P.systemPrompt==="string"?P.systemPrompt:""),mode:j?.mode??(P.mode==="plan"||P.mode==="yolo"?P.mode:"act"),maxIterations:j?.maxIterations??(typeof P.maxIterations==="number"?P.maxIterations:void 0),enableTools:j?.enableTools??P.enableTools!==!1,enableSpawnAgent:j?.enableSpawnAgent??P.enableSpawn!==!1,enableAgentTeams:j?.enableAgentTeams??P.enableTeams!==!1,checkpoint:j?.checkpoint??(P.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:j?.teamName??(typeof Z.teamName==="string"?Z.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):P.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});k("info","session.create.start_session.end",{...W,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-H),hasImmediateResult:!!F.result}),M4(f,F.sessionId,Y,"creator",{interactive:Z.interactive!==!1}),k("info","session.create.read_records.begin",{...W,sessionId:F.sessionId});let[K,M]=await Promise.all([bf(f,F.sessionId),wf(f,F.sessionId)]);if(k("info","session.create.read_records.end",{...W,sessionId:F.sessionId,hasSession:!!K,hasSnapshot:!!M,elapsedMs:Math.round(performance.now()-H)}),K)f.publish(f.buildEvent("session.created",{session:K,...M?{snapshot:M}:{}},F.sessionId));return k("info","session.create.reply",{...W,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-H)}),m($,{session:K,...M?{snapshot:M}:{}})}async function tj(f,$,J){let H=$.payload&&typeof $.payload==="object"?$.payload:{},W=typeof H.sessionId==="string"?H.sessionId.trim():$.sessionId?.trim()||"",Q=H.checkpointRunCount;if(!W)return E($,"invalid_restore","session.restore requires a session id");let Z=H.restore&&typeof H.restore==="object"?H.restore:{},j=Z.messages!==!1;if(typeof Q!=="number")return E($,"invalid_restore","checkpointRunCount must be a positive integer");try{let P=H.sessionConfig&&typeof H.sessionConfig==="object"?JSON.parse(JSON.stringify(H.sessionConfig)):void 0;if(j&&!P)return E($,"invalid_restore","sessionConfig is required when restore.messages is true");let X=H.runtimeOptions&&typeof H.runtimeOptions==="object"?H.runtimeOptions:{},V=H.metadata&&typeof H.metadata==="object"?JSON.parse(JSON.stringify(H.metadata)):{};if(typeof P?.mode==="string")V.mode=P.mode;else if(typeof X.mode==="string")V.mode=X.mode;if(typeof P?.systemPrompt==="string")V.systemPrompt=P.systemPrompt;else if(typeof X.systemPrompt==="string")V.systemPrompt=X.systemPrompt;if(P?.checkpoint?.enabled===!0)V.checkpointEnabled=!0;else if(X.checkpointEnabled===!0)V.checkpointEnabled=!0;let Y=H.modelSelection&&typeof H.modelSelection==="object"?H.modelSelection:{},B=$.clientId?.trim()||"hub-client",A=OW(X.clientContributions);if(A.length>0)nj(V,B);let U=(typeof P?.sessionId==="string"?P.sessionId.trim():"")||lj(),y=pj(X.configExtensions),F=NW({sessionId:U,targetClientId:B,contributions:A,sessionConfig:P,requestCapability:f.requestCapability}),M=await new n$().restoreCheckpoint({sessionId:W,checkpointRunCount:Q,restore:{messages:Z.messages,workspace:Z.workspace,omitCheckpointMessageFromSession:Z.omitCheckpointMessageFromSession===!0},start:P,cwd:typeof P?.cwd==="string"&&P.cwd.trim()||typeof P?.workspaceRoot==="string"&&P.workspaceRoot.trim()||void 0,getSession:(L)=>f.sessionHost.getSession(L),readMessages:(L)=>f.sessionHost.readSessionMessages(L),buildStartInput:(L)=>{if(L.restoredCheckpointMetadata)V.checkpoint=L.restoredCheckpointMetadata;let x=typeof H.workspaceRoot==="string"&&H.workspaceRoot.trim()?H.workspaceRoot.trim():typeof H.cwd==="string"&&H.cwd.trim()?H.cwd.trim():L.sourceSession.workspaceRoot||L.sourceSession.cwd;return{source:typeof V.source==="string"?V.source:void 0,interactive:V.interactive!==!1,sessionMetadata:{...V,restoredFromSessionId:W,restoredCheckpointRunCount:Q},initialMessages:L.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:y,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...P??{},sessionId:U,providerId:P?.providerId??(typeof Y.provider==="string"?Y.provider:L.sourceSession.provider),modelId:P?.modelId??(typeof Y.model==="string"?Y.model:L.sourceSession.model),apiKey:P?.apiKey??(typeof Y.apiKey==="string"?Y.apiKey:""),cwd:P?.cwd??L.plan.cwd,workspaceRoot:P?.workspaceRoot??x,systemPrompt:P?.systemPrompt??(typeof X.systemPrompt==="string"?X.systemPrompt:""),mode:P?.mode??(X.mode==="plan"||X.mode==="yolo"?X.mode:"act"),maxIterations:P?.maxIterations??(typeof X.maxIterations==="number"?X.maxIterations:void 0),enableTools:P?.enableTools??X.enableTools!==!1,enableSpawnAgent:P?.enableSpawnAgent??X.enableSpawn!==!1,enableAgentTeams:P?.enableAgentTeams??X.enableTeams!==!1,checkpoint:P?.checkpoint??(X.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:P?.teamName??(typeof V.teamName==="string"?V.teamName:void 0)},toolPolicies:H.toolPolicies&&typeof H.toolPolicies==="object"&&!Array.isArray(H.toolPolicies)?JSON.parse(JSON.stringify(H.toolPolicies)):X.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(L)=>f.sessionHost.startSession(L),getStartedSessionId:(L)=>L.sessionId,readRestoredSession:(L)=>f.sessionHost.getSession(L)});if(!j)return m($,{checkpoint:M.checkpoint});let T=M.startResult;if(!T)return E($,"restore_failed","Checkpoint restore did not start a session");M4(f,T.sessionId,B,"creator",{interactive:V.interactive!==!1});let[G,h]=await Promise.all([bf(f,T.sessionId),wf(f,T.sessionId)]);if(G)f.publish(f.buildEvent("session.created",{session:G,...h?{snapshot:h}:{}},T.sessionId));return m($,{session:G,...h?{snapshot:h}:{},messages:M.messages??[],checkpoint:M.checkpoint})}catch(P){if(P instanceof mf)return E($,P.code,P.code==="session_not_found"?`Unknown session: ${W}`:P.message);return E($,"restore_failed",P instanceof Error?P.message:String(P))}}async function sj(f,$){let J=Uf($);if(!J)return E($,"invalid_session_attach","session.attach requires a session id");M4(f,J,$.clientId?.trim()||"hub-client","participant");let H=await bf(f,J);if(H)f.publish(f.buildEvent("session.attached",{session:H},J));return H?m($,{session:H}):E($,"session_not_found",`Unknown session: ${J}`)}async function oj(f,$){let J=Uf($);if(!J)return E($,"invalid_session_detach","session.detach requires a session id");let H=$.clientId?.trim()||"hub-client",[W]=await Promise.all([bf(f,J)]),Q=JM(W?.metadata)??H,Z=f.sessionState.get(J);if(Z){if(Z.participants.delete(H),Z.createdByClientId===H)Z.createdByClientId=Q;if(Z.participants.size===0)f.sessionState.delete(J)}S0(f,(X)=>X.sessionId===J&&X.targetClientId===H,`Capability owner client ${H} detached before request was resolved.`);let[j,P]=await Promise.all([bf(f,J),wf(f,J)]);return f.publish(f.buildEvent("session.detached",j?{session:j,...P?{snapshot:P}:{},clientId:H}:{clientId:H},J)),m($)}async function ej(f,$){let J=Uf($),H=$.payload?.includeSnapshot===!0,[W,Q]=await Promise.all([bf(f,J),H?wf(f,J):Promise.resolve(void 0)]);return W?m($,{session:W,...Q?{snapshot:Q}:{}}):E($,"session_not_found",`Unknown session: ${J}`)}async function fP(f,$){let J=Uf($);if(!J)return E($,"invalid_session_id","session.messages requires a session id");if(!await bf(f,J))return E($,"session_not_found",`Unknown session: ${J}`);let W=await f.sessionHost.readSessionMessages(J);return m($,{sessionId:J,messages:W})}async function $P(f,$){let J=typeof $.payload?.limit==="number"?$.payload.limit:200,W=(await f.sessionHost.listSessions(J)).map((Q)=>T4(Q,f.sessionState.get(Q.sessionId)));return m($,{sessions:W})}async function JP(f,$){let J=Uf($),H=D4($.payload?.metadata),W=await f.sessionHost.updateSession(J,{metadata:H}),[Q,Z]=await Promise.all([bf(f,J),wf(f,J)]);if(Q)f.publish(f.buildEvent("session.updated",{session:Q,...Z?{snapshot:Z}:{}},J));return{version:$.version,requestId:$.requestId,ok:W.updated,payload:{updated:W.updated,session:Q,...Z?{snapshot:Z}:{}}}}async function HP(f,$){let J=Uf($),H=await f.sessionHost.deleteSession(J);return f.sessionState.delete(J),m($,{deleted:H})}async function WP(f,$){let J=Uf($),H=f.sessionHost.pendingPrompts;if(!H)return E($,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await H.list({sessionId:J});return m($,{sessionId:J,prompts:W})}async function QP(f,$){let J=Uf($),H=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",W=typeof $.payload?.prompt==="string"?$.payload.prompt:void 0,Q=$.payload?.delivery==="queue"||$.payload?.delivery==="steer"?$.payload.delivery:void 0,Z=f.sessionHost.pendingPrompts;if(!Z)return E($,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await Z.update({sessionId:J,promptId:H,prompt:W,delivery:Q});return m($,j)}async function ZP(f,$){let J=Uf($),H=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",W=f.sessionHost.pendingPrompts;if(!W)return E($,"pending_prompts_unavailable","Pending prompt service is not available.");let Q=await W.delete({sessionId:J,promptId:H});return m($,Q)}function jP(f){switch(f){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var WM=new Set(["skills","workflows","rules","tools"]);function qW(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function Z2(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${$}' must be a string.`);return J}function QM(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${$}' must be a boolean.`);return J}function PP(f){if(f===void 0)return{};if(!qW(f))throw Error("settings.list payload must be an object.");return{cwd:Z2(f,"cwd"),workspaceRoot:Z2(f,"workspaceRoot"),availabilityContext:qW(f.availabilityContext)?f.availabilityContext:void 0}}function ZM(f){if(!qW(f))throw Error("settings.toggle payload must be an object.");let{type:$}=f;if(typeof $!=="string"||!WM.has($))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools.");return{...PP(f),type:$,id:Z2(f,"id"),path:Z2(f,"path"),name:Z2(f,"name"),enabled:QM(f,"enabled")}}class _4{options;clients=new Map;listeners=new Map;sessionState=new Map;pendingApprovals=new Map;pendingCapabilityRequests=new Map;suppressNextTerminalEventBySession=new Map;schedules;scheduleCommands;settings;cronService;sessionHost;hubId=HM("hub_");ctx;constructor(f){this.options=f;if(this.sessionHost=f.sessionHost??new E0({sessionService:new N0(new O0),fetch:f.fetch,telemetry:f.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,sessionHost:this.sessionHost,publish:($)=>this.publish($),buildEvent:F$,requestCapability:($,J,H,W,Q)=>Cj(this.ctx,$,J,H,W,Q)},this.schedules=new F4({...f.scheduleOptions,runtimeHandlers:f.runtimeHandlers,eventPublisher:($,J)=>{let H=$==="schedule.execution.completed"?"schedule.execution_completed":$==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!H)return;this.publish(F$(H,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new B4(this.schedules),this.settings=f.settingsService??new k$,f.cronOptions)this.cronService=new N1({runtimeHandlers:f.runtimeHandlers,...f.cronOptions});this.sessionHost.subscribe(($)=>{dj(this.ctx,$).catch((J)=>{LW("session event handling failed",J)})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch(f){console.error("[hub] cron service start failed",f)}}async stop(){for(let f of this.pendingApprovals.keys())MW(this.ctx,f,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(S0(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch(f){console.error("[hub] cron service stop failed",f)}}async handleCommand(f){switch(f.command){case"client.register":return mj(this.ctx,f);case"client.update":return Ij(this.ctx,f);case"client.unregister":return xj(this.ctx,f,($)=>{this.listeners.delete($),this.detachClientFromSessions($)});case"client.list":return gj(this.ctx,f);case"session.create":return await aj(this.ctx,f,($)=>DW(this.ctx,$));case"session.restore":return await tj(this.ctx,f,($)=>DW(this.ctx,$));case"session.attach":return await sj(this.ctx,f);case"session.detach":return await oj(this.ctx,f);case"session.get":return await ej(this.ctx,f);case"session.messages":return await fP(this.ctx,f);case"session.list":return await $P(this.ctx,f);case"session.update":return await JP(this.ctx,f);case"session.pending_prompts":return await WP(this.ctx,f);case"session.update_pending_prompt":return await QP(this.ctx,f);case"session.remove_pending_prompt":return await ZP(this.ctx,f);case"session.delete":return await HP(this.ctx,f);case"session.hook":return await cj(this.ctx,f);case"run.start":case"session.send_input":return await vj(this.ctx,f);case"run.abort":return await uj(this.ctx,f);case"capability.request":return await Sj(this.ctx,f);case"approval.respond":return await bj(this.ctx,f);case"capability.respond":return kj(this.ctx,f);case"capability.progress":return Ej(this.ctx,f);case"ui.notify":return this.publish(F$("ui.notify",f.payload??{})),m(f);case"ui.show_window":return this.publish(F$("ui.show_window",f.payload??{})),m(f);case"settings.list":return await this.handleSettingsList(f);case"settings.toggle":return await this.handleSettingsToggle(f);case"settings.get":case"settings.patch":return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"not_implemented",message:`${f.command} is not implemented yet.`}};default:{let $=await this.scheduleCommands.handleCommand(f);if($.ok){let J=jP(f.command);if(J)this.publish(F$(J,$.payload))}return $}}}async handleSettingsList(f){try{let $=await this.settings.list(PP(f.payload));return{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_list_failed",message:$ instanceof Error?$.message:String($)}}}}async handleSettingsToggle(f){try{let $=await this.settings.toggle(ZM(f.payload));return this.publish(F$("settings.changed",{types:$.changedTypes,snapshot:$.snapshot})),{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$.snapshot,changedTypes:$.changedTypes}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_toggle_failed",message:$ instanceof Error?$.message:String($)}}}}subscribe(f,$,J){let H=this.listeners.get(f)??new Set,W={sessionId:J?.sessionId,listener:$};return H.add(W),this.listeners.set(f,H),()=>{let Q=this.listeners.get(f);if(!Q)return;if(Q.delete(W),Q.size===0)this.listeners.delete(f)}}detachClientFromSessions(f){for(let[$,J]of this.sessionState.entries())if(J.participants.delete(f),J.participants.size===0)this.sessionState.delete($);S0(this.ctx,($)=>$.targetClientId===f,`Capability owner client ${f} disconnected before request was resolved.`)}publish(f){for(let $ of this.listeners.values())for(let J of $){if(J.sessionId&&J.sessionId!==f.sessionId)continue;try{J.listener(f)}catch(H){LW(`listener threw while publishing ${f.event}`,H)}}}}import{timingSafeEqual as VM}from"node:crypto";import YM from"node:http";import BM from"node:net";import{URL as YP}from"node:url";import{WebSocketServer as AM}from"ws";import{HUB_COMMAND_SLOW_LOG_MS as jM,resolveHubCommandTimeoutMs as PM,safeJsonParse as XM}from"@cline/shared";function XP(f){return{command:f.envelope.command,requestId:f.envelope.requestId,clientId:f.envelope.clientId,sessionId:f.envelope.sessionId}}function VP(f,$,J){return{version:f.envelope.version,requestId:f.envelope.requestId,ok:!1,error:{code:$,message:J}}}class bW{transport;constructor(f){this.transport=f}attach(f){let $=new Map,J=new Set,H=!1,W=(P)=>{try{f.send(JSON.stringify(P))}catch(X){console.error(`[hub] failed to send websocket frame: ${X instanceof Error?X.stack||X.message:String(X)}`)}},Q=(P)=>{W({kind:"event",envelope:P})},Z=async(P)=>{try{let X=JSON.parse(P.data);switch(X.kind){case"command":{let V=performance.now(),Y=!1,B=XP(X);k("info","command.start",B);let A=setTimeout(()=>{if(Y)return;k("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-V)})},jM),R=this.transport.command(X.envelope);R.then((T)=>{if(!Y)return;k(T.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-V),ok:T.ok,errorCode:T.error?.code,errorMessage:T.error?.message})},(T)=>{if(!Y)return;k("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-V),error:T})});let U=!1,y,F,K=PM(X.envelope.command,X.envelope.timeoutMs);try{F=K===null?await R:await Promise.race([R,new Promise((T)=>{y=setTimeout(()=>{U=!0,T(VP(X,"hub_command_timeout",`Hub command ${X.envelope.command} did not complete within ${K}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${X.envelope.requestId}.`))},K)})])}catch(T){if(clearTimeout(A),y)clearTimeout(y);throw T}if(Y=U,clearTimeout(A),y)clearTimeout(y);let M=Math.round(performance.now()-V);if(U)k("error","command.timeout",{...B,durationMs:M,timeoutMs:K});else k(F.ok?"info":"warn","command.end",{...B,durationMs:M,ok:F.ok,errorCode:F.error?.code,errorMessage:F.error?.message});if(X.envelope.command==="client.register"&&F.ok){let G=(X.envelope.payload??{}).clientId?.trim()||X.envelope.clientId?.trim();if(G)J.add(G)}else if(X.envelope.command==="client.unregister"&&F.ok){let T=X.envelope.clientId?.trim();if(T)J.delete(T)}W({kind:"reply",envelope:F});break}case"stream.subscribe":{let V=`${X.clientId}:${X.sessionId??"*"}`;if($.has(V))break;let Y=await this.transport.subscribe(X.clientId,Q,{sessionId:X.sessionId});$.set(V,Y);break}case"stream.unsubscribe":{let V=`${X.clientId}:${X.sessionId??"*"}`;$.get(V)?.(),$.delete(V);break}case"reply":case"event":break}}catch(X){let V=typeof P.data==="string"?XM(P.data):void 0;if(!V||V.kind!=="command"){k("error","rejected malformed websocket frame",{error:X});return}k("error","command.error",{...XP(V),error:X}),W({kind:"reply",envelope:VP(V,"command_failed",X instanceof Error?X.message:"Unknown hub error")})}},j=()=>{if(H)return;H=!0;for(let P of $.values())P();$.clear();for(let P of J)this.transport.command({version:"v1",command:"client.unregister",clientId:P});J.clear(),f.removeEventListener("message",Z),f.removeEventListener("close",j)};return f.addEventListener("message",Z),f.addEventListener("close",j),j}}class wW{transport;constructor(f){this.transport=f}command(f){return this.transport.handleCommand(f)}subscribe(f,$,J){return this.transport.subscribe(f,$,J)}}function RM(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();return String(f)}function FM(f){return{send($){f.send($)},addEventListener($,J){if($==="message"){f.on("message",(H)=>{J({data:RM(H)})});return}f.on("close",J)},removeEventListener(){}}}function yM(f){try{f.write(`HTTP/1.1 400 Bad Request\r
|
|
703
|
+
${P}`:X.instructions}})}})}}function NM(f,$,J,W){let H=J.map((Q)=>[Q.executor,async(...Z)=>{let j=Z.at(-1),X=Z.slice(0,-1);return(await W(f,Q.capabilityName,{executor:Q.executor,args:X,context:tj(j)},$))?.result}]);return H.length>0?Object.fromEntries(H):void 0}function qM(f,$,J,W){if(J.length===0)return;return J.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema,lifecycle:H.lifecycle,async execute(Q,Z){return(await W(f,H.capabilityName,{toolName:H.name,input:Q,context:tj(Z)},$,Z.emitUpdate?(X)=>{Z.emitUpdate?.(MM(X))}:void 0))?.result}}))}function wM(f,$,J,W){let H=new Map(J.map((Z)=>[Z.name,Z])),Q={};for(let Z of DM){let j=H.get(Z);if(!j)continue;Q[Z]=async(X)=>{return(await W(f,j.capabilityName,{context:X},$))?.control}}return Object.keys(Q).length>0?Q:void 0}function vW(f){let $=f.contributions.filter((X)=>X.kind==="toolExecutor"),J=f.contributions.filter((X)=>X.kind==="tool"),W=f.contributions.filter((X)=>X.kind==="hook"),H=f.contributions.find((X)=>X.kind==="compaction"),Q=f.contributions.find((X)=>X.kind==="checkpoint"),Z=f.contributions.find((X)=>X.kind==="mistakeLimit"),j=f.contributions.find((X)=>X.kind==="userInstructionService");return{hasClientContributions:f.contributions.length>0,toolExecutors:NM(f.sessionId,f.targetClientId,$,f.requestCapability),localRuntime:{...W.length>0?{hooks:wM(f.sessionId,f.targetClientId,W,f.requestCapability)}:{},...J.length>0?{extraTools:qM(f.sessionId,f.targetClientId,J,f.requestCapability)}:{},...H?{compaction:{...f.sessionConfig?.compaction??{},...H.config,compact:async(X)=>{return(await f.requestCapability(f.sessionId,H.capabilityName,{context:X},f.targetClientId))?.result}}}:{},...Q?{checkpoint:{...f.sessionConfig?.checkpoint??{},...Q.config,createCheckpoint:async(X)=>{return(await f.requestCapability(f.sessionId,Q.capabilityName,{context:X},f.targetClientId))?.result}}}:{},...Z?{onConsecutiveMistakeLimitReached:async(X)=>{return(await f.requestCapability(f.sessionId,Z.capabilityName,{context:X},f.targetClientId))?.result}}:{},...j?{userInstructionService:zM(f.sessionId,f.targetClientId,j,f.requestCapability)}:{}}}}var ej="hubCapabilityOwnerClientId";function fX(f,$){f[ej]=$}function bM(f){let $=f?.[ej];return typeof $==="string"&&$.trim()?$.trim():void 0}async function $X(f,$,J){let W=performance.now(),H={command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:$.sessionId};I("info","session.create.begin",H);let Q=$.payload&&typeof $.payload==="object"?$.payload:{},Z=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{},j=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0,X=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{};if(typeof j?.mode==="string")Z.mode=j.mode;else if(typeof X.mode==="string")Z.mode=X.mode;if(typeof j?.systemPrompt==="string")Z.systemPrompt=j.systemPrompt;else if(typeof X.systemPrompt==="string")Z.systemPrompt=X.systemPrompt;if(j?.checkpoint?.enabled===!0)Z.checkpointEnabled=!0;else if(X.checkpointEnabled===!0)Z.checkpointEnabled=!0;let A=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},P=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():"";if(!P)return I("warn","session.create.invalid",{...H,reason:"missing_workspace_root"}),S($,"invalid_session_create","session.create requires workspaceRoot or cwd");let B=$.clientId?.trim()||"hub-client",Y=gW(X.clientContributions);if(I("info","session.create.contributions_parsed",{...H,clientId:B,workspaceRoot:P,cwd:typeof Q.cwd==="string"?Q.cwd:void 0,contributionCount:Y.length}),Y.length>0)fX(Z,B);let R=(typeof j?.sessionId==="string"?j.sessionId.trim():"")||sj(),U=oj(X.configExtensions);I("info","session.create.runtime_build.begin",{...H,sessionId:R,configExtensionCount:U?.length??0});let K=vW({sessionId:R,targetClientId:B,contributions:Y,sessionConfig:j,requestCapability:f.requestCapability});I("info","session.create.start_session.begin",{...H,sessionId:R,provider:j?.providerId??(typeof A.provider==="string"?A.provider:typeof Z.provider==="string"?Z.provider:"hub"),model:j?.modelId??(typeof A.model==="string"?A.model:typeof Z.model==="string"?Z.model:"hub")});let F=await f.sessionHost.startSession({source:typeof Z.source==="string"?Z.source:void 0,interactive:Z.interactive!==!1,sessionMetadata:Object.keys(Z).length>0?Z:void 0,initialMessages:Array.isArray(Q.initialMessages)?Q.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:U,...K.localRuntime},capabilities:{toolExecutors:K.toolExecutors,requestToolApproval:J},config:{...j??{},sessionId:R,providerId:j?.providerId??(typeof A.provider==="string"?A.provider:typeof Z.provider==="string"?Z.provider:"hub"),modelId:j?.modelId??(typeof A.model==="string"?A.model:typeof Z.model==="string"?Z.model:"hub"),apiKey:j?.apiKey??(typeof A.apiKey==="string"?A.apiKey:void 0),cwd:j?.cwd??(typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():P),workspaceRoot:j?.workspaceRoot??P,systemPrompt:j?.systemPrompt??(typeof X.systemPrompt==="string"?X.systemPrompt:""),mode:j?.mode??(X.mode==="plan"||X.mode==="yolo"?X.mode:"act"),maxIterations:j?.maxIterations??(typeof X.maxIterations==="number"?X.maxIterations:void 0),enableTools:j?.enableTools??X.enableTools!==!1,enableSpawnAgent:j?.enableSpawnAgent??X.enableSpawn!==!1,enableAgentTeams:j?.enableAgentTeams??X.enableTeams!==!1,checkpoint:j?.checkpoint??(X.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:j?.teamName??(typeof Z.teamName==="string"?Z.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):X.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});I("info","session.create.start_session.end",{...H,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-W),hasImmediateResult:!!F.result}),N4(f,F.sessionId,B,"creator",{interactive:Z.interactive!==!1}),I("info","session.create.read_records.begin",{...H,sessionId:F.sessionId});let[y,D]=await Promise.all([kf(f,F.sessionId),If(f,F.sessionId)]);if(I("info","session.create.read_records.end",{...H,sessionId:F.sessionId,hasSession:!!y,hasSnapshot:!!D,elapsedMs:Math.round(performance.now()-W)}),y)f.publish(f.buildEvent("session.created",{session:y,...D?{snapshot:D}:{}},F.sessionId));return I("info","session.create.reply",{...H,sessionId:F.sessionId,elapsedMs:Math.round(performance.now()-W)}),m($,{session:y,...D?{snapshot:D}:{}})}async function JX(f,$,J){let W=$.payload&&typeof $.payload==="object"?$.payload:{},H=typeof W.sessionId==="string"?W.sessionId.trim():$.sessionId?.trim()||"",Q=W.checkpointRunCount;if(!H)return S($,"invalid_restore","session.restore requires a session id");let Z=W.restore&&typeof W.restore==="object"?W.restore:{},j=Z.messages!==!1;if(typeof Q!=="number")return S($,"invalid_restore","checkpointRunCount must be a positive integer");try{let X=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0;if(j&&!X)return S($,"invalid_restore","sessionConfig is required when restore.messages is true");let A=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{},P=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{};if(typeof X?.mode==="string")P.mode=X.mode;else if(typeof A.mode==="string")P.mode=A.mode;if(typeof X?.systemPrompt==="string")P.systemPrompt=X.systemPrompt;else if(typeof A.systemPrompt==="string")P.systemPrompt=A.systemPrompt;if(X?.checkpoint?.enabled===!0)P.checkpointEnabled=!0;else if(A.checkpointEnabled===!0)P.checkpointEnabled=!0;let B=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},Y=$.clientId?.trim()||"hub-client",V=gW(A.clientContributions);if(V.length>0)fX(P,Y);let U=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||sj(),K=oj(A.configExtensions),F=vW({sessionId:U,targetClientId:Y,contributions:V,sessionConfig:X,requestCapability:f.requestCapability}),D=await new e$().restoreCheckpoint({sessionId:H,checkpointRunCount:Q,restore:{messages:Z.messages,workspace:Z.workspace,omitCheckpointMessageFromSession:Z.omitCheckpointMessageFromSession===!0},start:X,cwd:typeof X?.cwd==="string"&&X.cwd.trim()||typeof X?.workspaceRoot==="string"&&X.workspaceRoot.trim()||void 0,getSession:(L)=>f.sessionHost.getSession(L),readMessages:(L)=>f.sessionHost.readSessionMessages(L),buildStartInput:(L)=>{if(L.restoredCheckpointMetadata)P.checkpoint=L.restoredCheckpointMetadata;let O=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():L.sourceSession.workspaceRoot||L.sourceSession.cwd;return{source:typeof P.source==="string"?P.source:void 0,interactive:P.interactive!==!1,sessionMetadata:{...P,restoredFromSessionId:H,restoredCheckpointRunCount:Q},initialMessages:L.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:K,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:U,providerId:X?.providerId??(typeof B.provider==="string"?B.provider:L.sourceSession.provider),modelId:X?.modelId??(typeof B.model==="string"?B.model:L.sourceSession.model),apiKey:X?.apiKey??(typeof B.apiKey==="string"?B.apiKey:""),cwd:X?.cwd??L.plan.cwd,workspaceRoot:X?.workspaceRoot??O,systemPrompt:X?.systemPrompt??(typeof A.systemPrompt==="string"?A.systemPrompt:""),mode:X?.mode??(A.mode==="plan"||A.mode==="yolo"?A.mode:"act"),maxIterations:X?.maxIterations??(typeof A.maxIterations==="number"?A.maxIterations:void 0),enableTools:X?.enableTools??A.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??A.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??A.enableTeams!==!1,checkpoint:X?.checkpoint??(A.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof P.teamName==="string"?P.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):A.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(L)=>f.sessionHost.startSession(L),getStartedSessionId:(L)=>L.sessionId,readRestoredSession:(L)=>f.sessionHost.getSession(L)});if(!j)return m($,{checkpoint:D.checkpoint});let M=D.startResult;if(!M)return S($,"restore_failed","Checkpoint restore did not start a session");N4(f,M.sessionId,Y,"creator",{interactive:P.interactive!==!1});let[T,_]=await Promise.all([kf(f,M.sessionId),If(f,M.sessionId)]);if(T)f.publish(f.buildEvent("session.created",{session:T,..._?{snapshot:_}:{}},M.sessionId));return m($,{session:T,..._?{snapshot:_}:{},messages:D.messages??[],checkpoint:D.checkpoint})}catch(X){if(X instanceof gf)return S($,X.code,X.code==="session_not_found"?`Unknown session: ${H}`:X.message);return S($,"restore_failed",X instanceof Error?X.message:String(X))}}async function WX(f,$){let J=Mf($);if(!J)return S($,"invalid_session_attach","session.attach requires a session id");N4(f,J,$.clientId?.trim()||"hub-client","participant");let W=await kf(f,J);if(W)f.publish(f.buildEvent("session.attached",{session:W},J));return W?m($,{session:W}):S($,"session_not_found",`Unknown session: ${J}`)}async function HX(f,$){let J=Mf($);if(!J)return S($,"invalid_session_detach","session.detach requires a session id");let W=$.clientId?.trim()||"hub-client",[H]=await Promise.all([kf(f,J)]),Q=bM(H?.metadata)??W,Z=f.sessionState.get(J);if(Z){if(Z.participants.delete(W),Z.createdByClientId===W)Z.createdByClientId=Q;if(Z.participants.size===0)f.sessionState.delete(J)}v0(f,(A)=>A.sessionId===J&&A.targetClientId===W,`Capability owner client ${W} detached before request was resolved.`);let[j,X]=await Promise.all([kf(f,J),If(f,J)]);return f.publish(f.buildEvent("session.detached",j?{session:j,...X?{snapshot:X}:{},clientId:W}:{clientId:W},J)),m($)}async function QX(f,$){let J=Mf($),W=$.payload?.includeSnapshot===!0,[H,Q]=await Promise.all([kf(f,J),W?If(f,J):Promise.resolve(void 0)]);return H?m($,{session:H,...Q?{snapshot:Q}:{}}):S($,"session_not_found",`Unknown session: ${J}`)}async function ZX(f,$){let J=Mf($);if(!J)return S($,"invalid_session_id","session.messages requires a session id");if(!await kf(f,J))return S($,"session_not_found",`Unknown session: ${J}`);let H=await f.sessionHost.readSessionMessages(J);return m($,{sessionId:J,messages:H})}async function jX(f,$){let J=typeof $.payload?.limit==="number"?$.payload.limit:200,H=(await f.sessionHost.listSessions(J)).map((Q)=>O4(Q,f.sessionState.get(Q.sessionId)));return m($,{sessions:H})}async function XX(f,$){let J=Mf($),W=z4($.payload?.metadata),H=await f.sessionHost.updateSession(J,{metadata:W}),[Q,Z]=await Promise.all([kf(f,J),If(f,J)]);if(Q)f.publish(f.buildEvent("session.updated",{session:Q,...Z?{snapshot:Z}:{}},J));return{version:$.version,requestId:$.requestId,ok:H.updated,payload:{updated:H.updated,session:Q,...Z?{snapshot:Z}:{}}}}async function AX(f,$){let J=Mf($),W=await f.sessionHost.deleteSession(J);return f.sessionState.delete(J),m($,{deleted:W})}async function PX(f,$){let J=Mf($),W=f.sessionHost.pendingPrompts;if(!W)return S($,"pending_prompts_unavailable","Pending prompt service is not available.");let H=await W.list({sessionId:J});return m($,{sessionId:J,prompts:H})}async function BX(f,$){let J=Mf($),W=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",H=typeof $.payload?.prompt==="string"?$.payload.prompt:void 0,Q=$.payload?.delivery==="queue"||$.payload?.delivery==="steer"?$.payload.delivery:void 0,Z=f.sessionHost.pendingPrompts;if(!Z)return S($,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await Z.update({sessionId:J,promptId:W,prompt:H,delivery:Q});return m($,j)}async function YX(f,$){let J=Mf($),W=typeof $.payload?.promptId==="string"?$.payload.promptId.trim():"",H=f.sessionHost.pendingPrompts;if(!H)return S($,"pending_prompts_unavailable","Pending prompt service is not available.");let Q=await H.delete({sessionId:J,promptId:W});return m($,Q)}function VX(f){switch(f){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var EM=new Set(["skills","workflows","rules","tools"]);function uW(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function V2(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${$}' must be a string.`);return J}function SM(f,$){let J=f[$];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${$}' must be a boolean.`);return J}function RX(f){if(f===void 0)return{};if(!uW(f))throw Error("settings.list payload must be an object.");return{cwd:V2(f,"cwd"),workspaceRoot:V2(f,"workspaceRoot"),availabilityContext:uW(f.availabilityContext)?f.availabilityContext:void 0}}function kM(f){if(!uW(f))throw Error("settings.toggle payload must be an object.");let{type:$}=f;if(typeof $!=="string"||!EM.has($))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools.");return{...RX(f),type:$,id:V2(f,"id"),path:V2(f,"path"),name:V2(f,"name"),enabled:SM(f,"enabled")}}class q4{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=CM("hub_");ctx;constructor(f){this.options=f;if(this.sessionHost=f.sessionHost??new g0({sessionService:new S0(new E0),fetch:f.fetch,telemetry:f.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,sessionHost:this.sessionHost,publish:($)=>this.publish($),buildEvent:T$,requestCapability:($,J,W,H,Q)=>xj(this.ctx,$,J,W,H,Q)},this.schedules=new T4({...f.scheduleOptions,runtimeHandlers:f.runtimeHandlers,eventPublisher:($,J)=>{let W=$==="schedule.execution.completed"?"schedule.execution_completed":$==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!W)return;this.publish(T$(W,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new y4(this.schedules),this.settings=f.settingsService??new c$,f.cronOptions)this.cronService=new k1({runtimeHandlers:f.runtimeHandlers,...f.cronOptions});this.sessionHost.subscribe(($)=>{aj(this.ctx,$).catch((J)=>{mW("session event handling failed",J)})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch(f){console.error("[hub] cron service start failed",f)}}async stop(){for(let f of this.pendingApprovals.keys())kW(this.ctx,f,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(v0(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch(f){console.error("[hub] cron service stop failed",f)}}async handleCommand(f){switch(f.command){case"client.register":return cj(this.ctx,f);case"client.update":return dj(this.ctx,f);case"client.unregister":return rj(this.ctx,f,($)=>{this.listeners.delete($),this.detachClientFromSessions($)});case"client.list":return lj(this.ctx,f);case"session.create":return await $X(this.ctx,f,($)=>SW(this.ctx,$));case"session.restore":return await JX(this.ctx,f,($)=>SW(this.ctx,$));case"session.attach":return await WX(this.ctx,f);case"session.detach":return await HX(this.ctx,f);case"session.get":return await QX(this.ctx,f);case"session.messages":return await ZX(this.ctx,f);case"session.list":return await jX(this.ctx,f);case"session.update":return await XX(this.ctx,f);case"session.pending_prompts":return await PX(this.ctx,f);case"session.update_pending_prompt":return await BX(this.ctx,f);case"session.remove_pending_prompt":return await YX(this.ctx,f);case"session.delete":return await AX(this.ctx,f);case"session.hook":return await nj(this.ctx,f);case"run.start":case"session.send_input":return await pj(this.ctx,f);case"run.abort":return await ij(this.ctx,f);case"capability.request":return await vj(this.ctx,f);case"approval.respond":return await Ij(this.ctx,f);case"capability.respond":return uj(this.ctx,f);case"capability.progress":return gj(this.ctx,f);case"ui.notify":return this.publish(T$("ui.notify",f.payload??{})),m(f);case"ui.show_window":return this.publish(T$("ui.show_window",f.payload??{})),m(f);case"settings.list":return await this.handleSettingsList(f);case"settings.toggle":return await this.handleSettingsToggle(f);case"settings.get":case"settings.patch":return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"not_implemented",message:`${f.command} is not implemented yet.`}};default:{let $=await this.scheduleCommands.handleCommand(f);if($.ok){let J=VX(f.command);if(J)this.publish(T$(J,$.payload))}return $}}}async handleSettingsList(f){try{let $=await this.settings.list(RX(f.payload));return{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_list_failed",message:$ instanceof Error?$.message:String($)}}}}async handleSettingsToggle(f){try{let $=await this.settings.toggle(kM(f.payload));return this.publish(T$("settings.changed",{types:$.changedTypes,snapshot:$.snapshot})),{version:f.version,requestId:f.requestId,ok:!0,payload:{snapshot:$.snapshot,changedTypes:$.changedTypes}}}catch($){return{version:f.version,requestId:f.requestId,ok:!1,error:{code:"settings_toggle_failed",message:$ instanceof Error?$.message:String($)}}}}subscribe(f,$,J){let W=this.listeners.get(f)??new Set,H={sessionId:J?.sessionId,listener:$};return W.add(H),this.listeners.set(f,W),()=>{let Q=this.listeners.get(f);if(!Q)return;if(Q.delete(H),Q.size===0)this.listeners.delete(f)}}detachClientFromSessions(f){for(let[$,J]of this.sessionState.entries())if(J.participants.delete(f),J.participants.size===0)this.sessionState.delete($);v0(this.ctx,($)=>$.targetClientId===f,`Capability owner client ${f} disconnected before request was resolved.`)}publish(f){for(let $ of this.listeners.values())for(let J of $){if(J.sessionId&&J.sessionId!==f.sessionId)continue;try{J.listener(f)}catch(W){mW(`listener threw while publishing ${f.event}`,W)}}}}import{timingSafeEqual as gM}from"node:crypto";import vM from"node:http";import uM from"node:net";import{URL as yX}from"node:url";import{WebSocketServer as cM}from"ws";import{HUB_COMMAND_SLOW_LOG_MS as IM,resolveHubCommandTimeoutMs as mM,safeJsonParse as xM}from"@cline/shared";function FX(f){return{command:f.envelope.command,requestId:f.envelope.requestId,clientId:f.envelope.clientId,sessionId:f.envelope.sessionId}}function KX(f,$,J){return{version:f.envelope.version,requestId:f.envelope.requestId,ok:!1,error:{code:$,message:J}}}class cW{transport;constructor(f){this.transport=f}attach(f){let $=new Map,J=new Set,W=!1,H=(X)=>{try{f.send(JSON.stringify(X))}catch(A){console.error(`[hub] failed to send websocket frame: ${A instanceof Error?A.stack||A.message:String(A)}`)}},Q=(X)=>{H({kind:"event",envelope:X})},Z=async(X)=>{try{let A=JSON.parse(X.data);switch(A.kind){case"command":{let P=performance.now(),B=!1,Y=FX(A);I("info","command.start",Y);let V=setTimeout(()=>{if(B)return;I("warn","command.slow",{...Y,elapsedMs:Math.round(performance.now()-P)})},IM),R=this.transport.command(A.envelope);R.then((M)=>{if(!B)return;I(M.ok?"warn":"error","command.late_end",{...Y,elapsedMs:Math.round(performance.now()-P),ok:M.ok,errorCode:M.error?.code,errorMessage:M.error?.message})},(M)=>{if(!B)return;I("error","command.late_error",{...Y,elapsedMs:Math.round(performance.now()-P),error:M})});let U=!1,K,F,y=mM(A.envelope.command,A.envelope.timeoutMs);try{F=y===null?await R:await Promise.race([R,new Promise((M)=>{K=setTimeout(()=>{U=!0,M(KX(A,"hub_command_timeout",`Hub command ${A.envelope.command} did not complete within ${y}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${A.envelope.requestId}.`))},y)})])}catch(M){if(clearTimeout(V),K)clearTimeout(K);throw M}if(B=U,clearTimeout(V),K)clearTimeout(K);let D=Math.round(performance.now()-P);if(U)I("error","command.timeout",{...Y,durationMs:D,timeoutMs:y});else I(F.ok?"info":"warn","command.end",{...Y,durationMs:D,ok:F.ok,errorCode:F.error?.code,errorMessage:F.error?.message});if(A.envelope.command==="client.register"&&F.ok){let T=(A.envelope.payload??{}).clientId?.trim()||A.envelope.clientId?.trim();if(T)J.add(T)}else if(A.envelope.command==="client.unregister"&&F.ok){let M=A.envelope.clientId?.trim();if(M)J.delete(M)}H({kind:"reply",envelope:F});break}case"stream.subscribe":{let P=`${A.clientId}:${A.sessionId??"*"}`;if($.has(P))break;let B=await this.transport.subscribe(A.clientId,Q,{sessionId:A.sessionId});$.set(P,B);break}case"stream.unsubscribe":{let P=`${A.clientId}:${A.sessionId??"*"}`;$.get(P)?.(),$.delete(P);break}case"reply":case"event":break}}catch(A){let P=typeof X.data==="string"?xM(X.data):void 0;if(!P||P.kind!=="command"){I("error","rejected malformed websocket frame",{error:A});return}I("error","command.error",{...FX(P),error:A}),H({kind:"reply",envelope:KX(P,"command_failed",A instanceof Error?A.message:"Unknown hub error")})}},j=()=>{if(W)return;W=!0;for(let X of $.values())X();$.clear();for(let X of J)this.transport.command({version:"v1",command:"client.unregister",clientId:X});J.clear(),f.removeEventListener("message",Z),f.removeEventListener("close",j)};return f.addEventListener("message",Z),f.addEventListener("close",j),j}}class dW{transport;constructor(f){this.transport=f}command(f){return this.transport.handleCommand(f)}subscribe(f,$,J){return this.transport.subscribe(f,$,J)}}function dM(f){if(typeof f==="string")return f;if(f instanceof Uint8Array)return Buffer.from(f).toString();if(f instanceof ArrayBuffer)return Buffer.from(f).toString();if(Array.isArray(f))return Buffer.concat(f.map(($)=>Buffer.from($))).toString();return String(f)}function rM(f){return{send($){f.send($)},addEventListener($,J){if($==="message"){f.on("message",(W)=>{J({data:dM(W)})});return}f.on("close",J)},removeEventListener(){}}}function lM(f){try{f.write(`HTTP/1.1 400 Bad Request\r
|
|
704
704
|
Connection: close\r
|
|
705
705
|
Content-Length: 0\r
|
|
706
706
|
\r
|
|
707
|
-
`),f.end()}catch{f.destroy()}}function
|
|
707
|
+
`),f.end()}catch{f.destroy()}}function pM(f){try{f.write(`HTTP/1.1 401 Unauthorized\r
|
|
708
708
|
Connection: close\r
|
|
709
709
|
Content-Length: 0\r
|
|
710
710
|
\r
|
|
711
|
-
`),f.end()}catch{f.destroy()}}function
|
|
712
|
-
Caused by: ${f.stack}`;return Q}async function
|
|
713
|
-
`,"utf8");let P=$.timeoutMs??300000,X=$.pollIntervalMs??200,V=Date.now();while(Date.now()-V<P){try{let Y=await _M(Z,"utf8"),B=JSON.parse(Y),A={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([SW(Z),SW(Q)]),A}catch{}await NM(X)}return await SW(Q),{approved:!1,reason:"Tool approval request timed out"}}ef();import*as Jf from"@cline/llms";import{isOAuthProviderId as bM}from"@cline/shared";function wM(f){return f.apiKey??f.auth?.apiKey}function CM(f){return(f.auth?.accessToken?.trim()??"").length>0}function UP(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function EM(f){let $=f.split(/\s+/).filter(Boolean);if($.length===0)return"?";if($.length===1)return $[0].slice(0,2).toUpperCase();return`${$[0][0]}${$[1][0]}`.toUpperCase()}function SM(f){let $=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let H of f)J=J*31+H.charCodeAt(0)>>>0;return $[J%$.length]}function GP(f){return Object.entries(f).sort(([$],[J])=>$.localeCompare(J)).map(([$,J])=>OZ($,J))}async function kM(f,$){let J=await Jf.getModelsForProvider(f);if(!$)return J;let H=await Y6(f,{loadPrivateOnAuth:!0,failOnError:!1},$);return H?.knownModels?{...J,...H.knownModels}:J}function kW(f){return[...new Set((f??[]).map(($)=>$.trim()).filter(Boolean))]}function hP(f){let $=Object.entries(f??{}).filter(([J])=>J.trim().length>0);return $.length>0?Object.fromEntries($):void 0}function mW(f,$){let J=$?.includes("vision")??!1,H=$?.includes("reasoning")??!1;return Object.fromEntries(f.map((W)=>[W,{id:W,name:W,supportsVision:J,supportsAttachments:J,supportsReasoning:H}]))}async function TP(f){if(!f.shouldRecompute)return f.fallbackModelIds??[];let $=f.modelsSourceUrl?await D2(f.modelsSourceUrl,f.providerId):[];return[...new Set([...f.explicitModels??[],...$])]}function DP(f,$){let J=f.read(),H=!1;if(J.providers[$])delete J.providers[$],H=!0;if(J.lastUsedProvider===$)delete J.lastUsedProvider,H=!0;if(H)f.write(J);Jf.unregisterProvider($)}async function mM(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let H=$.baseUrl.trim(),W=$.apiKey?.trim()??"";if(!H&&!W){let R=B$(f);if((await p$(R)).providers[J]){let y=await _P(f,{providerId:J});return{providerId:J,settingsPath:y.settingsPath,modelsPath:y.modelsPath,modelsCount:0}}return DP(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:R,modelsCount:0}}if(Jf.hasProvider(J))throw Error(`provider "${J}" already exists`);let Q=$.name.trim();if(!Q)throw Error("name is required");if(!H)throw Error("baseUrl is required");let Z=kW($.models),j=$.modelsSourceUrl?.trim(),P=await TP({providerId:J,explicitModels:Z,modelsSourceUrl:j,shouldRecompute:!0});if(P.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let X=$.defaultModelId?.trim()&&P.includes($.defaultModelId.trim())?$.defaultModelId.trim():P[0],V=$.capabilities?.length?[...new Set($.capabilities)]:void 0,Y=hP($.headers);f.saveProviderSettings({provider:J,apiKey:W||void 0,baseUrl:H,headers:Y,timeout:$.timeoutMs,model:X,protocol:$.protocol,client:$.client},{setLastUsed:!1});let B=B$(f),A=await p$(B);return A.providers[J]={provider:{name:Q,baseUrl:H,defaultModelId:X,protocol:$.protocol,client:$.client,capabilities:V,modelsSourceUrl:j},models:mW(P,V)},await s8(B,A),a1(J,A.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:B,modelsCount:P.length}}async function MP(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let H=B$(f),W=await p$(H),Q=W.providers[J];if(!Q){let T=f.getProviderSettings(J);if(!T)throw Error(`provider "${J}" does not exist`);let G=$.modelsSourceUrl?.trim(),h=kW($.models)[0]??T.model?.trim();if(!h&&!G)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:$.name?.trim()||UP(J),baseUrl:$.baseUrl?.trim()??T.baseUrl?.trim()??"",defaultModelId:h,protocol:T.protocol,client:T.client,capabilities:T.capabilities},models:h?mW([h],T.capabilities):{}}}if(!Q.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let Z=$.name?.trim()??Q.provider.name.trim();if(!Z)throw Error("name is required");let j=$.baseUrl?.trim()??Q.provider.baseUrl.trim();if(!j)throw Error("baseUrl is required");let P=$.capabilities===void 0?Q.provider.capabilities:$.capabilities===null?void 0:[...new Set($.capabilities)],X=$.protocol===void 0?Q.provider.protocol:$.protocol??void 0,V=$.client===void 0?Q.provider.client:$.client??void 0,Y=kW($.models),B=$.modelsSourceUrl===void 0?Q.provider.modelsSourceUrl:$.modelsSourceUrl?.trim()||void 0,A=$.models!==void 0||$.modelsSourceUrl!==void 0&&!!B,R=Object.keys(Q.models??{}).map((T)=>T.trim()).filter(Boolean),U=await TP({providerId:J,explicitModels:Y,modelsSourceUrl:B,fallbackModelIds:R,shouldRecompute:A});if(U.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let y=$.defaultModelId===void 0?Q.provider.defaultModelId?.trim():$.defaultModelId?.trim(),F=y&&U.includes(y)?y:U[0],M={...f.getProviderSettings(J)??{},provider:J,baseUrl:j,model:F};if(X)M.protocol=X;else delete M.protocol;if(V)M.client=V;else delete M.client;if($.apiKey!==void 0){let T=$.apiKey?.trim()??"";if(T)M.apiKey=T;else delete M.apiKey}if($.headers!==void 0){let T=hP($.headers);if(T)M.headers=T;else delete M.headers}if($.timeoutMs!==void 0)if(typeof $.timeoutMs==="number")M.timeout=$.timeoutMs;else delete M.timeout;return f.saveProviderSettings(M,{setLastUsed:!1}),W.providers[J]={provider:{name:Z,baseUrl:j,defaultModelId:F,protocol:X,client:V,capabilities:P,modelsSourceUrl:B},models:mW(U,P)},await s8(H,W),a1(J,W.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:H,modelsCount:U.length}}async function _P(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let H=B$(f),W=await p$(H);if(!W.providers[J])throw Error(`provider "${J}" does not exist`);return delete W.providers[J],await s8(H,W),Jf.unregisterProvider(J),DP(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:H}}async function IM(f){let $=f.read(),J=Jf.getProviderIds().sort((W,Q)=>W.localeCompare(Q));return{providers:await Promise.all(J.map(async(W)=>{let[Q,Z]=await Promise.all([Jf.getProvider(W),Jf.getModelsForProvider(W)]),j=GP(Z),P=$.providers[W]?.settings,X=Q?.name??UP(W);return{id:W,name:X,models:j.length,color:SM(W),letter:EM(X),enabled:Boolean(P),apiKey:P?wM(P):void 0,oauthAccessTokenPresent:P?CM(P):void 0,baseUrl:P?.baseUrl??Q?.baseUrl,defaultModelId:Q?.defaultModelId,protocol:P?.protocol??Q?.protocol,client:P?.client??Q?.client,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",modelList:j}})),settingsPath:f.getFilePath()}}async function xM(f,$){let J=f.trim(),H=await kM(J,$),W=GP(H);return{providerId:J,models:W}}function gM(f,$){let J=$.providerId.trim();if($.enabled===!1){let Q=f.read();if(delete Q.providers[J],Q.lastUsedProvider===J)delete Q.lastUsedProvider;return f.write(Q),{providerId:J,enabled:!1,settingsPath:f.getFilePath()}}let W={...f.getProviderSettings(J)??{},provider:J};for(let Q of["apiKey","baseUrl","model","region"])if(Object.hasOwn($,Q)&&typeof $[Q]==="string")if($[Q].trim().length===0)delete W[Q];else W[Q]=$[Q];for(let Q of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn($,Q))W[Q]=$[Q];for(let Q of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn($,Q)&&$[Q]!=null)W[Q]={...typeof W[Q]==="object"&&W[Q]!=null?W[Q]:{},...$[Q]};return f.saveProviderSettings(W,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:f.getFilePath()}}async function vM(f,$){let J=$.trim(),H=f.getProviderSettings(J),Q=Jf.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,Z=H?.baseUrl?.trim()||Q?.baseUrl?.trim(),j=M2(Z,Q?.baseUrl,Q?.modelsSourceUrl);if(!H||!Q||!Z||!j)return{providerId:J,refreshed:!1};let P=await MP(f,{providerId:J,name:Q.name,baseUrl:Z,apiKey:H.apiKey,headers:H.headers??null,timeoutMs:H.timeout??null,modelsSourceUrl:j,protocol:H.protocol??Q.protocol??null,client:H.client??Q.client??null,capabilities:H.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:P.modelsCount}}function uM(f){let $=f.trim().toLowerCase();if($==="codex"||$==="openai-codex")return"openai-codex";if($==="cline"||$==="oca")return $;throw Error(`provider "${f}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function cM(f,$){if(f==="cline")return $.access.startsWith("workos:")?$.access:`workos:${$.access}`;return $.access}async function dM(f,$,J){let H=q4({onPrompt:async(W)=>W.defaultValue??"",openUrl:J,onOpenUrlError:({error:W})=>{throw W instanceof Error?W:Error(String(W))}});if(f==="cline")return F2({apiBaseUrl:$?.baseUrl?.trim()||"https://api.cline.bot",useWorkOSDeviceAuth:!0,callbacks:H});if(f==="oca")return T2({mode:$?.oca?.mode,callbacks:H});return K2(H)}function rM(f,$,J,H){let W={...J?.auth??{},accessToken:cM($,H),refreshToken:H.refresh,accountId:H.accountId,expiresAt:H.expires},Q={...J??{provider:$},provider:$,auth:W};return f.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function lM(f){let $=f?.auth?.accessToken?.trim()||f?.apiKey?.trim();return $&&$.length>0?$:void 0}var pM=new Set(["ollama","lmstudio","litellm"]);function iM(f,$){if(!$?.provider.baseUrl)return!1;if($.provider.source!=="system")return!0;return pM.has(f)}function nM(f){let $=Jf.normalizeProviderId(f);if(bM($))return{providerId:$,authMethod:"oauth",fields:{}};let J=Jf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],H=J?.provider.baseUrl,W={apiKey:{}};if(iM($,J))W.baseUrl={defaultValue:H};return{providerId:$,authMethod:"api-key",fields:W}}Af();G4();import{appendFileSync as aM,existsSync as IW,mkdirSync as tM,readFileSync as sM,renameSync as oM,unlinkSync as eM,writeFileSync as f_}from"node:fs";import{join as xW}from"node:path";import{resolveTeamDataDir as $_}from"@cline/shared/storage";function J_(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class LP{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor(f){let $=J_(f.teamName),J=f.baseDir?.trim()||$_();this.dirPath=xW(J,$),this.statePath=xW(this.dirPath,"state.json"),this.taskHistoryPath=xW(this.dirPath,"task-history.jsonl")}loadState(){if(!IW(this.statePath))return;try{let f=sM(this.statePath,"utf8"),$=JSON.parse(f);if($.version!==1||!$.teamState)return;for(let J of $.teammates??[])this.teammateSpecs.set(J.agentId,J);return IQ($.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec(f){this.teammateSpecs.set(f.agentId,f)}removeTeammateSpec(f){this.teammateSpecs.delete(f)}persist(f){if(!this.hasPersistableState(f)){this.clearPersistedState();return}this.ensureDir();let $={version:1,updatedAt:new Date().toISOString(),teamState:f.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;f_(J,`${JSON.stringify($,null,2)}
|
|
714
|
-
`,"utf8"),
|
|
715
|
-
`,"utf8")}ensureDir(){if(!IW(this.dirPath))tM(this.dirPath,{recursive:!0})}hasPersistableState(f){let $=f.exportState();if(this.teammateSpecs.size>0)return!0;if($.members.some((J)=>J.role==="teammate"))return!0;return $.tasks.length>0||$.mailbox.length>0||$.missionLog.length>0}clearPersistedState(){if(IW(this.statePath))eM(this.statePath)}}import{z}from"zod";var zP=z.object({workspaceRoot:z.string().min(1),cwd:z.string().optional(),provider:z.string().min(1),model:z.string().min(1),mode:z.enum(["act","plan"]).default("act"),apiKey:z.string(),systemPrompt:z.string().optional(),rules:z.string().optional(),maxIterations:z.number().int().positive().optional(),enableTools:z.boolean(),enableSpawn:z.boolean().optional(),enableTeams:z.boolean().optional(),autoApproveTools:z.boolean().optional(),missionStepInterval:z.number().int().positive().optional(),missionTimeIntervalMs:z.number().int().positive().optional()}),OP=z.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),NP=z.enum(["user","assistant","tool","system","status","error"]),qP=z.object({id:z.string().min(1),sessionId:z.string().nullable(),role:NP,content:z.string(),createdAt:z.number().int().nonnegative(),meta:z.object({stream:z.enum(["stdout","stderr"]).optional(),toolName:z.string().optional(),iteration:z.number().int().nonnegative().optional(),agentId:z.string().optional(),conversationId:z.string().optional(),hookEventName:z.string().optional(),inputTokens:z.number().int().nonnegative().optional(),outputTokens:z.number().int().nonnegative().optional(),checkpoint:z.object({ref:z.string(),createdAt:z.number().int().nonnegative(),runCount:z.number().int().positive(),kind:z.enum(["stash","commit"]).optional()}).optional()}).optional()}),bP=z.object({toolCalls:z.number().int().nonnegative(),tokensIn:z.number().int().nonnegative(),tokensOut:z.number().int().nonnegative()}),H_=z.object({sessionId:z.string().nullable(),status:OP,config:zP,messages:z.array(qP),rawTranscript:z.string(),error:z.string().nullable(),summary:bP});var W_=l7;import{Agent as Uu,createAgentRuntime as Gu}from"@cline/agents";var wP="https://api.cline.bot",Q_=5000,EP={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 Z_(f){return{recommended:f.recommended.map(($)=>({...$,tags:[...$.tags]})),free:f.free.map(($)=>({...$,tags:[...$.tags]}))}}function CP(f){if(!f||typeof f!=="object")return null;let $=f;if(typeof $.id!=="string"||$.id.length===0)return null;return{id:$.id,name:typeof $.name==="string"&&$.name.length>0?$.name:$.id,description:typeof $.description==="string"?$.description:"",tags:Array.isArray($.tags)?$.tags.filter((J)=>typeof J==="string"):[]}}function j_(f){if(!f||typeof f!=="object")return null;let $=f,J=Array.isArray($.recommended)?$.recommended:[],H=Array.isArray($.free)?$.free:[],W=J.map(CP).filter((Z)=>Z!==null),Q=H.map(CP).filter((Z)=>Z!==null);if(W.length===0&&Q.length===0)return null;return{recommended:W,free:Q}}function P_(f){let $=f.baseUrl?.trim();if($)return $;try{return(f.providerSettingsManager??new C0).getProviderSettings("cline")?.baseUrl?.trim()||wP}catch{return wP}}async function X_(f,$,J){let H=new AbortController,W=setTimeout(()=>H.abort(),J);try{return await f($,{signal:H.signal})}finally{clearTimeout(W)}}async function V_(f={}){try{let $=P_(f),J=f.fetchImpl??fetch,H=await X_(J,`${$}/api/v1/ai/cline/recommended-models`,f.timeoutMs??Q_);if(!H.ok)throw Error(`HTTP ${H.status}`);let W=await H.json(),Q=j_(W);if(Q)return Q}catch{}return Z_(EP)}import{readFile as Y_}from"node:fs/promises";import B_ from"node:path";function A_(f){return f}async function R_(f){let $=B_.resolve(f),J=await Y_($,"utf8"),H;try{H=JSON.parse(J)}catch(W){let Q=W instanceof Error?W.message:String(W);throw Error(`Failed to parse JSON config at "${$}": ${Q}`)}return F_(H,$)}function F_(f,$){if(!f||typeof f!=="object")throw Error(`Invalid llms config in "${$}": expected an object.`);let H=f.providers;if(!Array.isArray(H))throw Error(`Invalid llms config in "${$}": "providers" must be an array.`);if(!H.length)throw Error(`Invalid llms config in "${$}": "providers" cannot be empty.`);return f}import{BUILT_IN_PROVIDER_IDS as mP,createHandler as U_,createHandlerAsync as G_,getProviderCollection as h_,hasProvider as IP,registerAsyncHandler as T_,registerHandler as D_,registerModel as M_,registerProvider as xP}from"@cline/llms";function SP(f){return f?{...f}:{}}function y_(f,$){if(f)return f;if(!$)return;let J=globalThis.process;if(!J?.env)return;return J.env[$]}function K_(f,$){if(!$.length)throw Error(`Provider "${f}" must include at least one model.`)}function kP(f){let $=Object.keys(f.collection.models);return{id:f.collection.provider.id,name:f.collection.provider.name,description:f.collection.provider.description,protocol:f.collection.provider.protocol,baseUrl:f.collection.provider.baseUrl,capabilities:f.collection.provider.capabilities,env:f.collection.provider.env,models:$,defaultModel:f.collection.provider.defaultModelId,modelCount:$.length}}class gW{providers=new Map;register(f){K_(f.id,f.models);let $=f.defaultModel??f.models[0];if(!$)throw Error(`Provider "${f.id}" must define a default model.`);if(!f.models.includes($))throw Error(`Default model "${$}" is not included in configured models for "${f.id}".`);let J=this.providers.get(f.id);this.providers.set(f.id,{id:f.id,models:new Set([...J?.models??[],...f.models]),defaultModel:$,defaults:{...J?.defaults??{},...SP(f.defaults)}})}registerSelectionConfig(f){this.register({id:f.id,models:f.models,defaultModel:f.defaultModel,defaults:{apiKey:y_(f.apiKey,f.apiKeyEnv),routingProviderId:f.builtinProviderId,baseUrl:f.baseUrl,headers:f.headers,timeoutMs:f.timeoutMs,capabilities:f.capabilities,...SP(f.settings)}})}registerModel(f,$){let J=this.providers.get(f);if(!J){this.providers.set(f,{id:f,models:new Set([$]),defaultModel:$,defaults:{}});return}J.models.add($)}createHandlerConfig(f){let $=this.require(f.providerId),J=f.modelId??$.defaultModel;if(!$.models.has(J))throw Error(`Model "${J}" is not configured for provider "${f.providerId}".`);return{providerId:f.providerId,modelId:J,...$.defaults,...f.overrides}}list(){return Array.from(this.providers.values()).map((f)=>({id:f.id,models:Array.from(f.models),defaultModel:f.defaultModel}))}getModels(f){return Array.from(this.require(f).models)}hasProvider(f){return this.providers.has(f)}hasModel(f,$){return this.providers.get(f)?.models.has($)??!1}require(f){let $=this.providers.get(f);if(!$)throw Error(`Provider "${f}" is not configured in this SDK instance.`);return $}}class vW{configuredProviders=new gW;constructor(f){this.applyConfig(f)}createHandler(f){return U_(this.configuredProviders.createHandlerConfig(f))}async createHandlerAsync(f){return G_(this.configuredProviders.createHandlerConfig(f))}registerProvider(f){if(xP(f.collection),f.handlerFactory&&f.asyncHandlerFactory)throw Error(`Provider "${f.collection.provider.id}" cannot register both sync and async handlers.`);if(f.handlerFactory)D_(f.collection.provider.id,f.handlerFactory);if(f.asyncHandlerFactory)T_(f.collection.provider.id,f.asyncHandlerFactory);this.configuredProviders.register({id:f.collection.provider.id,models:f.exposeModels??Object.keys(f.collection.models),defaultModel:f.defaultModel??f.collection.provider.defaultModelId,defaults:f.defaults})}registerBuiltinProvider(f){let $=f.exposeModels??Object.keys(f.models),J=f.defaultModel??$[0];if(!J)throw Error(`Provider "${f.id}" must define a default model.`);xP({provider:{id:f.id,name:f.name??f.id,description:f.description,protocol:f.protocol,baseUrl:f.baseUrl,defaultModelId:J,client:f.client??"openai-compatible",capabilities:f.capabilities,env:f.env,source:"system"},models:f.models}),this.configuredProviders.register({id:f.id,models:$,defaultModel:J,defaults:{routingProviderId:f.builtinProviderId,...f.defaults??{}}})}registerModel(f){M_(f.providerId,f.modelId,f.info),this.configuredProviders.registerModel(f.providerId,f.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...mP]}async getBuiltInProviders(){return(await Promise.all(mP.map(($)=>h_($)))).filter(($)=>$!==void 0).map(($)=>kP({collection:$}))}getModels(f){return this.configuredProviders.getModels(f)}isProviderConfigured(f){return this.configuredProviders.hasProvider(f)}isModelConfigured(f,$){return this.configuredProviders.hasModel(f,$)}applyConfig(f){for(let $ of f.providers)this.configuredProviders.registerSelectionConfig($);for(let $ of f.models??[])this.registerModel($);for(let $ of f.customProviders??[])this.registerProvider($);for(let $ of this.configuredProviders.list()){let J=IP($.id),H=this.configuredProviders.createHandlerConfig({providerId:$.id,modelId:$.defaultModel}).routingProviderId,W=typeof H==="string"&&IP(H);if(!J&&!W)throw Error(`Provider "${$.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function __(f){return new vW(f)}KW();async function jv(){return Promise.resolve().then(() => (vP(),gP))}export{e7 as writeHubDiscovery,E$ as writeGlobalSettings,fQ as withHubStartupLock,L0 as verifyHubConnection,MP as updateLocalProvider,TW as truncateNotificationBody,$J as toggleDisabledTool,I8 as toTeamProgressLifecycleEvent,tf as toProviderConfig,oF as toHubHealthUrl,IH as toHookConfigFileName,CH as summarizeUsageFromMessages,sy as stopLocalHubServerGracefully,g0 as startLocalOAuthServer,EW as startHubWebSocketServer,jg as startHubServer,XX as startClineDeviceAuth,KJ as splitCoreSessionConfig,N8 as spawnDetachedHubServer,WA as setTelemetryOptOutGlobally,x3 as setDisabledTools,jA as setDisabledPlugin,HI as sendHubCommand,gM as saveLocalProviderSettings,rM as saveLocalProviderOAuthCredentials,_3 as sanitizeTeamName,q1 as sanitizeSessionToken,v5 as safeParseSettings,YV as safeCreateProviderConfig,X4 as runSubprocessEvent,Y4 as runHook,M3 as reviveTeamStateDates,AQ as restartLocalHubIfIdleAfterStartupTimeout,Tb as resolveWorkspaceHubOwnerContext,N6 as resolveWorkflowsConfigSearchPaths,z6 as resolveSkillsConfigSearchPaths,Bf as resolveSharedHubOwnerContext,OT as resolveSessionBackend,O6 as resolveRulesConfigSearchPaths,Y6 as resolveProviderConfig,BJ as resolvePluginConfigSearchPaths,$W as resolveMcpServerRegistrations,lM as resolveLocalClineAuthToken,hD as resolveHubUrl,H$ as resolveHubOwnerContext,_0 as resolveHubEndpointOptions,m$ as resolveHubBuildId,kH as resolveHooksConfigSearchPaths,cf as resolveDisabledToolNames,X8 as resolveDisabledPluginPaths,a$ as resolveDefaultMcpSettingsPath,O8 as resolveDefaultHubPort,Xy as resolveDefaultHubPathname,Py as resolveDefaultHubHost,N3 as resolveCoreSelectedToolIds,QH as resolveCompatibleLocalHubUrl,Bb as resolveClineDir,eJ as resolveClineDataDir,F8 as resolveAndLoadAgentPlugins,G1 as resolveAgentPluginPaths,fH as requestHubShutdown,qM as requestDesktopToolApproval,I$ as rememberRecoverableLocalHubUrl,$4 as registerMcpServersFromSettingsFile,Dv as registerDisposable,vM as refreshProviderModelsFromSource,s4 as refreshOpenAICodexToken,$6 as refreshOcaToken,a4 as refreshClineToken,tH as readSessionCheckpointHistory,Zf as readHubDiscovery,of as readGlobalSettings,Yf as probeHubServer,JI as probeHubConnection,E9 as prewarmFileIndex,HQ as prewarmDetachedHubServer,L6 as parseWorkflowConfigFromMarkdown,Tv as parseUserCommandEnvelope,M6 as parseSkillConfigFromMarkdown,g5 as parseSettings,_6 as parseRuleConfigFromMarkdown,V4 as parseHookEventPayload,GX as openaiCodexOAuthProvider,s0 as normalizeWorkspacePath,hv as normalizeUserInput,Vf as normalizeRuntimeCapabilities,N2 as normalizeProviderId,UX as normalizeOpenAICodexCredentials,uM as normalizeOAuthProvider,x$ as normalizeHubWebSocketUrl,Gv as noopBasicLogger,iH as migrateLegacyProviderSettings,k2 as mergeRulesForSystemPrompt,n1 as mergeAgentHooks,gJ as makeTeamTaskSubSessionId,T8 as makeSubSessionId,K2 as loginOpenAICodex,T2 as loginOcaOAuth,dM as loginLocalProvider,F2 as loginClineOAuth,jv as loadOpenTelemetryAdapter,fW as loadMcpSettingsFile,R_ as loadLlmsConfigFromFile,t0 as loadAgentPluginsFromPathsWithDiagnostics,s3 as loadAgentPluginsFromPaths,XJ as loadAgentPluginFromPath,IF as listSessionHistoryFromBackend,RJ as listPluginTools,IM as listLocalProviders,r$ as listHookConfigFiles,QA as isToolDisabledGlobally,fJ as isTelemetryOptedOutGlobally,f9 as isRuleEnabled,ZA as isPluginDisabledGlobally,KX as isOpenAICodexTokenExpired,ry as isHubReconnectableTransportError,YQ as isHubCommandTimeoutError,Fb as isDiscoveryFilePresent,pW as isClineAccountActionRequest,jV as isBuiltInProviderId,Y0 as identifyAccount,f4 as hasMcpSettingsFile,o4 as getValidOpenAICodexCredentials,J6 as getValidOcaCredentials,t4 as getValidClineCredentials,nM as getProviderConfigFields,N5 as getProviderConfig,xM as getLocalProviderModels,O2 as getLiveModelsCatalog,l0 as getFileIndex,qU as getCurrentContextSize,e6 as getCoreHeadlessToolNames,O3 as getCoreDefaultEnabledToolIds,F1 as getCoreBuiltinToolCatalog,q3 as getCoreAcpToolNames,Yv as getClineDefaultSystemPrompt,DJ as generateWorkspaceInfoWithDiagnostics,G8 as generateWorkspaceInfo,h5 as generateOcaOpcRequestId,S2 as formatRulesForSystemPrompt,Uv as formatDisplayUserInput,HJ as filterExtensionToolRegistrations,S$ as filterDisabledTools,JJ as filterDisabledPluginPaths,V_ as fetchClineRecommendedModels,iW as executeClineAccountAction,yP as ensureHubWebSocketServer,Pg as ensureHubServer,Cb as ensureDetachedHubServer,EZ as ensureCustomProvidersLoaded,m1 as ensureCompatibleLocalHubUrl,t2 as enrichPromptWithMentions,Kv as emptyWorkspaceManifest,l$ as emptyStoredProviderSettings,AJ as discoverPluginModulePaths,vJ as deriveSubsessionStatus,_P as deleteLocalProvider,A_ as defineLlmsConfig,w6 as createWorkflowsConfigDefinition,C$ as createUserInstructionConfigService,I9 as createToolPoliciesWithPreset,yv as createTool,jj as createTeamName,Tj as createSubprocessHooks,w$ as createSpawnAgentTool,q6 as createSkillsConfigDefinition,P4 as createSessionHost,P4 as createRuntimeHost,b6 as createRulesConfigDefinition,VV as createProviderConfig,K4 as createOpenTelemetryTelemetryService,EX as createOcaRequestHeaders,CX as createOcaOAuthProvider,q4 as createOAuthClientCallbacks,H4 as createMcpTools,RI as createLocalHubScheduleRuntimeHandlers,__ as createLlmsSdk,c$ as createInitialAccumulatedUsage,Rb as createInMemoryHubOwnerContext,$0 as createHubServerUrl,o7 as createHubAuthToken,uH as createHookConfigFileHooks,l8 as createHookConfigFileExtension,r8 as createHookAuditHooks,JW as createDisabledMcpToolPolicy,eZ as createDisabledMcpToolPolicies,J8 as createDelegatedAgentConfigProvider,H8 as createDelegatedAgent,x9 as createDefaultToolsWithPreset,N$ as createDefaultTools,e8 as createDefaultMcpServerClientFactory,f8 as createDefaultExecutors,h1 as createCoreSettingsService,z0 as createCoreSessionSnapshot,Fv as createContributionRegistry,wH as createContextCompactionPrepareTurn,W2 as createConfiguredTelemetryService,U4 as createConfiguredTelemetryHandle,Rv as createClineTelemetryServiceMetadata,Av as createClineTelemetryServiceConfig,YX as createClineOAuthProvider,y1 as createBuiltinTools,R1 as createAgentTeamsTools,Gu as createAgentRuntime,v8 as createAgentHooksExtension,zj as connectToHub,VX as completeClineDeviceAuth,WV as clearPrivateModelsCatalogCache,HV as clearLiveModelsCatalogCache,rf as clearHubDiscovery,tP as captureWorkspacePathResolved,b4 as captureWorkspaceInitialized,w4 as captureWorkspaceInitError,m4 as captureToolUsage,S4 as captureTokenUsage,E4 as captureTaskRestarted,C4 as captureTaskCreated,X2 as captureTaskCompleted,Y2 as captureSubagentExecution,I4 as captureSkillUsed,V2 as captureProviderApiError,k4 as captureModeSwitch,g4 as captureMentionUsed,u4 as captureMentionSearchResults,v4 as captureMentionFailed,d4 as captureHookDiscovery,aP as captureExtensionActivated,x4 as captureDiffEditFailure,$1 as captureConversationTurnEvent,X0 as captureAuthSucceeded,P0 as captureAuthStarted,I0 as captureAuthLoggedOut,V0 as captureAuthFailed,c4 as captureAgentTeamCreated,x0 as captureAgentCreated,MJ as buildWorkspaceMetadata,m8 as buildTeamProgressSummary,B1 as buildDelegatedAgentConfig,Z8 as bootstrapAgentTeams,mM as addLocalProvider,d$ as accumulateUsageTotals,G6 as WORKFLOWS_CONFIG_DIRECTORY_NAME,W1 as UnifiedConfigFileWatcher,uf as ToolPresets,J2 as TelemetryService,y4 as TelemetryLoggerSink,Q8 as TEAM_TOOL_NAMES,B8 as SubprocessSandbox,i8 as StoredProviderSettingsSchema,FZ as StoredProviderSettingsEntrySchema,o1 as SqliteTeamStore,O0 as SqliteSessionStore,n$ as SessionVersioningService,mf as SessionVersioningError,Pf as SessionSource,m5 as SapSettingsSchema,U6 as SKILLS_CONFIG_DIRECTORY_NAME,R6 as SESSION_STATUSES,N4 as RpcClineAccountService,b8 as RemoteRuntimeHost,C5 as ReasoningSettingsSchema,n5 as RULES_CONFIG_DIRECTORY_NAME,_$ as ProviderSettingsSchema,C0 as ProviderSettingsManager,q5 as ProviderProtocolSchema,A6 as ProviderIdSchema,b5 as ProviderClientSchema,H2 as OpenTelemetryProvider,I5 as OcaSettingsSchema,V6 as OPENAI_COMPATIBLE_PROVIDERS,A5 as OCI_HEADER_OPC_REQUEST_ID,J0 as NodeHubClient,wW as NativeHubTransportAdapter,x5 as ModelCatalogSettingsSchema,E0 as LocalRuntimeHost,Xv as Llms,n8 as InMemoryWorkspaceManager,s1 as InMemoryMcpManager,LD as HubUIClient,zf as HubTransportError,_D as HubSessionClient,_4 as HubServerTransport,F4 as HubScheduleService,B4 as HubScheduleCommandService,Z$ as HubRuntimeHost,q8 as HubCommandError,Gj as HookEventPayloadSchema,Uj as HookEventNameSchema,u8 as HookConfigFileName,mH as HOOK_CONFIG_FILE_EVENT_MAP,ZZ as HOOKS_CONFIG_DIRECTORY_NAME,P8 as GlobalSettingsSchema,S5 as GcpSettingsSchema,LP as FileTeamPersistenceStore,EP as FALLBACK_CLINE_RECOMMENDED_MODELS,$f as DefaultToolNames,Q4 as DefaultRuntimeBuilder,vW as DefaultLlmsSdk,L5 as DEFAULT_MODELS_CATALOG_URL,U2 as DEFAULT_INTERNAL_OCA_BASE_URL,P5 as DEFAULT_INTERNAL_IDCS_URL,X5 as DEFAULT_INTERNAL_IDCS_SCOPES,j5 as DEFAULT_INTERNAL_IDCS_CLIENT_ID,Zy as DEFAULT_HUB_PORT,jy as DEFAULT_HUB_PATHNAME,Qy as DEFAULT_HUB_HOST,G2 as DEFAULT_EXTERNAL_OCA_BASE_URL,Y5 as DEFAULT_EXTERNAL_IDCS_URL,B5 as DEFAULT_EXTERNAL_IDCS_SCOPES,V5 as DEFAULT_EXTERNAL_IDCS_CLIENT_ID,k$ as CoreSettingsService,N0 as CoreSessionService,Bv as ContributionRegistry,yW as ClineCore,O4 as ClineAccountService,H_ as ChatViewStateSchema,bP as ChatSummarySchema,OP as ChatSessionStatusSchema,zP as ChatSessionConfigSchema,qP as ChatMessageSchema,NP as ChatMessageRoleSchema,I as CORE_TELEMETRY_EVENTS,W_ as CORE_BUILD_VERSION,bW as BrowserWebSocketHubAdapter,ZV as BUILT_IN_PROVIDER_IDS,B6 as BUILT_IN_PROVIDER,k5 as AzureSettingsSchema,E5 as AwsSettingsSchema,w5 as AuthSettingsSchema,u1 as AgentTeamsRuntime,RH as AgentTeam,Uu as Agent,z$ as ALL_DEFAULT_TOOL_NAMES};
|
|
711
|
+
`),f.end()}catch{f.destroy()}}function UX(f,$){if(!f||!$)return!1;let J=Buffer.from(f,"utf8"),W=Buffer.from($,"utf8");return J.length===W.length&&gM(J,W)}function GX(f,$){let J=f&&typeof f==="object"&&"code"in f&&typeof f.code==="string"?f.code:void 0,W=f instanceof Error?f.message:typeof f==="string"?f:"Unknown startup error",H=`Failed to start hub server on ${$.host}:${$.port}${$.pathname}: ${W}`,Q=Error(J?`${H} (${J})`:H);if(J)f.code=J,Q.code=J;if(f instanceof Error&&f.stack)Q.stack=`${Q.name}: ${Q.message}
|
|
712
|
+
Caused by: ${f.stack}`;return Q}async function iM(f){return await new Promise(($,J)=>{let W=uM.createServer();W.once("error",J),W.listen(0,f,()=>{let H=W.address();if(!H||typeof H==="string"){W.close(()=>J(Error("Failed to resolve free port")));return}let Q=H.port;W.close((Z)=>{if(Z){J(Z);return}$(Q)})})})}function nM(f){return f instanceof Error&&"code"in f&&f.code==="EADDRINUSE"}var rW=new Map,TX="cline-hub-auth.",aM=30000;function DX(f){return Array.isArray(f)?f.join(","):f??""}function tM(f){let $=DX(f).trim();return/^Bearer\s+(.+)$/i.exec($)?.[1]?.trim()||null}function sM(f){for(let $ of DX(f).split(",")){let J=$.trim();if(J.startsWith(TX))return J.slice(TX.length).trim()||null}return null}async function lW(f){let $=f.owner??j$(),J=f.host??"127.0.0.1",W=f.pathname??"/hub",H=f.port??w8(),Q=H===0?await iM(J):H,Z=Q,j=Q0(J,Q,W),X=d$(),A=H7(),P=new q4(f);await P.start();let B=new cW(new dW(P)),Y=new Set,V=new Date().toISOString(),R={protocolVersion:"v1",buildId:X,pid:process.pid,startedAt:V},U=new Set,K,F,y=async()=>{if(F)return F;return F=(async()=>{if(K)clearInterval(K),K=void 0;for(let _ of U)_.terminate?.();U.clear();for(let _ of Y)_();if(Y.clear(),await new Promise((_,L)=>{M.close((O)=>{if(O){L(O);return}_()})}),await new Promise((_,L)=>{D.close((O)=>{if(O){L(O);return}_()})}),await P.stop(),(await Yf($.discoveryPath))?.url===j)await pf($.discoveryPath)})(),F},D=vM.createServer((T,_)=>{if((T.url??"/")==="/health"){let O=JSON.stringify({hubId:P.getHubId(),...R,authToken:"",host:J,port:Z,url:j,updatedAt:new Date().toISOString()});_.statusCode=200,_.setHeader("content-type","application/json"),_.end(O);return}if((T.url??"/")==="/version"){_.statusCode=200,_.setHeader("content-type","application/json"),_.end(JSON.stringify(R));return}if(new yX(T.url??"/",`http://${J}:${Z}`).pathname==="/shutdown"&&T.method==="POST"){if(!UX(tM(T.headers.authorization),A)){_.statusCode=401,_.end("Unauthorized");return}_.statusCode=202,_.setHeader("content-type","application/json"),_.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{y()});return}_.statusCode=404,_.end("Not found")}),M=new cM({noServer:!0});K=setInterval(()=>{for(let T of U){if(T.isAlive===!1){try{T.terminate?.()}catch{}U.delete(T);continue}T.isAlive=!1;try{T.ping?.()}catch{try{T.terminate?.()}catch{}U.delete(T)}}},aM),D.on("upgrade",(T,_,L)=>{if(new yX(T.url??"/",`http://${J}:${Z}`).pathname!==W){_.destroy();return}if(!UX(sM(T.headers["sec-websocket-protocol"]),A)){pM(_);return}try{M.handleUpgrade(T,_,L,(e)=>{let ff=e;ff.isAlive=!0,ff.on("pong",()=>{ff.isAlive=!0}),U.add(ff);let a=B.attach(rM(e));Y.add(a),e.once("close",()=>{U.delete(ff),a(),Y.delete(a)})})}catch{lM(_)}});try{await new Promise((T,_)=>{D.once("error",(L)=>{_(GX(L,{host:J,port:Q,pathname:W}))}),D.listen(Q,J,()=>{let L=D.address();if(!L||typeof L==="string"){_(GX(Error("Failed to resolve hub port"),{host:J,port:Q,pathname:W}));return}Z=L.port,j=Q0(J,Z,W),T()})})}catch(T){if(K)clearInterval(K),K=void 0;throw await P.stop().catch(()=>{return}),T}return await Q7($.discoveryPath,{hubId:P.getHubId(),protocolVersion:"v1",buildId:X,authToken:A,host:J,port:Z,url:j,pid:process.pid,startedAt:V,updatedAt:V}),{host:J,port:Z,url:j,authToken:A,close:y}}async function _X(f){let $=f.owner??j$(),J=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=f.host??"127.0.0.1",H=f.port??w8(),Q=f.pathname??"/hub",Z=Q0(W,H,Q),j=$.discoveryPath,X=(P)=>{if(!J)r$(P.url,P.authToken);return P},A=rW.get(j);if(A){let P=await A;if(P.url===Z)return X({server:P,url:P.url,authToken:P.authToken,action:"reuse"})}return await Z7($.discoveryPath,async()=>{let P=await Yf($.discoveryPath);if(P?.url&&(P.url===Z||f.allowPortFallback===!0)){let R=await Kf(P.url);if(R?.url&&await w0(R.url,{authToken:P.authToken}))return X({url:R.url,authToken:P.authToken,action:"reuse"})}if((await Kf(Z))?.url||P?.url)await pf($.discoveryPath);let V=async(R)=>{let U=lW({...R,owner:$});rW.set(j,U);try{let K=await U;return X({server:K,url:K.url,authToken:K.authToken,action:"started"})}catch(K){throw rW.delete(j),K}};try{return await V(f)}catch(R){if(!f.allowPortFallback||!nM(R))throw R;return await V({...f,port:0})}})}async function sg(f){let $=q0({host:f.host,port:f.port,pathname:f.pathname});return await lW({...f,...$,owner:yf()})}async function og(f){let $=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=q0({host:f.host,port:f.port,pathname:f.pathname});return await _X({...f,...J,allowPortFallback:f.allowPortFallback??!$,owner:yf()})}pW();import{buildRemoteConfigSessionBlobUploadMetadata as LX,clearRemoteConfigSessionBlobUpload as oM,createClineTelemetryServiceConfig as eM,createSessionId as fL,createRemoteConfigSessionMessagesArtifactUploader as $L,prepareRemoteConfigRuntime as JL,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as hX,readRemoteConfigSessionBlobUploadMetadata as WL,registerRemoteConfigSessionBlobUpload as OX}from"@cline/shared";function HL(f,$){let J=f.telemetry||$.telemetryService?{...$.telemetryService??{},...f.telemetry??{}}:void 0;if(!J)return;return G$(eM(J)).telemetry}function QL(){let f=$L();return{async uploadMessagesFile($){await f.uploadMessagesFile($)}}}async function ZL(f){let $=await JL(f),J=HL($,f),W=[$.pluginDefinition],H=$.claims?.subject,Q=LX($.bundle?.remoteConfig,H),Z;return{prepared:$,extensions:W,telemetry:J,applyToStartSessionInput(j){let X=j.config.extensions??[],A=j.config.telemetry,P=Q?j.config.sessionId?.trim()||fL():j.config.sessionId;if(P&&Q)Z=P;let B=P&&Q?OX(P,$.bundle?.remoteConfig,H):void 0,Y=B?{...j.sessionMetadata??{},[hX]:B}:j.sessionMetadata;return{...j,...Y?{sessionMetadata:Y}:{},config:{...j.config,...P?{sessionId:P}:{},extensions:[...X,...W],telemetry:J??A}}},async dispose(){if(Z)oM(Z)}}}import{mkdir as jL,readFile as XL,unlink as AL,writeFile as PL}from"node:fs/promises";import{join as zX}from"node:path";function BL(f){return f.replace(/[^a-zA-Z0-9._-]+/g,"_")}function YL(f){return new Promise(($)=>setTimeout($,f))}async function iW(f){try{await AL(f)}catch{}}async function VL(f,$={}){let J=$.approvalDir?.trim(),W=$.sessionId?.trim();if(!J||!W)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await jL(J,{recursive:!0});let H=BL(`${f.toolCallId}`),Q=zX(J,`${W}.request.${H}.json`),Z=zX(J,`${W}.decision.${H}.json`),j=$.nowIso??(()=>new Date().toISOString());await PL(Q,`${JSON.stringify({requestId:H,sessionId:W,createdAt:j(),toolCallId:f.toolCallId,toolName:f.toolName,input:f.input,iteration:f.iteration,agentId:f.agentId,conversationId:f.conversationId},null,2)}
|
|
713
|
+
`,"utf8");let X=$.timeoutMs??300000,A=$.pollIntervalMs??200,P=Date.now();while(Date.now()-P<X){try{let B=await XL(Z,"utf8"),Y=JSON.parse(B),V={approved:Y.approved===!0,reason:typeof Y.reason==="string"?Y.reason:void 0};return await Promise.all([iW(Z),iW(Q)]),V}catch{}await YL(A)}return await iW(Q),{approved:!1,reason:"Tool approval request timed out"}}W0();import*as Qf from"@cline/llms";import{getClineEnvironmentConfig as RL,isOAuthProviderId as FL}from"@cline/shared";function KL(f){return f.apiKey??f.auth?.apiKey}function yL(f){return(f.auth?.accessToken?.trim()??"").length>0}function NX(f){return f.split(/[-_]/).filter(Boolean).map(($)=>$.charAt(0).toUpperCase()+$.slice(1)).join(" ")}function UL(f){let $=f.split(/\s+/).filter(Boolean);if($.length===0)return"?";if($.length===1)return $[0].slice(0,2).toUpperCase();return`${$[0][0]}${$[1][0]}`.toUpperCase()}function GL(f){let $=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let W of f)J=J*31+W.charCodeAt(0)>>>0;return $[J%$.length]}function qX(f){return Object.entries(f).sort(([$],[J])=>$.localeCompare(J)).map(([$,J])=>SZ($,J))}async function TL(f,$){let J=await Qf.getModelsForProvider(f);if(!$)return J;let W=await U6(f,{loadPrivateOnAuth:!0,failOnError:!1},$);return W?.knownModels?{...J,...W.knownModels}:J}function nW(f){return[...new Set((f??[]).map(($)=>$.trim()).filter(Boolean))]}function wX(f){let $=Object.entries(f??{}).filter(([J])=>J.trim().length>0);return $.length>0?Object.fromEntries($):void 0}function aW(f,$){let J=$?.includes("vision")??!1,W=$?.includes("reasoning")??!1;return Object.fromEntries(f.map((H)=>[H,{id:H,name:H,supportsVision:J,supportsAttachments:J,supportsReasoning:W}]))}async function bX(f){if(!f.shouldRecompute)return f.fallbackModelIds??[];let $=f.modelsSourceUrl?await z2(f.modelsSourceUrl,f.providerId):[];return[...new Set([...f.explicitModels??[],...$])]}function CX(f,$){let J=f.read(),W=!1;if(J.providers[$])delete J.providers[$],W=!0;if(J.lastUsedProvider===$)delete J.lastUsedProvider,W=!0;if(W)f.write(J);Qf.unregisterProvider($)}async function DL(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=$.baseUrl.trim(),H=$.apiKey?.trim()??"";if(!W&&!H){let R=K$(f);if((await s$(R)).providers[J]){let K=await SX(f,{providerId:J});return{providerId:J,settingsPath:K.settingsPath,modelsPath:K.modelsPath,modelsCount:0}}return CX(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:R,modelsCount:0}}if(Qf.hasProvider(J))throw Error(`provider "${J}" already exists`);let Q=$.name.trim();if(!Q)throw Error("name is required");if(!W)throw Error("baseUrl is required");let Z=nW($.models),j=$.modelsSourceUrl?.trim(),X=await bX({providerId:J,explicitModels:Z,modelsSourceUrl:j,shouldRecompute:!0});if(X.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let A=$.defaultModelId?.trim()&&X.includes($.defaultModelId.trim())?$.defaultModelId.trim():X[0],P=$.capabilities?.length?[...new Set($.capabilities)]:void 0,B=wX($.headers);f.saveProviderSettings({provider:J,apiKey:H||void 0,baseUrl:W,headers:B,timeout:$.timeoutMs,model:A,protocol:$.protocol,client:$.client},{setLastUsed:!1});let Y=K$(f),V=await s$(Y);return V.providers[J]={provider:{name:Q,baseUrl:W,defaultModelId:A,protocol:$.protocol,client:$.client,capabilities:P,modelsSourceUrl:j},models:aW(X,P)},await J4(Y,V),J2(J,V.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:Y,modelsCount:X.length}}async function EX(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=K$(f),H=await s$(W),Q=H.providers[J];if(!Q){let M=f.getProviderSettings(J);if(!M)throw Error(`provider "${J}" does not exist`);let T=$.modelsSourceUrl?.trim(),_=nW($.models)[0]??M.model?.trim();if(!_&&!T)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:$.name?.trim()||NX(J),baseUrl:$.baseUrl?.trim()??M.baseUrl?.trim()??"",defaultModelId:_,protocol:M.protocol,client:M.client,capabilities:M.capabilities},models:_?aW([_],M.capabilities):{}}}if(!Q.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let Z=$.name?.trim()??Q.provider.name.trim();if(!Z)throw Error("name is required");let j=$.baseUrl?.trim()??Q.provider.baseUrl.trim();if(!j)throw Error("baseUrl is required");let X=$.capabilities===void 0?Q.provider.capabilities:$.capabilities===null?void 0:[...new Set($.capabilities)],A=$.protocol===void 0?Q.provider.protocol:$.protocol??void 0,P=$.client===void 0?Q.provider.client:$.client??void 0,B=nW($.models),Y=$.modelsSourceUrl===void 0?Q.provider.modelsSourceUrl:$.modelsSourceUrl?.trim()||void 0,V=$.models!==void 0||$.modelsSourceUrl!==void 0&&!!Y,R=Object.keys(Q.models??{}).map((M)=>M.trim()).filter(Boolean),U=await bX({providerId:J,explicitModels:B,modelsSourceUrl:Y,fallbackModelIds:R,shouldRecompute:V});if(U.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let K=$.defaultModelId===void 0?Q.provider.defaultModelId?.trim():$.defaultModelId?.trim(),F=K&&U.includes(K)?K:U[0],D={...f.getProviderSettings(J)??{},provider:J,baseUrl:j,model:F};if(A)D.protocol=A;else delete D.protocol;if(P)D.client=P;else delete D.client;if($.apiKey!==void 0){let M=$.apiKey?.trim()??"";if(M)D.apiKey=M;else delete D.apiKey}if($.headers!==void 0){let M=wX($.headers);if(M)D.headers=M;else delete D.headers}if($.timeoutMs!==void 0)if(typeof $.timeoutMs==="number")D.timeout=$.timeoutMs;else delete D.timeout;return f.saveProviderSettings(D,{setLastUsed:!1}),H.providers[J]={provider:{name:Z,baseUrl:j,defaultModelId:F,protocol:A,client:P,capabilities:X,modelsSourceUrl:Y},models:aW(U,X)},await J4(W,H),J2(J,H.providers[J]),{providerId:J,settingsPath:f.getFilePath(),modelsPath:W,modelsCount:U.length}}async function SX(f,$){let J=$.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=K$(f),H=await s$(W);if(!H.providers[J])throw Error(`provider "${J}" does not exist`);return delete H.providers[J],await J4(W,H),Qf.unregisterProvider(J),CX(f,J),{providerId:J,settingsPath:f.getFilePath(),modelsPath:W}}async function _L(f){let $=f.read(),J=Qf.getProviderIds().sort((H,Q)=>H.localeCompare(Q));return{providers:await Promise.all(J.map(async(H)=>{let[Q,Z]=await Promise.all([Qf.getProvider(H),Qf.getModelsForProvider(H)]),j=qX(Z),X=$.providers[H]?.settings,A=Q?.name??NX(H);return{id:H,name:A,models:j.length,color:GL(H),letter:UL(A),enabled:Boolean(X),apiKey:X?KL(X):void 0,oauthAccessTokenPresent:X?yL(X):void 0,baseUrl:X?.baseUrl??Q?.baseUrl,defaultModelId:Q?.defaultModelId,protocol:X?.protocol??Q?.protocol,client:X?.client??Q?.client,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",modelList:j}})),settingsPath:f.getFilePath()}}async function ML(f,$){let J=f.trim(),W=await TL(J,$),H=qX(W);return{providerId:J,models:H}}function LL(f,$){let J=$.providerId.trim();if($.enabled===!1){let Q=f.read();if(delete Q.providers[J],Q.lastUsedProvider===J)delete Q.lastUsedProvider;return f.write(Q),{providerId:J,enabled:!1,settingsPath:f.getFilePath()}}let H={...f.getProviderSettings(J)??{},provider:J};for(let Q of["apiKey","baseUrl","model","region"])if(Object.hasOwn($,Q)&&typeof $[Q]==="string")if($[Q].trim().length===0)delete H[Q];else H[Q]=$[Q];for(let Q of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn($,Q))H[Q]=$[Q];for(let Q of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn($,Q)&&$[Q]!=null)H[Q]={...typeof H[Q]==="object"&&H[Q]!=null?H[Q]:{},...$[Q]};return f.saveProviderSettings(H,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:f.getFilePath()}}async function hL(f,$){let J=$.trim(),W=f.getProviderSettings(J),Q=Qf.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,Z=W?.baseUrl?.trim()||Q?.baseUrl?.trim(),j=N2(Z,Q?.baseUrl,Q?.modelsSourceUrl);if(!W||!Q||!Z||!j)return{providerId:J,refreshed:!1};let X=await EX(f,{providerId:J,name:Q.name,baseUrl:Z,apiKey:W.apiKey,headers:W.headers??null,timeoutMs:W.timeout??null,modelsSourceUrl:j,protocol:W.protocol??Q.protocol??null,client:W.client??Q.client??null,capabilities:W.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:X.modelsCount}}function OL(f){let $=f.trim().toLowerCase();if($==="codex"||$==="openai-codex")return"openai-codex";if($==="cline"||$==="oca")return $;throw Error(`provider "${f}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function zL(f,$){if(f==="cline")return $.access.startsWith("workos:")?$.access:`workos:${$.access}`;return $.access}async function NL(f,$,J){let W=S4({onPrompt:async(H)=>H.defaultValue??"",openUrl:J,onOpenUrlError:({error:H})=>{throw H instanceof Error?H:Error(String(H))}});if(f==="cline")return _2({apiBaseUrl:$?.baseUrl?.trim()||RL().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:W});if(f==="oca")return O2({mode:$?.oca?.mode,callbacks:W});return L2(W)}function qL(f,$,J,W){let H={...J?.auth??{},accessToken:zL($,W),refreshToken:W.refresh,accountId:W.accountId,expiresAt:W.expires},Q={...J??{provider:$},provider:$,auth:H};return f.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function wL(f){let $=f?.auth?.accessToken?.trim()||f?.apiKey?.trim();return $&&$.length>0?$:void 0}var bL=new Set(["ollama","lmstudio","litellm"]);function CL(f,$){if(!$?.provider.baseUrl)return!1;if($.provider.source!=="system")return!0;return bL.has(f)}function EL(f){let $=Qf.normalizeProviderId(f);if(FL($))return{providerId:$,authMethod:"oauth",fields:{}};let J=Qf.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=J?.provider.baseUrl,H={apiKey:{}};if(CL($,J))H.baseUrl={defaultValue:W};return{providerId:$,authMethod:"api-key",fields:H}}Uf();L4();import{appendFileSync as SL,existsSync as tW,mkdirSync as kL,readFileSync as IL,renameSync as mL,unlinkSync as xL,writeFileSync as gL}from"node:fs";import{join as sW}from"node:path";import{resolveTeamDataDir as vL}from"@cline/shared/storage";function uL(f){return f.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class kX{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor(f){let $=uL(f.teamName),J=f.baseDir?.trim()||vL();this.dirPath=sW(J,$),this.statePath=sW(this.dirPath,"state.json"),this.taskHistoryPath=sW(this.dirPath,"task-history.jsonl")}loadState(){if(!tW(this.statePath))return;try{let f=IL(this.statePath,"utf8"),$=JSON.parse(f);if($.version!==1||!$.teamState)return;for(let J of $.teammates??[])this.teammateSpecs.set(J.agentId,J);return r7($.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec(f){this.teammateSpecs.set(f.agentId,f)}removeTeammateSpec(f){this.teammateSpecs.delete(f)}persist(f){if(!this.hasPersistableState(f)){this.clearPersistedState();return}this.ensureDir();let $={version:1,updatedAt:new Date().toISOString(),teamState:f.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;gL(J,`${JSON.stringify($,null,2)}
|
|
714
|
+
`,"utf8"),mL(J,this.statePath)}appendTaskHistory(f){let $={};switch(f.type){case"team_task_updated":$=f.task;break;case"team_message":$={agentId:f.message.fromAgentId,toAgentId:f.message.toAgentId,subject:f.message.subject,taskId:f.message.taskId};break;case"team_mission_log":$={agentId:f.entry.agentId,kind:f.entry.kind,summary:f.entry.summary,taskId:f.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":$={agentId:f.agentId,message:"message"in f?f.message:void 0};break;case"task_end":$={agentId:f.agentId,finishReason:f.result?.finishReason,error:f.error?.message};break;case"agent_event":$={agentId:f.agentId,eventType:f.event.type};break}this.ensureDir(),SL(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:f.type,task:$})}
|
|
715
|
+
`,"utf8")}ensureDir(){if(!tW(this.dirPath))kL(this.dirPath,{recursive:!0})}hasPersistableState(f){let $=f.exportState();if(this.teammateSpecs.size>0)return!0;if($.members.some((J)=>J.role==="teammate"))return!0;return $.tasks.length>0||$.mailbox.length>0||$.missionLog.length>0}clearPersistedState(){if(tW(this.statePath))xL(this.statePath)}}import{z}from"zod";var IX=z.object({workspaceRoot:z.string().min(1),cwd:z.string().optional(),provider:z.string().min(1),model:z.string().min(1),mode:z.enum(["act","plan"]).default("act"),apiKey:z.string(),systemPrompt:z.string().optional(),rules:z.string().optional(),maxIterations:z.number().int().positive().optional(),enableTools:z.boolean(),enableSpawn:z.boolean().optional(),enableTeams:z.boolean().optional(),autoApproveTools:z.boolean().optional(),missionStepInterval:z.number().int().positive().optional(),missionTimeIntervalMs:z.number().int().positive().optional()}),mX=z.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),xX=z.enum(["user","assistant","tool","system","status","error"]),gX=z.object({id:z.string().min(1),sessionId:z.string().nullable(),role:xX,content:z.string(),createdAt:z.number().int().nonnegative(),meta:z.object({stream:z.enum(["stdout","stderr"]).optional(),toolName:z.string().optional(),iteration:z.number().int().nonnegative().optional(),agentId:z.string().optional(),conversationId:z.string().optional(),hookEventName:z.string().optional(),inputTokens:z.number().int().nonnegative().optional(),outputTokens:z.number().int().nonnegative().optional(),checkpoint:z.object({ref:z.string(),createdAt:z.number().int().nonnegative(),runCount:z.number().int().positive(),kind:z.enum(["stash","commit"]).optional()}).optional()}).optional()}),vX=z.object({toolCalls:z.number().int().nonnegative(),tokensIn:z.number().int().nonnegative(),tokensOut:z.number().int().nonnegative()}),cL=z.object({sessionId:z.string().nullable(),status:mX,config:IX,messages:z.array(gX),rawTranscript:z.string(),error:z.string().nullable(),summary:vX});var dL=sQ;import{Agent as Vc,createAgentRuntime as Rc}from"@cline/agents";import{getClineEnvironmentConfig as rL}from"@cline/shared";var lL=5000,cX={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 pL(f){return{recommended:f.recommended.map(($)=>({...$,tags:[...$.tags]})),free:f.free.map(($)=>({...$,tags:[...$.tags]}))}}function uX(f){if(!f||typeof f!=="object")return null;let $=f;if(typeof $.id!=="string"||$.id.length===0)return null;return{id:$.id,name:typeof $.name==="string"&&$.name.length>0?$.name:$.id,description:typeof $.description==="string"?$.description:"",tags:Array.isArray($.tags)?$.tags.filter((J)=>typeof J==="string"):[]}}function iL(f){if(!f||typeof f!=="object")return null;let $=f,J=Array.isArray($.recommended)?$.recommended:[],W=Array.isArray($.free)?$.free:[],H=J.map(uX).filter((Z)=>Z!==null),Q=W.map(uX).filter((Z)=>Z!==null);if(H.length===0&&Q.length===0)return null;return{recommended:H,free:Q}}function nL(f){let $=f.baseUrl?.trim();if($)return $;let J=rL().apiBaseUrl;try{return(f.providerSettingsManager??new x0).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function aL(f,$,J){let W=new AbortController,H=setTimeout(()=>W.abort(),J);try{return await f($,{signal:W.signal})}finally{clearTimeout(H)}}async function tL(f={}){try{let $=nL(f),J=f.fetchImpl??fetch,W=await aL(J,`${$}/api/v1/ai/cline/recommended-models`,f.timeoutMs??lL);if(!W.ok)throw Error(`HTTP ${W.status}`);let H=await W.json(),Q=iL(H);if(Q)return Q}catch{}return pL(cX)}import{readFile as sL}from"node:fs/promises";import oL from"node:path";function eL(f){return f}async function fh(f){let $=oL.resolve(f),J=await sL($,"utf8"),W;try{W=JSON.parse(J)}catch(H){let Q=H instanceof Error?H.message:String(H);throw Error(`Failed to parse JSON config at "${$}": ${Q}`)}return $h(W,$)}function $h(f,$){if(!f||typeof f!=="object")throw Error(`Invalid llms config in "${$}": expected an object.`);let W=f.providers;if(!Array.isArray(W))throw Error(`Invalid llms config in "${$}": "providers" must be an array.`);if(!W.length)throw Error(`Invalid llms config in "${$}": "providers" cannot be empty.`);return f}import{BUILT_IN_PROVIDER_IDS as lX,createHandler as Hh,createHandlerAsync as Qh,getProviderCollection as Zh,hasProvider as pX,registerAsyncHandler as jh,registerHandler as Xh,registerModel as Ah,registerProvider as iX}from"@cline/llms";function dX(f){return f?{...f}:{}}function Jh(f,$){if(f)return f;if(!$)return;let J=globalThis.process;if(!J?.env)return;return J.env[$]}function Wh(f,$){if(!$.length)throw Error(`Provider "${f}" must include at least one model.`)}function rX(f){let $=Object.keys(f.collection.models);return{id:f.collection.provider.id,name:f.collection.provider.name,description:f.collection.provider.description,protocol:f.collection.provider.protocol,baseUrl:f.collection.provider.baseUrl,capabilities:f.collection.provider.capabilities,env:f.collection.provider.env,models:$,defaultModel:f.collection.provider.defaultModelId,modelCount:$.length}}class oW{providers=new Map;register(f){Wh(f.id,f.models);let $=f.defaultModel??f.models[0];if(!$)throw Error(`Provider "${f.id}" must define a default model.`);if(!f.models.includes($))throw Error(`Default model "${$}" is not included in configured models for "${f.id}".`);let J=this.providers.get(f.id);this.providers.set(f.id,{id:f.id,models:new Set([...J?.models??[],...f.models]),defaultModel:$,defaults:{...J?.defaults??{},...dX(f.defaults)}})}registerSelectionConfig(f){this.register({id:f.id,models:f.models,defaultModel:f.defaultModel,defaults:{apiKey:Jh(f.apiKey,f.apiKeyEnv),routingProviderId:f.builtinProviderId,baseUrl:f.baseUrl,headers:f.headers,timeoutMs:f.timeoutMs,capabilities:f.capabilities,...dX(f.settings)}})}registerModel(f,$){let J=this.providers.get(f);if(!J){this.providers.set(f,{id:f,models:new Set([$]),defaultModel:$,defaults:{}});return}J.models.add($)}createHandlerConfig(f){let $=this.require(f.providerId),J=f.modelId??$.defaultModel;if(!$.models.has(J))throw Error(`Model "${J}" is not configured for provider "${f.providerId}".`);return{providerId:f.providerId,modelId:J,...$.defaults,...f.overrides}}list(){return Array.from(this.providers.values()).map((f)=>({id:f.id,models:Array.from(f.models),defaultModel:f.defaultModel}))}getModels(f){return Array.from(this.require(f).models)}hasProvider(f){return this.providers.has(f)}hasModel(f,$){return this.providers.get(f)?.models.has($)??!1}require(f){let $=this.providers.get(f);if(!$)throw Error(`Provider "${f}" is not configured in this SDK instance.`);return $}}class eW{configuredProviders=new oW;constructor(f){this.applyConfig(f)}createHandler(f){return Hh(this.configuredProviders.createHandlerConfig(f))}async createHandlerAsync(f){return Qh(this.configuredProviders.createHandlerConfig(f))}registerProvider(f){if(iX(f.collection),f.handlerFactory&&f.asyncHandlerFactory)throw Error(`Provider "${f.collection.provider.id}" cannot register both sync and async handlers.`);if(f.handlerFactory)Xh(f.collection.provider.id,f.handlerFactory);if(f.asyncHandlerFactory)jh(f.collection.provider.id,f.asyncHandlerFactory);this.configuredProviders.register({id:f.collection.provider.id,models:f.exposeModels??Object.keys(f.collection.models),defaultModel:f.defaultModel??f.collection.provider.defaultModelId,defaults:f.defaults})}registerBuiltinProvider(f){let $=f.exposeModels??Object.keys(f.models),J=f.defaultModel??$[0];if(!J)throw Error(`Provider "${f.id}" must define a default model.`);iX({provider:{id:f.id,name:f.name??f.id,description:f.description,protocol:f.protocol,baseUrl:f.baseUrl,defaultModelId:J,client:f.client??"openai-compatible",capabilities:f.capabilities,env:f.env,source:"system"},models:f.models}),this.configuredProviders.register({id:f.id,models:$,defaultModel:J,defaults:{routingProviderId:f.builtinProviderId,...f.defaults??{}}})}registerModel(f){Ah(f.providerId,f.modelId,f.info),this.configuredProviders.registerModel(f.providerId,f.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...lX]}async getBuiltInProviders(){return(await Promise.all(lX.map(($)=>Zh($)))).filter(($)=>$!==void 0).map(($)=>rX({collection:$}))}getModels(f){return this.configuredProviders.getModels(f)}isProviderConfigured(f){return this.configuredProviders.hasProvider(f)}isModelConfigured(f,$){return this.configuredProviders.hasModel(f,$)}applyConfig(f){for(let $ of f.providers)this.configuredProviders.registerSelectionConfig($);for(let $ of f.models??[])this.registerModel($);for(let $ of f.customProviders??[])this.registerProvider($);for(let $ of this.configuredProviders.list()){let J=pX($.id),W=this.configuredProviders.createHandlerConfig({providerId:$.id,modelId:$.defaultModel}).routingProviderId,H=typeof W==="string"&&pX(W);if(!J&&!H)throw Error(`Provider "${$.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function Ph(f){return new eW(f)}qW();async function $u(){return Promise.resolve().then(() => (pW(),MX))}export{Q7 as writeHubDiscovery,x$ as writeGlobalSettings,Z7 as withHubStartupLock,w0 as verifyHubConnection,EX as updateLocalProvider,EW as truncateNotificationBody,XJ as toggleDisabledTool,v8 as toTeamProgressLifecycleEvent,f0 as toProviderConfig,GK as toHubHealthUrl,i5 as toHookConfigFileName,r8 as summarizeUsageFromMessages,Dy as stopLocalHubServerGracefully,r0 as startLocalOAuthServer,lW as startHubWebSocketServer,sg as startHubServer,KA as startClineDeviceAuth,OJ as splitCoreSessionConfig,b8 as spawnDetachedHubServerWithRetry,fy as spawnDetachedHubServer,DV as setTelemetryOptOutGlobally,d3 as setDisabledTools,LV as setDisabledPlugin,im as sendHubCommand,LL as saveLocalProviderSettings,qL as saveLocalProviderOAuthCredentials,I1 as sanitizeSessionToken,pH as safeParseSettings,NP as safeCreateProviderConfig,R4 as runSubprocessEvent,K4 as runHook,q3 as reviveTeamStateDates,G7 as restartLocalHubIfIdleAfterStartupTimeout,Ab as resolveWorkspaceHubOwnerContext,k6 as resolveWorkflowsConfigSearchPaths,E6 as resolveSkillsConfigSearchPaths,yf as resolveSharedHubOwnerContext,J_ as resolveSessionBackend,S6 as resolveRulesConfigSearchPaths,U6 as resolveProviderConfig,DJ as resolvePluginConfigSearchPaths,BW as resolveMcpServerRegistrations,wL as resolveLocalClineAuthToken,a_ as resolveHubUrl,j$ as resolveHubOwnerContext,q0 as resolveHubEndpointOptions,d$ as resolveHubBuildId,l5 as resolveHooksConfigSearchPaths,rf as resolveDisabledToolNames,V8 as resolveDisabledPluginPaths,f1 as resolveDefaultMcpSettingsPath,w8 as resolveDefaultHubPort,wK as resolveDefaultHubPathname,qK as resolveDefaultHubHost,E3 as resolveCoreSelectedToolIds,F5 as resolveCompatibleLocalHubUrl,fb as resolveClineDir,A5 as resolveClineDataDir,U8 as resolveAndLoadAgentPlugins,O1 as resolveAgentPluginPaths,P5 as requestHubShutdown,VL as requestDesktopToolApproval,r$ as rememberRecoverableLocalHubUrl,OX as registerRemoteConfigSessionBlobUpload,Z4 as registerMcpServersFromSettingsFile,Ku as registerDisposable,hL as refreshProviderModelsFromSource,J6 as refreshOpenAICodexToken,X6 as refreshOcaToken,f6 as refreshClineToken,ZW as readSessionCheckpointHistory,WL as readRemoteConfigSessionBlobUploadMetadata,Yf as readHubDiscovery,J0 as readGlobalSettings,Kf as probeHubServer,pm as probeHubConnection,g9 as prewarmFileIndex,A7 as prewarmDetachedHubServer,ZL as prepareRemoteConfigCoreIntegration,C6 as parseWorkflowConfigFromMarkdown,Fu as parseUserCommandEnvelope,w6 as parseSkillConfigFromMarkdown,lH as parseSettings,b6 as parseRuleConfigFromMarkdown,F4 as parseHookEventPayload,OA as openaiCodexOAuthProvider,J$ as normalizeWorkspacePath,Ru as normalizeUserInput,Ff as normalizeRuntimeCapabilities,C2 as normalizeProviderId,hA as normalizeOpenAICodexCredentials,OL as normalizeOAuthProvider,l$ as normalizeHubWebSocketUrl,Vu as noopBasicLogger,WW as migrateLegacyProviderSettings,g2 as mergeRulesForSystemPrompt,$2 as mergeAgentHooks,nJ as makeTeamTaskSubSessionId,L8 as makeSubSessionId,L2 as loginOpenAICodex,O2 as loginOcaOAuth,NL as loginLocalProvider,_2 as loginClineOAuth,$u as loadOpenTelemetryAdapter,PW as loadMcpSettingsFile,fh as loadLlmsConfigFromFile,$$ as loadAgentPluginsFromPathsWithDiagnostics,HQ as loadAgentPluginsFromPaths,UJ as loadAgentPluginFromPath,HK as listSessionHistoryFromBackend,MJ as listPluginTools,_L as listLocalProviders,a$ as listHookConfigFiles,_V as isToolDisabledGlobally,jJ as isTelemetryOptedOutGlobally,Z9 as isRuleEnabled,MV as isPluginDisabledGlobally,LA as isOpenAICodexTokenExpired,Ry as isHubReconnectableTransportError,y7 as isHubCommandTimeoutError,Wb as isDiscoveryFilePresent,QH as isClineAccountActionRequest,LP as isBuiltInProviderId,K0 as identifyAccount,Q4 as hasMcpSettingsFile,W6 as getValidOpenAICodexCredentials,A6 as getValidOcaCredentials,$6 as getValidClineCredentials,EL as getProviderConfigFields,SH as getProviderConfig,ML as getLocalProviderModels,b2 as getLiveModelsCatalog,t0 as getFileIndex,fG as getCurrentContextSize,ZJ as getCoreHeadlessToolNames,C3 as getCoreDefaultEnabledToolIds,T1 as getCoreBuiltinToolCatalog,S3 as getCoreAcpToolNames,Qu as getClineDefaultSystemPrompt,bJ as generateWorkspaceInfoWithDiagnostics,_8 as generateWorkspaceInfo,OH as generateOcaOpcRequestId,x2 as formatRulesForSystemPrompt,Yu as formatDisplayUserInput,PJ as filterExtensionToolRegistrations,g$ as filterDisabledTools,AJ as filterDisabledPluginPaths,tL as fetchClineRecommendedModels,ZH as executeClineAccountAction,_X as ensureHubWebSocketServer,og as ensureHubServer,Tb as ensureDetachedHubServer,vZ as ensureCustomProvidersLoaded,d1 as ensureCompatibleLocalHubUrl,f8 as enrichPromptWithMentions,Bu as emptyWorkspaceManifest,t$ as emptyStoredProviderSettings,_J as discoverPluginModulePaths,aJ as deriveSubsessionStatus,SX as deleteLocalProvider,eL as defineLlmsConfig,x6 as createWorkflowsConfigDefinition,m$ as createUserInstructionConfigService,d9 as createToolPoliciesWithPreset,Pu as createTool,Rj as createTeamName,zj as createSubprocessHooks,I$ as createSpawnAgentTool,I6 as createSkillsConfigDefinition,V4 as createSessionHost,V4 as createRuntimeHost,m6 as createRulesConfigDefinition,QL as createRemoteConfigSessionMessagesArtifactUploader,zP as createProviderConfig,_4 as createOpenTelemetryTelemetryService,iA as createOcaRequestHeaders,pA as createOcaOAuthProvider,S4 as createOAuthClientCallbacks,X4 as createMcpTools,Hx as createLocalHubScheduleRuntimeHandlers,Ph as createLlmsSdk,Vf as createInitialAccumulatedUsage,Jb as createInMemoryHubOwnerContext,Q0 as createHubServerUrl,H7 as createHubAuthToken,s5 as createHookConfigFileHooks,t8 as createHookConfigFileExtension,a8 as createHookAuditHooks,YW as createDisabledMcpToolPolicy,Zj as createDisabledMcpToolPolicies,Z8 as createDelegatedAgentConfigProvider,j8 as createDelegatedAgent,r9 as createDefaultToolsWithPreset,E$ as createDefaultTools,H4 as createDefaultMcpServerClientFactory,H8 as createDefaultExecutors,z1 as createCoreSettingsService,b0 as createCoreSessionSnapshot,Au as createContributionRegistry,c5 as createContextCompactionPrepareTurn,G$ as createConfiguredTelemetryService,M4 as createConfiguredTelemetryHandle,Xu as createClineTelemetryServiceMetadata,ju as createClineTelemetryServiceConfig,UA as createClineOAuthProvider,D1 as createBuiltinTools,G1 as createAgentTeamsTools,Rc as createAgentRuntime,l8 as createAgentHooksExtension,Cj as connectToHub,yA as completeClineDeviceAuth,DP as clearPrivateModelsCatalogCache,TP as clearLiveModelsCatalogCache,pf as clearHubDiscovery,WA as captureWorkspacePathResolved,k4 as captureWorkspaceInitialized,I4 as captureWorkspaceInitError,u4 as captureToolUsage,g4 as captureTokenUsage,x4 as captureTaskRestarted,m4 as captureTaskCreated,K2 as captureTaskCompleted,U2 as captureSubagentExecution,c4 as captureSkillUsed,y2 as captureProviderApiError,v4 as captureModeSwitch,r4 as captureMentionUsed,p4 as captureMentionSearchResults,l4 as captureMentionFailed,n4 as captureHookDiscovery,JA as captureExtensionActivated,d4 as captureDiffEditFailure,Q1 as captureConversationTurnEvent,R0 as captureAuthSucceeded,V0 as captureAuthStarted,c0 as captureAuthLoggedOut,F0 as captureAuthFailed,i4 as captureAgentTeamCreated,d0 as captureAgentCreated,CJ as buildWorkspaceMetadata,g8 as buildTeamProgressSummary,LX as buildRemoteConfigSessionBlobUploadMetadata,y1 as buildDelegatedAgentConfig,P8 as bootstrapAgentTeams,DL as addLocalProvider,Xf as accumulateUsageTotals,O6 as WORKFLOWS_CONFIG_DIRECTORY_NAME,A1 as UnifiedConfigFileWatcher,df as ToolPresets,P2 as TelemetryService,D4 as TelemetryLoggerSink,A8 as TEAM_TOOL_NAMES,F8 as SubprocessSandbox,o8 as StoredProviderSettingsSchema,_Z as StoredProviderSettingsEntrySchema,Q2 as SqliteTeamStore,E0 as SqliteSessionStore,e$ as SessionVersioningService,gf as SessionVersioningError,Rf as SessionSource,cH as SapSettingsSchema,h6 as SKILLS_CONFIG_DIRECTORY_NAME,D6 as SESSION_STATUSES,E4 as RpcClineAccountService,E8 as RemoteRuntimeHost,xH as ReasoningSettingsSchema,f9 as RULES_CONFIG_DIRECTORY_NAME,hX as REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY,q$ as ProviderSettingsSchema,x0 as ProviderSettingsManager,kH as ProviderProtocolSchema,T6 as ProviderIdSchema,IH as ProviderClientSchema,B2 as OpenTelemetryProvider,dH as OcaSettingsSchema,y6 as OPENAI_COMPATIBLE_PROVIDERS,Z0 as NodeHubClient,dW as NativeHubTransportAdapter,rH as ModelCatalogSettingsSchema,g0 as LocalRuntimeHost,Wu as Llms,e8 as InMemoryWorkspaceManager,H2 as InMemoryMcpManager,fM as HubUIClient,bf as HubTransportError,e_ as HubSessionClient,q4 as HubServerTransport,T4 as HubScheduleService,y4 as HubScheduleCommandService,P$ as HubRuntimeHost,C8 as HubCommandError,hj as HookEventPayloadSchema,Lj as HookEventNameSchema,p8 as HookConfigFileName,p5 as HOOK_CONFIG_FILE_EVENT_MAP,VZ as HOOKS_CONFIG_DIRECTORY_NAME,Y8 as GlobalSettingsSchema,vH as GcpSettingsSchema,kX as FileTeamPersistenceStore,cX as FALLBACK_CLINE_RECOMMENDED_MODELS,Hf as DefaultToolNames,P4 as DefaultRuntimeBuilder,eW as DefaultLlmsSdk,bH as DEFAULT_MODELS_CATALOG_URL,zK as DEFAULT_HUB_PORT,NK as DEFAULT_HUB_PATHNAME,OK as DEFAULT_HUB_HOST,c$ as CoreSettingsService,S0 as CoreSessionService,Zu as ContributionRegistry,NW as ClineCore,C4 as ClineAccountService,cL as ChatViewStateSchema,vX as ChatSummarySchema,mX as ChatSessionStatusSchema,IX as ChatSessionConfigSchema,gX as ChatMessageSchema,xX as ChatMessageRoleSchema,x as CORE_TELEMETRY_EVENTS,dL as CORE_BUILD_VERSION,cW as BrowserWebSocketHubAdapter,MP as BUILT_IN_PROVIDER_IDS,G6 as BUILT_IN_PROVIDER,uH as AzureSettingsSchema,gH as AwsSettingsSchema,mH as AuthSettingsSchema,n1 as AgentTeamsRuntime,h5 as AgentTeam,Vc as Agent,b$ as ALL_DEFAULT_TOOL_NAMES};
|